0

I want to do a login with javaServlets.

I did this in the past with PHP. But I found this short tutorial to do it with JavaServlets: http://www.studytonight.com/servlet/login-system-example-in-servlet.php

I just wonder, how they check later if the user is logged in. In PHP I started a SESSION and within this SESSION there was the session_username/id stored. So I could just check if there is a session, and if yes I read the sessionparameter where the username is stored and so I could load user specific content.

How does this work here? Can anyone help me? Thanks!

progNewbie
  • 4,362
  • 9
  • 48
  • 107

3 Answers3

1

You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below:

HttpSession session = request.getSession();

Source

Harshul Pandav
  • 1,016
  • 11
  • 23
1

You will need to add session information usually through servlet (get/post) request so your login.jsp page would point to Login and redirect you to homepage.jsp

  public class Login extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response){

        HttpSession session = request.getSession();
        String user = (String)request.getParameter("userName");
        session.setAttribute("userName", user);

        request.getRequestDispatcher("/homepage.jsp").forward(request, response);
    }
  }

You can access session information directly inside jsp several ways

<%
  String userId = request.getSession().getAttribute("userName");
%>

or using jstl (you will have to add library from jstl)

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:if test="${not empty sessionScope.userName}">
  User logged in as <c:out value="${sessionScope.userName}" />
</c:if>
Kyle Bradley
  • 141
  • 1
  • 10
0

I would use a Servlet Filter where you can check if the session exists

boolean loggedIn = (session != null) && (session.getAttribute("UserID") != null);

The filter will direct all traffic to it (based on what you tell its pages to direct to in web.xml). The filtered traffic can then be checked if the session exists and continue or redirect user to correct page.

Here are some great starting points:

http://www.tutorialspoint.com/servlets/servlets-writing-filters.htm

How to handle authentication/authorization with users in a database?

How implement a login filter in JSF?

J2EE filter : login page unable to load the css or any images

Community
  • 1
  • 1
Kyle Bradley
  • 141
  • 1
  • 10