USERNAME PRINTING NULL; javabeans, jsp session - java

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...

Related

Spring MVC #SessionAttribute Missing session attribute of type String[] error

I was having some problem when trying to use #SessionAttribute in Spring MVC Controller. Basically what I am trying to do is, in my API, I want to retrieve from the session, if it contains data, fetch it out, then remove the session itself. Here is my controller class:
#SessionAttributes({WebKeys.SEARCH_RESULT_LIST_THREE})
public class ALController {
#RequestMapping(value = "/search.do", method = { RequestMethod.POST })
public String doSearchList(Model model, #ModelAttribute("attendanceTO") AttendanceTO attendanceSearchForm, #SessionAttribute(WebKeys.SEARCH_RESULT_LIST_THREE) String[] selectedRecords) {
// removed code
attendanceSearchForm.setSelectedRecords(null);
// checking from session
if(selectedRecords != null && selectedRecords.length > 0){
attendanceSearchForm.setSelectedRecords(selectedRecords);
}
model.addAttribute("selectedRecords", selectedRecords);
// remove session
model.addAttribute(WebKeys.SEARCH_RESULT_LIST_THREE, null);
}
}
At this point of time, the session is not existed yet. I only set up the session when user submit form. I am getting this error messages:
Missing session attribute 'key.searchResultList.three' of type String[]
Any ideas on how to resolve this? Thanks!
U should add a required parameter to the #SessionAttribute annotation and set its value to false,meaning it's not necessary,like
#SessionAttribute(name=WebKeys.SEARCH_RESULT_LIST_THREE,required=false)

Wicket tests: mock attribute to HttpSession

guys.
I have the following code for my http session at Wicket-based application:
public static HttpServletRequest getHttpServletRequest() {
Request request = RequestCycle.get().getRequest();
if (request != null && request instanceof WebRequest) return
HttpServletRequest) request.getContainerRequest();
return null;
}
public static SessionObject getSessionObject() {
HttpServletRequest request = getHttpServletRequest();
HttpSession session = request == null ? null : request.getSession();
SessionObject so = session == null ? null : (SessionObject) session.getAttribute("so");
if (so == null) {
logger.warn("SessionObject is not found in HttpSession!");
}
return so;
}
The session object is initialized at jsp like the following:
jsp:useBean id="so" class="package.SessionObject" scope="session"
I'd like to mock this attribute so into Wicket tests.
Tried to do the following:
bind(SessionObject.class).toInstance(EasyMock.createMock(SessionObject.class));
also
tester = new WicketTester(new MockApplication() {
#Override
public Session newSession(Request request, Response response) {
final Session session = super.newSession(request, response);
session.setAttribute("so", EasyMock.createMock(SessionObject.class));
return session;
}
});
But when I try to call method as:
init(){
a = getSessionObject().getA();
}
getSessionObject() returns null because there are no attribute named "so".
Could you help please me to mock this attribute into session?
You can simplify your helper methods to: Session.get().getAttribute("so").
Your code that writes the value already uses Session#setAttribute().
Try by binding the session: Session#bind(). Unless bound Wicket will create a new instance of Session for each request. Once bound Wicket will acquire HttpSession and store Wicket's Session into it (as attribute).
If this doesn't help then put a breakpoint at Session set/getAttribute() methods and see what happens.

Struts setSesssion() is not working

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.

Getting User Name from Within HttpSessionListener

I would like to get the username from within HttpSessionListener.sessionCreated(). When I say username, I mean specifically that name that is returned by HttpServletRequest.getRemoteUser().
Obviously, there must have been a HttpServletRequest object that caused the session to be created (and hence the sessionCreated() call). But how do I access it from within sessionCreated()? The HttpSessionEvent object passed into sessionCreated() appears to provide no way to get at the HttpServletRequest object that caused the session to be created.
The HttpSessionListener does not have access to the HttpServletRequest object because it is invoked when no request has been made—to notify of session destruction or creation.
So, a Filter would be better places where you can add username = request.getRemoteUsr() into session.
Example - Filter Code
String username = request.getRemoteUsr() ;
session.setAttribute("username",username);
and then retrive this username in sessionCreated method as
String username = (String)session.getAttribute("username");
i hope you will get the same username of the same request which has created this session in HttpSessionListener sessionCreated() method.
// set
session.setAttribute("username", request.getRemoteUser();
// get
String un = (String) session.getAttribute("username");
You could use a HttpSessionAttributeListener:
public class UsernameHttpSessionAttributeListener implements HttpSessionAttributeListener {
#Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
if (httpSessionBindingEvent.getName().equals("username")) {
// do something
}
}
...
}
Of course, you need to set the attribute username in the HTTP session anywhere, for instance in a servlet filter.

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