Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

Java Servlet :Example of Session
Previous Home Next

This example shows you how we use the session in the 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
 {
  HttpSession session=req.getSession();
  String name=(String)session.getAttribute("name");
  res.setContentType("text/html");
  PrintWriter out=res.getWriter();
  out.println("Sorry,"+name);
  out.println("<br> Site is 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");
  HttpSession session=req.getSession();
  session.setAttribute("name",name);
  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

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: