Struts setSesssion() is not working - java

I am trying to put attributes to session from my action class
public String execute() {
String result = Action.SUCCESS;
if (username.equals("pavan") && password.equals("kumar")){
System.out.println("Success");
Map<String, Object> session = new HashMap<String, Object>();
session.put("username", username);
session.put("role", 1);
ActionContext.getContext().setSession(session);
return Action.SUCCESS;
}
else{
System.out.println("Input");
return Action.INPUT;
}
}
Success will be returned when username and password are valid and goes to appropriate JSP.
but session attributes i did set are not visible in jsp
<% if(session == null || session.getAttribute("username") == null) {
System.out.println("No valid session found");
response.sendRedirect("/Test/index.jsp");
}%>
Above code is the jsp will redirect to index.jsp and "No valid session found" will be printed in console.
What am i missing?

You are missing the session is a different object in both cases. You don't need to use scriptlets in the code. If you want to put something to the session you should get the session map from the action context
Map<String, Object> session = ActionContext.getContext().getSession();
session.put("username", username);
session.put("role", 1);
return Action.SUCCESS;
or use servlet session directly
HttpSession session = ServletActionContext.getRequest().getSession();
session.setAttribute("username", username);
session.setAttribute("role", 1);
return Action.SUCCESS;
But the first case is preferable, due to it's supported by the framework.

Related

I can't save session attributes with HttpSession

I'm doing a loggin test app that recive username and password in JSON format and compare the value with the DB. But for some reason the session it's not saved.
This is the method that I use for validate the user info and save the session:
#POST
#Path("/login")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public Response userLogin(Usuario us , #Context HttpServletRequest rq){
HttpSession session ;
//Search for the user with the username provided
Usuario user = usuarioService.getUsuario(us);
//Verify that user != to null
if(user != null){
//verify that password be the same that provided by the client
if(user.getPassword().equals(us.getPassword())){
//Set new Attribute in the session with the user info
session = rq.getSession(true);
session.setAttribute("username" , user.getUsername());
return Response.ok().entity("User:" +user.getUsername() + "has started session with success " + "Session ID : " +session.getId()).build();
}
else{
return Response.ok().entity("Wrong password, please verify and try again" ).build();
}
}else{
return Response.ok().entity("User : "+ us.getUsername()+ " name not found").build();
}
}
The problems come when I try to call the session attribute 'username' where the user name has been saved.
When I try to use a method that retrive the current session id, I found that it's not the same session id that when the username attribute has been added.
The method that I use to verify the session info next:
#GET
#Path("/checkSession")
#Produces(MediaType.APPLICATION_JSON)
public Response userLoginCheck(#Context HttpServletRequest rq){
//Call the current session information
HttpSession session = rq.getSession(false);
String msg;
//Verify if the session is new and return not session available
if( session == null){
msg = " Session not available" + session.getId();
return Response.ok().entity(msg).build();
}else if(session.getAttribute("username") == null){
msg = "Has been not possible call the required session SESSION ID : " + session.getId();
return Response.ok().entity(msg).build();
}
else{ //If session != null & attribute 'username' exist, then call 'username' attribute from the session
return Response.ok().entity(session.getAttribute("user")).build();
}
}
Thanks in advance for any help or idea to solve it.

what is difference between login.jsp and login.jsp?success=1

I am using the following code for login I want to what is the difference between redirecting to main.jsp and main.jsp?success=1
if(flag==1){
HttpSession session = request.getSession(true);
session.setAttribute("ukey",uname );
System.out.println("------------------------------\n"+session.getAttribute("ukey")+" logged in!!!\n------------------------------");
response.sendRedirect("main.jsp?success=1");
}
else
{
//HttpSession session = request.getSession();
System.out.println("------------------------------\nEmail or Password is wrong!!!!!!!!\n------------------------------");
response.sendRedirect("login.jsp?error=1");
//session.setAttribute("error",invalid);
}`if(flag==1){
HttpSession session = request.getSession(true);
session.setAttribute("ukey",uname );
System.out.println("------------------------------\n"+session.getAttribute("ukey")+" logged in!!!\n------------------------------");
response.sendRedirect("main.jsp?success=1");
}
else
{
//HttpSession session = request.getSession();
System.out.println("------------------------------\nEmail or Password is wrong!!!!!!!!\n------------------------------");
response.sendRedirect("login.jsp?error=1");
//session.setAttribute("error",invalid);
}`
what is the differnece between redirecting to main.jsp and main.jsp?success=1
With main.jsp?success=1 you are passing request parameter called success to main.jsp and with main.jsp you aren't passing any request parameters to main.jsp.

Error message when user Fails to Login using Session in JSP and Servlet

My goal is to create an error message when user fails to log in to the system.
I managed to create an error message using session.
However, when I refresh the browser, the error message is still there. It should not appear. Is there a way for me to make the error message invisible when user refresh the browser?
Below are my codes.
Help will be appreciate..Thanks! :)
At login.jsp
<div class="error">
<% String e = (String) session.getAttribute("error" );
if(e != null)
{
out.print(e);
}%>
</div>
At Servlet
HttpSession session = request.getSession(true);
session.setAttribute( "error", "Invalid username or password");
RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
dispatcher.forward( request, response);
Session attributes live for the duration of an HttpSession. Try using request attributes
request.setAttribute( "error", "Invalid username or password");
which only last for the duration of the request.
Otherwise, you will have to remove the attribute from the HttpSession.
you can either the use the request object or you can just check if the session attribute exists in the session and if so you can just remove that.
i.e.
jsp
<% String e = (String) session.getAttribute("error" );
if(e != null)
{
out.print(e);
}else{
out.print("All Is Well");
}>
servlet
HttpSession session = req.getSession(true);
try{
if(null != (session.getAttribute("error"))){
session.removeAttribute("error");
}else{
session.setAttribute( "error", "Invalid username or password");
}
}catch(Exception er){
er.printStackTrace();
}
RequestDispatcher dispatcher = req.getRequestDispatcher("/jsp/LoginTest.jsp");
dispatcher.forward( req, res);

USERNAME PRINTING NULL; javabeans, jsp session

Username is printing NULL, what is the problem here in realtion to the servlet and jsp page. please note i am using javabean here too. i am using same session attribute twice with the bean db.
SERVLET ONE
if(userPassword!=null && userPassword.equals(password)) {
HttpSession session = request.getSession();
BookingBean db = (BookingBean)session.getAttribute("formData"); //use existing session
if(db == null) {
db = new BookingBean(); }
db.setUsername(username);
session.setAttribute("formData", db);
getServletContext().getRequestDispatcher("/BookingForm.jsp").forward(request, response);
} else ......
SERVLET TWO
HttpSession session = request.getSession();
if(!session.isNew()){
db = new BookingBean();
db.setRandom();
db.setAdult(adults);
db.setChildren(children);
db.setOap(oap);
db.setEmail(email);
db.setDate(date);
db.setLocation(loc);
db.setPromo(promo);
db.setTime(time);
db.setfirstName(firstName);
db.setsurName(surname);
db.setTotal();
session.setAttribute("formData", db);
}
JSP PAGE
<jsp:useBean id="formData" class="bean.BookingBean" scope ="session">
</jsp:useBean>
<%BookingBean username = (BookingBean)session.getAttribute("formData");
if(username==null) {
// if session is expired, forward it to login page
%>
<jsp:forward page="Login.jsp" />
<%}%>
<p>Confirmation of Booking for the following user: <%=formData.getUsername()%><p><br><br>
It looks like you are using two different object for your data. Make sure, that you are only using one object. Every servlet should check, if the attribute is already set with a BookingBean instance and use this instance.
Make sure, that you are synchronizing the session object:
synchronized (request.getSession().getId().intern()) {
//dosomething
}
Looks like both your servlets create a new BookingBean when invoked:
db = new BookingBean();
So, when you store it to the session under key "formData", the BookingBean stored by the other servlet gets overwritten. Instead, you need to first check if the session already contains the bean, and create a new one only if there's not one stored in the session.
Here's a simple way to check if the session already has this object:
BookingBean db = (BookingBean)session.getAttribute("formData");
//HttpSession will return null, if there is no object with the given key
if(db == null)
{
db = new BookingBean();
}
//Continue as before...

session id change and attributes copying after login

My application use java servlets,jsp and tomcat 6. I like to implement session id change and want to copy the old session attributes to the new one after login. We started using a little bit of spring in this.
Which is the best way to add this feature to a 10 year old application like this.
If you use Spring Security, the framework should change the session id after login by default.
#see Spring Security FAQ:
Why does the session Id change when I authenticate through Spring Security?
With the default configuration, Spring Security invalidates the existing session when the user authenticates and creates a new one, transferring the session data to it. The intention is to change the session identifier to prevent “session-fixation” attacks. You can find more about this online and in the reference manual
If you do not use Spring (Security) you have to do it by your own. A bit in this way:
public class Login extends HttpServlet {
...
HttpSession session = request.getSession();
Map<String,Object> values = session.GetAll(); //This line is psydo code
//Use getValueNames() and a loop with getValue(String name);
// Kill the current session
session.invalidate();
HttpSession newSession = request.getSession(true);
newSession.putAllValues(values); //This line is psydo code
...
session=request.getSession(true);
Enumeration keys = session.getAttributeNames();
HashMap<String,Object> hm=new HashMap<String,Object>();
while (keys.hasMoreElements())
{
String key = (String)keys.nextElement();
hm.put(key,session.getValue(key));
session.removeAttribute(key);
}
session.invalidate();
session=request.getSession(true);
for(Map.Entry m:hm.entrySet())
{
session.setAttribute((String)m.getKey(),m.getValue());
hm.remove(m);
}
private void regenrateSession(HttpServletRequest request) {
HttpSession oldSession = request.getSession();
Enumeration attrNames = oldSession.getAttributeNames();
Properties props = new Properties();
while (attrNames != null && attrNames.hasMoreElements()) {
String key = (String) attrNames.nextElement();
props.put(key, oldSession.getAttribute(key));
}
oldSession.invalidate();
HttpSession newSession = request.getSession(true);
attrNames = props.keys();
while (attrNames != null && attrNames.hasMoreElements()) {
String key = (String) attrNames.nextElement();
newSession.setAttribute(key, props.get(key));
}
}
This might help
Cookie cookie = new Cookie("JSESSIONID", null);
cookie.setPath("/");
cookie.setMaxAge(0);
response.addProperty(cookie);

Categories

Resources