Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Java Servlet :Example of Cookies
Previous Home Next

A cookie represents textual information in the form of key value pair that is sent by the server as part of the response to the client machine and is sent by the clien to the server with substituent requests.Cookies provide a simple mechanism for maintaining information between requests.This example shows you how to create the cookies using the JDBCand servlet.

index.html:-

<html>
	<head>
	  <title>My Second Web Application</title>
	</head>
	<body>
	 <form method="get" action="application">
	 <b>Name<input type="text" name="txtName">
	 <br><input type="submit" value="Login"></form>
	</body>
</html>

web.xml

<web-app>
	<servlet>
	 <servlet-name>s1</servlet-name>
	 <servlet-class>WelcomeServlet</servlet-class>
	</servlet>
	<servlet-mapping>
	 <servlet-name>s1</servlet-name>
	 <url-pattern>application</url-pattern>
	</servlet-mapping>
	<servlet>
	 <servlet-name>s2</servlet-name>
	 <servlet-class>TourServlet</servlet-class>
	</servlet>
	<servlet-mapping>
	 <servlet-name>s2</servlet-name>
	 <url-pattern>toursevlet</url-pattern>
	</servlet-mapping>
</web-app>

TourServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class TourServlet extends HttpServlet
{
 public void doGet(HttpServletRequest req,
 HttpServletResponse res)throws ServletException,IOException
 {
  String name="Guest";
  Cookie cks[]=req.getCookies();
  if(cks!=null)
  name=cks[0].getValue();
  res.setContentType("text/html");
  PrintWriter out=res.getWriter();
  out.println("Sorry,"+name);
  out.println("<br>down for routine maintainance,pls visit again later");
  out.close();
 }
}

WelcomeServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet
{
	public void doGet(HttpServletRequest req,
	 HttpServletResponse res)throws ServletException,IOException
	{
	String name=req.getParameter("txtName");
	Cookie cks=new Cookie("username",name);
	cks.setMaxAge(6000);
	res.addCookie(cks);
	res.setContentType("text/html");
	PrintWriter out=res.getWriter();
	out.println("welcome," +name);
	out.println("<br><form action=toursevlet>");
	out.println("<br><input type=submit  value=\"Take a tour\">");
	out.println("<br></form>");
	out.close();
	}
}
Previous Home Next