EasyMock - request.getSession is null - java

I am testing the following method:
public static String createSn(HttpServletRequest request, String usrnm) {
HttpSession session = request.getSession(true);
session.setAttribute("UserID", usrnm);
return session.getId();
}
With my JUnit test code:
HttpServletRequest request = createNiceMock(HttpServletRequest.class);
HttpSession session = createNiceMock(HttpSession.class);
expect(request.getSession()).andReturn(session);
replay(request);
replay(session);
String username="testuser";
String snID = LogInUtils.createSn(request, username);
However, these Lines seem to produce a Null Pointer Exception:
HttpSession session = request.getSession(true);
session.setAttribute("UserID", usrnm);
In conclusion request.getSession(true) dosen't seem to work for my Mock Request. Where did I went wrong?
Thank you for your input :)

You should use:
expect(request.getSession(true)).andReturn(session);
In your example you mock the method request.getSession() which is not called in your code.

Related

Losing Attribute Hashmap in Session

I'm facing a trouble when try to get the hashmap from session. Below are my code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String passWord = request.getParameter("passWord");
HttpSession session = request.getSession();
User user = new User(userName, passWord);
if(LoginUtils.DoInsert(user) == null) {
Map<String, User> listUser = (HashMap<String, User>) session.getAttribute("listUser");
User Sessionuser = (User)session.getAttribute("user");
response.sendRedirect("index.jsp");
}
else {
session.setAttribute("listUser", LoginUtils.getListUser());
session.setAttribute("user", user);
response.sendRedirect("index.jsp");
}
}
The first time, I persist Attribute listUser to session (else block) but the second time, when I tried to retrieve listUser, it get null here (if block). As the debugging, I can see, user Object is still inside the session but the listUser is not. This issue only happens when I use Eclipse, Netbeans works fine. I have tested on both IDE with the same code.
I'm not sure is something wrong with my code or Eclipse
Please give me some advices. Thanks so much

I want to get the session value from the controller method on jsp. can someone help me out how i can do this

I want to get the session value from the controller method to jsp. can someone help me out how i can do this
controller.java
#RequestMapping(value="customerLogin.do", method=RequestMethod.POST)
public String customerLogin(HttpServletRequest request, HttpSession session,HttpServletResponse response) throws SQLException, IOException{
String customerEmail=request.getParameter("customerEmail");
String password= request.getParameter("customerPassword");
Boolean isLoggedIn=false;
Customer customer= serviceInter.logincustomer(customerEmail, password);
if(customer!=null){
isLoggedIn=true;
}
response.getWriter().write(new Gson().toJson(isLoggedIn));
session.setAttribute("customerInfo", customer);
return null;
}
Let I need to get that value here Hello< customername>
You could get it by using following statement:
Customer customer = (Customer) session.getAttribute("customerInfo");
//System.out.println(customer.getFirstName());
How are you retrieving in your JSP?
What is the error you are getting?
${customerInfo.name}
OR
Customer customer = (Customer) session.getAttribute("customerInfo");
2nd option: You can also make the Controller to be session scoped.
#Controller
#Scope("session")
public class SessionScopedController

How to check in servlet that is an user new with session?

I am very new to java servlet programming. I have been writing a simple program for practicing java session. There are two .jsp file. first one called index.jsp, and another one is selection.jsp. And there is a servlet called controller. At first the index.jsp will be called, and user will be submit a input. That will be redirect in servlet controller. In that servlet will check whether it is new request or not. If new then it redirect to other page, else will do some other work.
I am checking whether it is new request or not by session.isNew() method. But it always says it is not new session. But, if I disable the browser cookies option then it is working fine. Now what is my observation is that when in the first I request the index.jsp to the container it assign a session along with that request. So when it comes to servlet it treat as a old session. I got this idea from Head first book Servlet and JSP.
Here is my servlet code -
public class Controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user;
HttpSession session = request.getSession(false);
if (session == null) {
user = request.getParameter("user");
if (user == null) {
response.sendRedirect("index.jsp");
}
session.setAttribute("username", user);
SelectItem selectItem = new SelectItem();
selectItem.setUser(user);
response.sendRedirect("selection.jsp");
session.setAttribute("selectItem", selectItem);
} else {
String selectionItem = request.getParameter("selection");
SelectItem selectItem = (SelectItem) session.getAttribute("selectItem");
if (selectItem != null) {
selectItem.add(selectionItem);
session.setAttribute("selectItem", selectItem);
}
response.sendRedirect("selection.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
So, how to determine whether it is a new session or old one? Thank you.
HttpSession.isNew API:
Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.
So, you're getting true because the client has cookies disabled. The "new session" check in done in the else block of this check:
HttpSession session = request.getSession(false);
if (session == null) {
// create new session
session = request.getSession();
} else {
// existing session so don't create
}
In your code, you don't appear to be creating a new session when a new session is detected. Perhaps that's where you're stumbling.
Note: learning the basic Servlet API is a good thing. However, for my professional work I use frameworks which simplify my programming, like Spring Boot and Spring Security.

HTPPSession with Google Cloud Endpoints new session every time

I am successfully using Google Cloud Endpoints. Now for custom user auth, I want to use HTTPSession. The problem is, the initial session is not being reused in future calls, and new session are created (I can see from datastore admin that the session all exists, _AH_SESSION entity). As instructed in the docs, i have enabled it in appengine-web.xml:
<sessions-enabled>true</sessions-enabled>
I made some sample code to narrow it down:
#Api(name = "loginService", version = "v0.1.5")
public class LoginService {
private static final Logger log = Logger.getLogger(LoginService.class.getName());
#ApiMethod(name = "login", path= "login")
public LoginResponse login(HttpServletRequest req)
{
HttpSession session = req.getSession(false);
if(session == null){
log.warning("creating new session");
session = req.getSession(true);
}
LoginResponse resp = new LoginResponse();
resp.statusCode = 200;
resp.statusMessage = "SessionId:" + session.getId();
return resp;
}
#ApiMethod(name = "show", path= "show")
public LoginResponse show(HttpServletRequest req)
{
//session should exist when calling LOGIN first
HttpSession session = req.getSession(false); //NULLPOINTER since session from login is not being reused/found!
LoginResponse resp = new LoginResponse();
resp.statusCode = 200;
resp.statusMessage = "SessionId:" + session.getId();
return resp;
}
public class LoginResponse implements Serializable{
public int statusCode;
public String statusMessage;
}
}`
So first, I call the login method, this creates a new session and prints me the session id. Then in the next request (both using Postman - which should track sessions - in Chrome as the API explorer) i call the 'show' endpoint, and there the previous session does not exist anymore, hence the nullpointer exception.
In the comments on this post, user mikO says endpoints don't keep the session. Is this the reason? I don't really understand the reason behind it. When I just deploy a 'regular' servlet on appengine, it DOES work using Postman or just browsing.. (testing by calling the getter twice, i see that the previous session is being picked up), so it seems that the comment in that post could be right, but i really don't understand why. Working code without endpoints:
public class LoginServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(LoginServlet.class.getName());
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession s = request.getSession(false);
if (s == null) {
log.warning("creating new session");
s = request.getSession(true);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + s.getId() + "</h1>");
}
}
Thanks!

How to retrieve Http session data in multiple Methods within a class

I need to retrieve users profile from Http Session. Since I need the same profile in couple different methods within the class is there a way that all the method access the same session? So I dont have to put the http request multiple times. Below is the example of session and methods.
In the below methods you will see im putting the http request in both methods since they are both in same class it would help if I dont create seprate sessions.
Http Request:
HttpSession session = request.getSession();
EntRProfile profile = (EntRProfile) session.getAttribute("profile");
Sample methods:
private Integer getClaimCount(HttpServletRequest request, String searchCriteria) throws Exception {
HttpSession session = request.getSession();
EntRProfile profile = (EntRProfile) session.getAttribute("profile");
Integer claimsCount = claimTDAO.getCountOfClaimsWithCurrentStatusNot(profile, "INI", searchCriteria);
request.getSession().setAttribute("claimsPaginationCount", claimsCount);
return claimsCount;
}
2nd Method
#RequestMapping(value = "/claims_history", method = RequestMethod.GET)
public String getClaims(HttpServletRequest request, #RequestParam(value = "claimsSearch", required = false) String searchCriteria, boolean keepOffset) throws Exception {
HttpSession session = request.getSession();
EntRProfile profile = (EntRProfile) session.getAttribute("profile");
request.getSession().setAttribute("claimsList", claimsList);
request.getSession().setAttribute("claimsSearchCriteria", searchCriteria);
Integer count = claimTDAO.getCountOfClaimsWithCurrentStatusNot(profile, "INI");
request.setAttribute("claimsHistoryCount", count);
return "claims_history";
}
You can create a private method in your controller:
private EntRProfile getProfile(HttpServletRequest request) {
HttpSession session = request.getSession();
EntRProfile profile = (EntRProfile) session.getAttribute("profile");
return profile;
}
Then you can get the profile by calling:
EntRProfile profile = getProfile(request);

Categories