Tutorial
Menus

Servlet - Servlet Basics

User Authentication via Sessions

Rating: 0.0/5 (0 votes cast)

Level   : Beginners
Author : Arunkumar S
Download Source : SessionAuthServlet.java

User Authentication via Sessions

Sessions can also be used for authentication. In contrast to HTTP Basic Authentication a session can be invalidated which enables users to log out without quitting the Web Browser (which is required with Basic Authentication because there is no way to force a browser to delete the authentication credentials).

The sessions were created as needed and only used to identify an anonymous user.

The following SessionAuthServlet shows how to do authentication with a Servlet. The doPost method processes requests to log in or out. sendPage is called by both, doGet and doPost.

SessionAuthServlet.java

1: import java.io.*;
2: import javax.servlet.*;
3: import javax.servlet.http.*;
4:
5: public final class SessionAuthServlet extends HttpServlet
6: {
7: protected void doGet(HttpServletRequest req, HttpServletResponse res)
8: throws ServletException, IOException
9: {
10: sendPage(req, res, req.getSession(false));
11: }
12:
13: protected void doPost(HttpServletRequest req, HttpServletResponse res)
14: throws ServletException, IOException
15: {
16: if(req.getParameter("login") != null)
17: {
18: HttpSession session = req.getSession(true);
19: String name = req.getParameter("name");
20: if(name == null || name.length()==0) name = "Anonymous";
21: session.putValue("name", name);
22: sendPage(req, res, session);
23: }
24: else
25: {
26: HttpSession session = req.getSession(false);
27: if(session != null) session.invalidate();
28: sendPage(req, res, null);
29: }
30: }
31:
32: private void sendPage(HttpServletRequest req, HttpServletResponse res,
33: HttpSession session)
34: throws ServletException, IOException
35: {
36: res.setContentType("text/html");
37: res.setHeader("pragma", "no-cache");
38: PrintWriter o = res.getWriter();
39: o.print("<HTML><HEAD><TITLE>SessionAuthServlet</TITLE></HEAD><BODY>");
40: if(session == null)
41: o.print("<FORM METHOD=POST>Please enter your name: "+
42: "<INPUT TYPE=TEXT NAME=\"name\">"+
43: "<INPUT TYPE=SUBMIT NAME=\"login\" VALUE=\"Log in\">"+
44: "</FORM></BODY></HTML>");
45: else
46: o.print("Hi " + session.getValue("name") +
47: "<P><FORM METHOD=POST><INPUT TYPE=SUBMIT NAME=\"logout\" "+
48: "VALUE=\"Log out\"></FORM></BODY></HTML>");
49: o.close();
50: }
51: }

1 | 

Discussion about this tutorial

  Start a new Discussion | Read All Discussion
Subject RepliesLast Post
Javaorigin.com contact@javaorigin.com