java.lang.IllegalStateException: getAttributeNames: Session already invalidated - java

Getting error:
java.lang.IllegalStateException: getAttributeNames: Session already invalidated.After logout from parent window.
LogOutUserAction.java
public String execute() throws Exception {
System.out.println("inside :: LogOutUserAction------");
//HttpServletRequest request = null;
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session =request.getSession(true);
session.removeAttribute("loggedInUser");
request.getSession(false).invalidate();
session=null;
return "logout";
}
LoginInterceptor
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context
.get(HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) context
.get(HTTP_RESPONSE);
HttpSession session = request.getSession(true);
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
/*user logged out from the parent window then set the message
for click on the popup window*/
if(session == null){
System.out.println("set the attribute");
request.setAttribute("SessionExpired","Your have already logged out");
}
Object user = session.getAttribute(USER_HANDLE);
String loginOut = request.getParameter(LOGIN_OUT);
System.out.println("loginOut---->"+loginOut);
if (user == null) {
// The user has not logged in yet.
System.out.println(" inside if ");
// Is the user attempting to log in right now?
String loginAttempt = request.getParameter(LOGIN_ATTEMPT);
/* The user is attempting to log in. */
if (!StringUtils.isBlank(loginAttempt)) {
return invocation.invoke();
}
return "login";
} else {
return invocation.invoke();
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
if (request.getAttribute("SessionExpired")!= null)
{
System.out.println("After Session invalid");
}
%>
<html>
<head>
<title>Login</title>
<sx:head cache="true"/>
<script type="text/javascript">
</script>
<script type="text/javascript" language="javascript" src="js/login.js"></script>
<style type="text/css">
.style1 {font-family: Verdana, Arial, Helvetica, sans-serif}
.style2 {
color: #000099
}
</style>
</head>
<body bgcolor="#CODFFD" background="<%request.getContextPath();%>images/watermark_new.jpg">
<br>
<br>
<br>
<br>
<br>
<br>
<div align="center"><span class="style1">USER LOGIN</span>
<br>
<br>
<br>
<s:form action="checkUserLogin.action" validate="true" name = "loginForm">
<s:hidden name="loginAttempt" value="%{'1'}" />
<table border="0" cellspacing="1" cellpadding="0" width="350" >
<tr>
<td align="center">
<b>Login ID</b>
</td>
<td>
<table>
<s:textfield id="id" name="loginId" value="" />
</table>
</td>
</tr>
<tr>
<td align="center">
<b>Password</b>
</td>
<td>
<table>
<s:password id="password" name="loginPassword" value="" showPassword="true"/>
</table>
</td>
</tr>
<tr><td colspan="2" align="center">
<table>
<s:submit value="Login" onclick = "return getRoleList()"/>
</table>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<table>
<s:a href="changePasswordScreen.action" >Change Password</s:a>
</table>
</td>
</tr>
</table>
</s:form>
</div>
<br>
<br>
<br>
</body>
</html>
Need to display message on popup window (when i click on any link) as i mentioned on my login jsp after logout from parent window.

Interceptors can execute code before and after an Action is invoked. When is yours being invoked? I would imagine what's happening is this:
In LogOutUserAction.java you invalidate the session
LoginInterceptor.intercept is then executed. This tries to get an attribute from the session object that you invalidated hence the IllegalStateException.
Why are you invalidating the session? Your LoginInterceptor is using the presence of the USER_HANDLE attribute to indicate whether or not the user is logged in. I would remove this attribute in your LogOutUserAction but don't invalidate the session.

Related

Get checkbox within div value from java servlet

I can't get the checkbox value of "no_del_file" into the servlet.
here is my JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>List of Command menu</title>
</head>
<body>
<div><b>${reply}</b></div>
<div id="wrapper">
<div id="menu">
<form action="runButtonCommand" method="post" name="myform">
<a href="runButtonCommand?param1=list apps" >List1</a><br/><br/>
<a href="runButtonCommand?param1=list data" >List2</a><br/><br/>
<br/><br/>
no del:
<%String test = (String)request.getParameter("no_del_file"); %>
<%String checked = "";%>
<%
if ("on".equals(test)) {
checked="checked=\"on\"";
} %>
<input type="checkbox" name="no_del_file" <%=checked%>>
<br />
</form>
</div>
<div id="output">
<p>Output:</p>
<textarea style="resize: none;" data-role="none" rows="40" cols="120" name="outputarea">
${data}
</textarea>
</div>
</div>
</body>
</html>
And here is the Servlet part where I try to get the checkbox value:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String[] tester= request.getParameterValues("no_del_file");
System.out.println("Start: "+tester);
performTask(request, response);
}
However it doesn't matter if I use getParameterValues, getParameter or getAttribute I always get null if checked or unchecked. How can I get that value?
Thanks for your help.
Viking

Illegal State Exception : Cannot call sendRedirect() after the response has been committed

I call GET method to retrieve data and display on JSP page using RequestDispatcher. Later i call POST to save it while staying on the same page using sendRedirect. I get illegal state exception. I am new. Please help.
Here is my logout.jsp page
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<form action="LogoutUserServlet" method="post">
<input type="submit" value="Logout" name="Logout">
</form>
<form action="LogoutUserServlet" method="get">
<input type="submit" value="Get Tracker">
</form>
<form action="LogoutUserServlet" method="post">
<table cellpadding="5" border="1">
<c:set var="i" value="0" />
<c:set var="eo" value="1" />
<c:forEach items="${sites}" var="s1" begin="${i}">
<c:if test="${eo==1 || eo%2 ==1 }">
<tr>
<c:forEach items="${sites}" var="s1" begin="${i}" end="${i+2}">
<td class="a-center "><input type="checkbox" class="flat"
name="table_records" value="${s1}"> <c:out value="${s1}" /></td>
</c:forEach>
</tr>
<c:set var="i" value="${i+3}" />
</c:if>
<c:if test="${eo%2 ==0}">
<tr>
<c:forEach items="${sites}" var="s1" begin="${i}" end="${i+2}">
<td class="a-center "><input type="checkbox" class="flat"
name="table_records" value="${s1}"> <c:out value="${s1}" /></td>
</c:forEach>
</tr>
<c:set var="i" value="${i+3}" />
</c:if>
<c:set var="eo" value="${eo+2}" />
</c:forEach>
</table>
<input type="submit" name="Save" value="save">
</form>
</body>
</html>
Here is my LogoutUserServlet servlet page
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<String> sitetypes = new ArrayList<String>();
sitetypes.add("abc");
sitetypes.add("def");
sitetypes.add("ghi");
request.setAttribute("sites", sitetypes);
request.getRequestDispatcher("/logout.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("Logout")!=null){
response.setContentType("text/html");
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User="+session.getAttribute("user"));
if(session != null){
session.invalidate();
}
response.sendRedirect("login.html");
} else if(request.getParameter("Save")!=null){
String[] selectedStudentIds = request.getParameterValues("table_records");
for (int i = 0; i < selectedStudentIds.length; i++) {
System.out.println("=="+selectedStudentIds[i]);
response.sendRedirect("logout.jsp");
}
}
}
Here is the error
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:482)
servlets.LogoutUserServlet.doPost(LogoutUserServlet.java:79)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
servlets.AuthenticationFilter.doFilter(AuthenticationFilter.java:45)

dynamic creation of select tag in jsp using jstl and arraylist

I have searched this forum and net for this, found many example but still i am not able to populate the select box in jsp.
I have written a jsp servlet, where servlet returns an arraylist and in jsp uhsing jstl i am trying to create a select box and populating option with arraylist values.
Following is my code.
Servlet Code:
#SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response) {
UserService userService = new UserServiceImpl();
try {
String[] questions = userService.getQNA().getQuestions();
List<String> ques = new ArrayList<String>();
ques = Arrays.asList(questions);
request.setAttribute("questionDTO", ques);
response.sendRedirect("forms/enrollMigrationUser.jsp");
} catch (IOException e) {
log.error("request failed "+ e.getMessage());
}
}
JSP code :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Enroll Migration Users</title>
</head>
<body>
<form method="post" action="/nycb/enrolluser" name="enrollForm">
<table>
<tr>
<td>User setup</td>
<td></td>
</tr>
<tr>
<td>UserId :</td>
<td><input type="text" name="userName" id="userName"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="password" id="password"/></td>
</tr>
<tr>
<td><input type="checkbox" name="computerType" value="public">Authorize this computer</td>
<td></td>
</tr>
<tr>
<td>
<select name='role'>
<c:forEach items="<%=request.getAttribute(\"questionDTO\") %>" var="question">
<option value="<c:out value="${question}"/>"><c:out value="${question}"/></option>
</c:forEach>
</select>
</td>
<td><input type="text" name="qna6" id="qna6"/></td>
</tr>
<tr>
<td>
<select name='role'>
<c:forEach items="${questionDTO}" var="question">
<option value="<c:out value="${question}"/>"><c:out value="${question}"/></option>
</c:forEach>
</select>
</td>
<td><input type="text" name="qna6" id="qna6"/></td>
</tr>
</table>
<input type="submit" value="click" name="dropdown" id="dropdown">
</form>
I am not able to populate the select box, the option field is empty.
Can anyone please let me know where i am going wrong?
sendRedirect() creates a new request and any attribute set in request will not be available in redirected JSP page.
Try any one
You can use RequestDispatcher#forward or RequestDispatcher#include in this case.
You can save it in session as attribute.
Sample code:
RequestDispatcher view = request.getRequestDispatcher("forms/enrollMigrationUser.jsp");
view.forward(request, response);
OR
HttpSession session = request.getSession();
session.setAttribute("questionDTO", ques);
response.sendRedirect("forms/enrollMigrationUser.jsp");
Always try to avoid Scriplet elements instead use JSTL & EL.
You can do in this to read an attribute from any scope in order page, request, session and finally applicaion
<c:forEach items="${questionDTO}" var="question">
OR read from specific scope.
<c:forEach items="${requestScope.questionDTO}" var="question">

JavaBean not being remembered throughout the session

I'm currently learning JSP/Servelets. The following is code containing 2 JSP pages and a servlet, which works as follows:
JSP #1 requests user info, & passes it into a servlet.
The servlet Instantiates a JavaBean class, and passes it to the 2nd JSP, using the Session Object.
The 2nd JSP then displays the info that th user entered in the 1st JSP; the user can then hit the Return button to return to the 1st JSP.
My Question is: I've read in various Tutorials (notably Murach's JSP, which this code is based on) that if the Javabean attributes are passed to the session object rather than the request object, the JavaBean's values should be maintained throughout the session. However when I return to the first page, the JB fields are empty. Am i doing anything wrong? I would appreciate any help!
The following is the code:
1st JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Join our Email list</h1>
<p>To join our email list, enter your name and email address below.<br>
Then, click on the Submit button</p>
<form action="addToEmailList" method="post">
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td>
<input type="text" name="firstName"
value = "<jsp:getProperty name="user" property="firstName"/>">
</td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value = "<jsp:getProperty name="user" property="lastName"/>">
</td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"
value = "<jsp:getProperty name="user" property="emailAddress"/>">
</td>
</tr>
<tr>
<td>I'm interested in these types of music:</td>
<td><select name="music" multiple>
<option value="rock">Rock</option>
<option value="country">Country</option>
<option value="bluegrass">Bluegrass</option>
<option value="folkMusic">Folk Music</option>
</select>
</td>
</tr>
<tr>
<td ></td>
<td><input type="submit" name="Submit"></td>
</tr>
</table>
</form>
</body>
Servlet:
public class AddToEmailListServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;
private String firstName;
private String lastName;
private String emailAddress;
private String[] musicTypes;
private Music music;
private User user;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
this.request = request;
this.response = response;
setInstanceVariables();
writeDataToFile();
forwardResponseToJSPpage();
System.err.println("Hello!");
}
private void setInstanceVariables()
{
this.firstName = getFirstName();
this.lastName = getLastName();
this.emailAddress = getEmailAddress();
this.musicTypes = request.getParameterValues("music"); //getMusic();
this.user = new User(firstName,lastName,emailAddress);
}
private String getFirstName()
{
return request.getParameter("firstName");
}
private String getLastName()
{
return request.getParameter("lastName");
}
private String getEmailAddress()
{
return request.getParameter("emailAddress");
}
private void writeDataToFile() throws IOException
{
String path = getRelativeFileName();
UserIO.add(user,path);
}
private String getRelativeFileName()
{
ServletContext sc = getServletContext();
String path = sc.getRealPath("/WEB-INF/EmailList.txt");
return path;
}
private void forwardResponseToJSPpage() throws ServletException, IOException
{
if(this.emailAddress.isEmpty()||this.firstName.isEmpty()||this.lastName.isEmpty())
{
String url = "/validation_error.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
else
{
music = new Music(musicTypes);
HttpSession session = this.request.getSession();
session.setAttribute("music", music);
session.setAttribute("user", user);
String url = "/display_email_entry.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
}
2nd JSP:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# include file="/header.html" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First name:</td>
<td><jsp:getProperty name="user" property="firstName"/></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><jsp:getProperty name="user" property="lastName"/></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td><jsp:getProperty name="user" property="emailAddress"/></td>
</tr>
</table>
<p>We'll use the Email to otify you whenever we have new releases of the following types of music:</p>
<c:forEach items="${music.musicTypes}" var="i">
<c:out value="${i}"></c:out><br/>
</c:forEach>
<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>
<form action="join_email_list.jsp" method="post">
<input type="submit" value="Return">
</form>
</body>
<%# include file="/footer.html" %>
</html>

Set a request attribute depending on the link clicked

I would like to determine which link is being click, and set a request attribute accordingly; to be processed in the controller. The controller is generic. It will dispatch to another page according to the attribute set in the JSP. How can I achieve this?
EDIT:
I have followed the BalusC's advice where
Register
Login
RandomController :
#WebServlet(name = "RandomController", urlPatterns = {"/RandomController/*"})
public class RandomController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int theRandom = 0;
Random myRandom = new Random();
RequestDispatcher dispatcher = null;
String pathInfo = request.getPathInfo();
String contextPath = request.getContextPath();
String dispatchesPath = contextPath + pathInfo;
System.out.println(pathInfo);
System.out.println(contextPath);
System.out.println(dispatchesPath);
theRandom = myRandom.nextInt(MAX_RANDOM);
request.setAttribute("random", theRandom);
if(pathInfo.equals("/Login")) {
dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
dispatcher = request.getRequestDispatcher("Register.jsp");
dispatcher.forward(request, response);
}
}
}
I have tried this approach but the Exception about maximum depth for nested request dispatchers : 20 is throw.
The generic controller is RandomController which servers two produces random number and set as attribute in request object and sent it to login or register page.
Login.jsp :
<%--
Document : Register
Created on : May 28, 2011, 5:49:35 PM
Author : nicholas_tse
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Online Store Register Page</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<jsp:useBean id="randomBean" class="Helper.RandomInt"
scope="request">
</jsp:useBean>
<h1>Online Store</h1>
<p></p>
<div align="right">
<h3>
<c:if test="${not empty sessionScope.username}">
! Welcome ${sessionScope["username"]} !
<form action="LogoutController" method="POST">
<input type="submit" name="submit" value="Logout"/>
</form>
</c:if>
</h3>
</div>
<ul id="nav_list">
<li>Home</li>
<li>Product</li>
<li>Add Stock</li>
<li>Shopping Cart</li>
<li>Order Status</li>
<li>Register</li>
<li>Login</li>
</ul>
<br></br>
<p></p>
<c:if test="${!not empty sessionScope.username}">
<div id="registerForm" align="center"
style="border:1px solid black; width:760px" >
<form name="RegisterForm" action="RegisterController"
method="POST">
<p>
Username : <input type="text" id="username" name="username">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Password : <input type="password" id="password" name="password"
</p>
<p>
Name : <input type="text" id="name" name="name">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Address : <input type="text" id="address" name="address">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
State :
<select>
<option>Selangor</option>
<option>Kuala Lumpur</option>
<option>Cyberjaya</option>
<option>Putrajaya</option>
</select>
</p>
<p></p>
<input type="submit" name="submit" value="Register">
<input type="reset" name="clear" value="Clear">
<p></p>
</form>
</div>
</c:if>
</body>
</html>
Without further info the only suggestion I can think of is to add a querystring to your URLs. Like this:
Page 1
This way you can look at the actiuon parameter in the request to determine what to do in your controller.
You can add a request parameter. This can be done in 2 ways depending on whether your form has a method of POST or GET.
You have implemented the submit buttons in the forms with a name attribute of submit and different value attributes. This should mean that the requests will include a submit parameter in the query string or the POST form data. On the server side, you can use this to figure out which of the submit buttons was clicked.

Categories