JSP: How to check if a user is logged in? - java

I'm learning Java Web, but I have some problems and I need help.
I use a template.jsp in which I include header.jsp, footer.jsp, login.jsp (the left side of the template ) and ${param.content}.jsp. For each page named X.jsp I made another jsp with the following content, because I want each page to have the same layout:
<jsp:include page="template.jsp">
<jsp:param name="content" value="X"/>
<jsp:param name="title" value="Start navigate"/>`enter code here`
</jsp:include>
When I click on the Review link,for example, I want to be redirect to Review.jsp, but I have some problems.
In footer.jsp I have something like this:
(...)
< a href =" Review.jsp "> Review </a>
(...)
After login, I try to click Review, it sends me to the Review.jsp, but it shows me that I'm not logged in. I use Spring Framework, Tomcat 7, Eclipse, MySQL. When I log in, I create a cookie:
String timestamp = new Date().toString();
String sessionId = DigestUtils.md5Hex(timestamp);
db.addSession(sessionId, username, timestamp);
Cookie sid = new Cookie("sid", sessionId);
response.addCookie(sid);
For each method, I have something like this (I saw this in a tutorial):
#RequestMapping(value = "/writeReview", method = RequestMethod.GET)
public String nameMethod(#CookieValue("sid") String sid,...)
Using the sid, I can find out who's the user. I have a database with the user's account and some other tables. The problem is that when I click review or any other, it shows me that I'm not logged in. What can I do?
UPDATE:
I use JavaBean for user and login.jsp. The JSP that has the text box for the login, I have a GET method when I click on the button to log in.
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView createCookie(
#RequestParam("username") String username, #RequestParam("password") String password,
HttpServletRequest request, HttpServletResponse response) throws SQLException {
//code for creating the cookie here, after testing if the user is in my database
}
For each page, I send the sid and I have an attribute for the model, username:
public String methodName(#CookieValue(required = false) String sid, Model model) {
if (sid != null) {
User user = getUserBySid(sid);
model.addAttribute("user", user);
}
(..other data.)
return "nameJSP.jsp";
}
I check in each JSP if the username is not empty, so that's how I see if a user is logged in. The application goes well, it passes parameters if I don't click on the links from the header or footer. The problem is that I have to pass , let's say, a parameter from a JSP who's the actual content of the layout to the JSP referred by the footer and this JSP will be the next content of my layout. The layout only recognize content and title:
<title>${param.title}</title>
(I didn't paste all the code, I use a table <table>....)
<%# include file="header.jsp"%>
<%# include file="login.jsp"%>
<jsp:include page="${param.content}.jsp"/>
<%# include file="footer.jsp"%>
So how can I include a parameter in this JSP which will be received from another JSP? Also it will have to be accessed by layout.jsp and sent to the footer or the header?
<jsp:include page="layout.jsp">
<jsp:param name="content" value="X"/>
<jsp:param name="title" value="Start navigate"/>
</jsp:include>

To pass some parameter(s) to the included JSP:
<jsp:include page="somePage.jsp" >
<jsp:param name="param1" value="someValue" />
<jsp:param name="param2" value="anotherParam"/>
....
</jsp:include>
You are already doing it.
OK, the details of the question is not very clear, but I get the idea.
One of the solutions could be the following.
In your Login action, if the authentication was successful, create HttpSession and set an attribute for the authenticated User:
if (/* authentication was successfull */) {
request.getSession().setAttribute("loggedInUser", user);
...
}
And in the code where you are controlling if the user is logged in just check the presence of the appropriate HttpSession attribute:
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("loggedInUser") == null) {
// user is not logged in, do something about it
} else {
// user IS logged in, do something: set model or do whatever you need
}
Or in your JSP page you can check if the user is logged in using JSTL tags as showed by BalusC in the example here:
...
<c:if test="${not empty loggedInUser}">
<p>You're still logged in.</p>
</c:if>
<c:if test="${empty loggedInUser}">
<p>You're not logged in!</p>
</c:if>
...
Filters to the rescue
But usually, you check if the user is logged in to restrict access to some pages (so only authenticated user could access them). And you write some class that implements javax.servlet.Filter.
Here is an example of the LoginFilter from one of my projects:
package com.example.webapp.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* The purpose of this filter is to prevent users who are not logged in
* from accessing confidential website areas.
*/
public class LoginFilter implements Filter {
/**
* #see Filter#init(FilterConfig)
*/
#Override
public void init(FilterConfig filterConfig) throws ServletException {}
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("loggedInUser") == null) {
response.sendRedirect(request.getContextPath() + "/login.jsp");
} else {
chain.doFilter(request, response);
}
}
/**
* #see Filter#destroy()
*/
#Override
public void destroy() {}
}
In this project I used plain servlets and JSP without Spring, but you'll get the idea.
And of course, you must configure web.xml to use this filter:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
...
<filter>
<filter-name>Login Filter</filter-name>
<filter-class>com.example.webapp.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Login Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
Note:
If you are using a Web Container or Application Server that supports Servlet version 3.0 and higher then you can annotate your filter class with #WebFilter annotation in which case there is no need to configure the filter in the deployment descriptor (web.xml). See an example of using #WebFilter annotation and more Filter related information here.
Hope this will help you.

Or just use:
String username = request.getRemoteUser();

Related

Session created by Tomcat

I am learning session with servlets and i read in the book that to create a session we need to call as below.
HttpSession session = request.getSession()
This causes the web container to create a session ID and send it back to client so that client can attach it with every subsequent request to the server. When i open developer tools in chrome under request headers in network tab i do see a cookie header.
Cookie: JSESSIONID=F92
Below is what i did in my login servlet
package shop;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class LoginServlet extends HttpServlet{
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String uid = request.getParameter("uid");
String password = request.getParameter("pwd");
if(uid.equals("admin") && password.equals("admin"))
{
HttpSession session = request.getSession();
System.out.println(session.getId());
response.sendRedirect("shopping");
}
else
response.getWriter().println("Invalid Credentials");
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
this.doGet(request, response);
}
}
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>shopping application</title>
</head>
<body style="background-color:cyan">
<div style="text-align:center">
<h3>Welcome to Mart</h3>
<form action="login" method="post" name="loginform">
<div style="padding:2px;">
<label for="uid">Username:</label>
<input type="text" id="uid" name="uid">
</div>
<div style="padding:2px;">
<label for="pwd">Password:</label>
<input type="password" name="pwd" id="pwd">
</div>
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
My question is that even if i remove the getSession() call i still see the cookie in the network tab. Is there a default session associated with every request by tomcat?
On Tomcat sessions are established lazily, when they are needed. There are basically a couple of situations where sessions are created:
if you call request.getSession() or request.getSession(true) a session is always established,
if you authenticate users against Tomcat's user database a session might be created depending on the authentication method. Most notably if you use form authentication (see this tutorial) a session is always established,
JSP pages create sessions unless you add the <%page session="false"%> directive (see Why set a JSP page session = "false" directive?).
Browsers remember cookies, so the presence of a JSESSIONID is not an indication of the presence of a session (it might be there from a previous test). To test for a presence of a session use request.getSession(false). For example:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final boolean establishSession = req.getParameter("withSession") != null;
try (final PrintWriter writer = resp.getWriter()) {
final String requestedSessionId = req.getRequestedSessionId();
final HttpSession possibleSession = req.getSession(establishSession);
writer.append("I requested a session with id: ")//
.append(requestedSessionId)
.append("\nI have a session with id: ")
.append(possibleSession != null ? possibleSession.getId() : null)
.println();
}
}
Edit: I added the case of a JSP page creating sessions.

Very random empty jsp form data on submit after validation

We have a jsp (2.2)/jstl(2.1) form that submits to a java servlet (3.0) on tomcat 7 server. Randomly, intermittently we will get a submission to the servlet with all the http request parameter values as null. Our form has some fields that are pre-populated so we expect at least those to be retrievable but they are null at the serlvet as well. Almost all of the form submissions we receive contain form data and are successfully processed. It's the once in every so many submissions that has the completely empty http request parameter set that I cannot figure out nor reproduce. There are no file uploads involved, the data is submitted via post. We validate client side and server side. I have searched high and low for reasons why the form data can be empty but have not had any success. Any thoughts?
1) no file uploads
2) all fields have 'name='
3) method is post
4) data is validated prior to submission
5) implement a filter for db entity management
partial jsp form:
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
response.setHeader("Cache-Control", "no-cache");//Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control", "no-store");//Directs caches not to store the page under any circumstance
response.setDateHeader("Expires", 0);//Causes the proxy cache to see the page as "stale"
response.setHeader("Pragma", "no-cache");//HTTP 1.0 backward enter code here
%>
<!DOCTYPE html>
<!--head/body stuff -->
<form id="app_form" name="app_form" action="process" method="post" novalidate="novalidate" accept-charset="ISO-8859-1">
<!-- general form fields using html/jstl -->
<button type="submit" id="submit_application" name="submit_application" class="submit application submitbtn" title="I'm finished and want to submit my completed application.">SUBMIT APPLICATION</button>
</form>
partial filter:
public class EntityManagerFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Initializing filter...");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
EntityManagerUtil.getEntityManager().getTransaction().begin();
chain.doFilter(request, response);
EntityManagerUtil.getEntityManager().getTransaction().commit();
} catch (Throwable ex) {
}
partial java servlet:
public class ProcessApplicationFormServlet extends BaseServlet {
private static Logger log = Logger.getLogger(ProcessApplicationFormServlet.class);
private static final long serialVersionUID = 1L;
Application_Domestic appdata = null;
Domestic_user currentUser = null;
String sessID = null;
String program = null;
String type = null;
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
//values from form
appdata.setTitle(maxLength(req.getParameter("title"),25));
appdata.setFirst(maxLength(req.getParameter("first"),30));
appdata.setMiddle(maxLength(req.getParameter("middle"),30));
appdata.setLast(maxLength(req.getParameter("last"),57));
appdata.setSuffix(maxLength(req.getParameter("suffix"),25));
appdata.setEmail_Address(maxLength(req.getParameter("trueemail"),50));
etc...
process data
}
}
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
These are just the portions that deal with submission/http request. If there are other important coding considerations that I need to show, please let me know. Do keep in mind that only 1 - 2 percent of the form submissions come in with empty httpServletRequest data. This code has been tested and working. I just cannot seem to be able to reproduce the scenario when a user submits the form (it can not be submitted until all data as been validated) and it reaches the servlet with an empty data set where every parameter is null.

Servlet Program works only for first time

I was trying this small HttpSession program as a demo for my project.
This program just checks whether the user is new, if it is then displays a form, if the user is not new, then it displays the name of the user, the color he selected and the total no. of visits.
When i run my program, it works only for the first time. That means when i run another instance of my program, it displays a blank web page.
What is wrong in the code that is causing this problem???
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Integer hitCount;
HttpSession s = request.getSession(true);
if(s.isNew()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SessionServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<form method=get action=SessionServlet>");
out.println("<h3>Please sleect a Color</h3>");
out.println("<input type=radio name=color />Red");
out.println("<br /><input type=radio name=color />Green");
out.println("<br /><input type=text name=txtName />");
out.println("<br /><input type=submit name=Submit value=Submit />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
} else if(!s.isNew()){
String name = (String) request.getParameter("txtName");
String color = (String) request.getParameter("color");
hitCount = new Integer(1);
s.setAttribute("Name", name);
s.setAttribute("color", color);
s.setAttribute("HitCount", hitCount);
if((name != null) && (color != null)) {
out.println("Name: " + s.getAttribute("Name"));
hitCount = (Integer)s.getAttribute("HitCount");
hitCount = hitCount++;
s.setAttribute("HitCount", hitCount);
//out.println("<body bgcolor=" + s.getAttribute("color") + ">");
out.println("you selected" + s.getAttribute("color"));
out.println("Total visits=====>" + s.getAttribute("HitCount"));
}
}
}
}
}
The second time you run this code, the session already exists, so the program goes through else branch- but the "old" request object (from the first run of the application) and its parameters (color and name) are already gone at that time. Request is destroyed by container right after the response from the first application run was sent back to the client.
In your code
String name = (String) request.getParameter("txtName");
String color = (String) request.getParameter("color");
you are trying to get non existing parameters. Parameters txtName and color do not exist in request anymore. Therefore they are null and the next condition
if((name != null) && (color != null))
is always false. And nothing is written into out Writer.
What you should do in order to make this work is to read the parameters from the session object (this is what the sessions are made for anyway) where you should put them in the first application run. This code won't work. And your hitCount will always be 1 (please see HttpSessionListener interface). This code is wrong on so many levels- you should re-write everything after the else if branch which should be only else anyway.
TLDR:
Your question was why it is not working: the answer is - you are reading non existing parameters. You have to put the parameters into session object in the first application run and read them from it.
edit after your question from December 31st:
Here is what I would do. Assume following directory structure of this simple project named SessionServlet. This structure will be used in whole answer. To simplify things I won't list every directory, you surely get the idea from this. This is not the real-life example of directory structure, it is simplified for the purposes of this tutorial example.
<path-to-project>/SessionServlet/src/com/example/session
<path-to-project>/SessionServlet/WebContent/META-INF
<path-to-project>/SessionServlet/WebContent/WEB-INF
Create an html file, for example start.html. It should contain the input fields which values you need to store in the session. The file goes here
<path-to-project>/SessionServlet/WebContent/start.html
Its contents
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Start page</title>
</head>
<body>
<form method="get" action="MySessionServlet">
<h3>Please select a Color</h3>
<input type="radio" name="color" value="red" />Red<br>
<input type="radio" name="color" value="green" />Green<br>
<input type="text" name="txtName" /><br>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
In your servlet example you forgot the value attribute in radiobutton input, therefore whichever radiobutton you would check, the value would be on, not the color name.
Next you have to create the servlet class SessionServlet.java, which will be slightly different from your original idea. It goes here:
<path-to-project>/SessionServlet/src/com/example/session/SessionServlet.java
Its contents
package com.example.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = -3808675281434686897L;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String requestColor = null;
String requestTxtName = null;
PrintWriter out = response.getWriter();
MySessionListener listener = new MySessionListener();
HttpSession session = request.getSession();
if (session.isNew()) {
//these are request parameters sent from html form
requestColor = request.getParameter("color");
requestTxtName = request.getParameter("txtName");
//save the attributes in session in order to use them later
session.setAttribute("sessionColor", requestColor);
session.setAttribute("sessionTxtName", requestTxtName);
}
else {
//get the previously stored attributes from session
String color = (String) session.getAttribute("sessionColor");
String name = (String) session.getAttribute("sessionTxtName");
//session info
out.println("session already existed");
if (color != null && name != null) {
out.println("Name: " + name);
out.println("Color: " + color);
out.println("Session count: " + listener.getSessionCount());
}
}
}
}
I think the servlet's code is pretty much self-explanatory. However, if you have any particular questions, please ask.
In order to count the active sessions, you need to create a SessionListener class and count the sessions. For the purposes of this example I put the class into the same directory as servlet class. Please do not do this in real project. You'd create a big mess. This is only simplified Java Enterprise Hello world example. The file is here
<path-to-project>/SessionServlet/src/com/example/session/MySessionListener.java
Its contents are
package com.example.session;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
private static int sessionCount;
#Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Creating session with id: " + se.getSession().getId());
sessionCount++;
}
#Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Destroying session id: " + se.getSession().getId());
sessionCount--;
}
public int getSessionCount() {
return sessionCount;
}
}
The listener class for counting active sessions must implement HttpSessionListener interface. We call the method getSessionCount() in SessionServlet class as you already noticed.
The last thing to do is to create a deployment descriptor xml in order to tell the container what to do with those classes we created.
the file must be named web.xml and it must be placed in WEB-INF directory.
<path-to-project>/SessionServlet/WebContent/WEB-INF/web.xml
Its contents are
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"
version="3.1">
<display-name>SessionServlet</display-name>
<welcome-file-list>
<welcome-file>start.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>my Session Servlet</servlet-name>
<servlet-class>com.example.session.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>my Session Servlet</servlet-name>
<url-pattern>/MySessionServlet</url-pattern>
</servlet-mapping>
<!-- set session timeout to 30 minutes -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- register listener class -->
<listener>
<listener-class>com.example.session.MySessionListener</listener-class>
</listener>
</web-app>
And that's all. Lastly my two cents- you should first acquaint with Standard Edition Java. This is an example from Enterprise world which is way over your head yet. There are plenty of tutorials on the web. Give it some time, you won't regret it.
Regarding the servlets- you should (must) first understand the basic concepts of request, response, session, client and container (who is who, the lifecycle, managing, etc.) before you start making real projects. The best book I've seen about this is Head First - Servlets and JSP, which should be a starting point in understanding this topic.
You set response.setContentType("text/html;charset=UTF-8") ....
But in your section if(!s.isNew()){.... the output is not HTML, but is plain text. ("Name:", etc...)
My bet is that the content is there, but your browser is not displaying it.

Session attribute is null at first load

I have the following servlet:
#WebServlet(name = "Placeholder",urlPatterns = {"/foo"})
public class Placeholder extends HttpServlet {
public static int numbers=5;
HttpSession session;
public void doGet (HttpServletRequest _req, HttpServletResponse _res) throws ServletException, IOException {
/* Refresh session attributes */
session = _req.getSession();
session.setAttribute("wee","ok");
}
}
With the following JSP:
<%#page language="java" contentType="text/html"%>
<%#page import="java.util.*, java.io.*"%>
<%#page import="main.java.Placeholder.*" %>
<html>
<body>
<b><% out.println("wee, printing from java");%></b>
<% out.println("<br/>Your IP address is " + request.getRemoteAddr());
String value = (String) session.getAttribute("wee");
out.println(value);%>
</body>
</html>
I'm surely missing the point somewhere as attribute wee is resolved as null, first time I load the page. If I go to /foo I get empty an page, and after I get back and reload the root page of servlet, wee actually gets its value.
My goal here is to simply print variables from the servlet into the view, no routing needed. Not sure that urlPatterns are needed here, but it does not work for now without this little hack.
UPD. Ok, so I've figured out that whatever route I put in, I need to add some characters in browser, get back and reload the page.
So, the root is 0.0.0.0:8080/webapp
I need to access,say 0.0.0.0:8080/webapp/qwerty , get back to /webapp and refresh the page.
How do I get session instantiated by just going to /webapp?
Why don't I have 404 or 500 on accessing some random unexisting route /webapp/randomstuff?
First configure servlet as welcome file in web.xml. If web.xml not present than create it manually inside WEB-INF folder and put below content inside it.
<welcome-file-list>
<welcome-file>foo</welcome-file>
</welcome-file-list>
than in your servlet dispatch request to your jsp lets say your jsp name is index.jsp than your servlet code would be look like:
#WebServlet(name = "Placeholder",urlPatterns = {"/foo"})
public class Placeholder extends HttpServlet {
public static int numbers=5;
public void doGet (HttpServletRequest _req, HttpServletResponse _res) throws ServletException, IOException {
HttpSession session = _req.getSession();
session.setAttribute("wee","ok");
_res.sendRedirect("index.jsp");
}
}
Now run your servlet you will see output.
Hope this solve your problem!!!

How do I invalidate a login session initialized in one servlet in another servlet with a href in between?

I am working on a web app and I have to implement a login/logout system. I have already implemented the login system(validating by verification through a database) in a controller servlet. Basically the most important aspect of my project is to keep a MVC approach.So here is the controller login servlet that I have implemented,
package com.cid_org.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.cid_org.model.*;
import java.sql.*;
/**
* Servlet implementation class LoginControllerServlet
*/
public class LoginControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginControllerServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*Take the data submitted by the user though the login
* form(Remember the HTTP Post request ->HttpServletRequest request object*/
String username = request.getParameter("username");
String pwd = request.getParameter("pass");
System.out.println(username + "aaa");
System.out.println(pwd);
Connection connection = (Connection)getServletContext().getAttribute("connection_context_param");
LoginModelPOJO lmpojo = new LoginModelPOJO(username, pwd, connection);
boolean isUserValidFlag = lmpojo.isValid();
if(isUserValidFlag){
/*Entering this block indicates the user has been validated and if the
* user has been validated, we should start a session. But here is a
* question, where exactly(at which point) should we say that user has
* logged in? -I guess when the user sends his/her our login info.
* for validation and right at the moment the info. gets validated,
* we can say at this particular point in program he is IN. And this
* is the precise point for a Login session to start. So remember
* at this point we are logged in*/
/*Getting the session*/
HttpSession session = request.getSession();
RequestDispatcher view =request.getRequestDispatcher("/view/view_profile.jsp");
view.forward(request, response);
}
else{
/*And obviously the unauthorized user will be redirected to the login page.*/
response.sendRedirect("login.html");
}
}
}
And here is the view_profile.jsp,I dispatch the request to,
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Crime Investigation Department-User" content="text/html; charset=ISO-8859-1">
<title>Criminal Investigation Department</title>
<link rel="stylesheet" href="/CrimeReportingSystem5/static/css/view_profile_page.css">
</head>
<body>
<img src="css/images/logo/CID_Logo_1.png" alt="CID Logo">
<nav id="navigation">
<a id="link1" class="header_links" href="most_wanted.html">Most Wanted</a>
<a id="link2" class="header_links" href="hotnews.html">Hot News</a>
<a id="link3" class="header_links" href="report_crime.html">Report Crime</a>
<a id="link4" class="header_links" href="login.html">Login</a>
<a id="link5" class="header_links" href="about.html">About Us</a>
<a id="link6" class="header_links" href="contact.html">Contact Us</a>
<a id="link7" class="header_links" href="safety_measures.html">Safety Measures</a>
</nav>
<%
/*Remember we got to this page only after validation of the username
*from the servlet ,point being the username has already been validated
*so all we got to do here is retrieve the username form the request
*object and it.*/
String username = request.getParameter("username");
if(username == null){
response.sendRedirect("/CrimeReportingSystem5/static/login.html");
}
%>
<div id="login_page_border">
<span id="welcome_username_text">Welcome <%=username%></span>
View Complaints
Edit Profile
Logout
<div id="profile_layout">
</div>
</div>
</body>
</html>
My problem: I want to implement a logout system for which I already generated a session in Login servlet and I have decided to invalidate the session in another Logout servlet but there lies a link in between them(see the jsp) so the request sent will be a GET request to the servlet,how can I send session info. to the Logout servlet for the invalidation.Btw, I have read another answer in which it was suggested to create a static Map variable and store JSESSIONID and session as map variable but even if I did that,how would I know which user clicked the logout link?
Note: I can't use JavaScript or Jquery for the solution cause I am yet to read them. Please provide a simple solution.
You see problems where no problems are.
It's quite easy to invalidate the current session inside a servlet:
// Check, if there is a session active. Avoid to create a new one.
HttpSession session = request.getSession(false);
if(session != null) {
session.invalidate();
}
It doesn't matter, if this code runs in a different servlet than where you created the session.
Internally the session is usually managed by a browser cookie. So when you create a new session the server sends a cookie to the browser associated to the domain. Then each subsequent request the browser transmits this cookie to your server. Your servlet server implementation (like Tomcat) then checks this cookie against the active sessions, so that your next request.getSession() returns the right session corresponding to the specific user.

Categories