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

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);

Related

Is there any way to return a View and ResponseBody at the same time using only one method?

I need some help from you all. Basically it has a base path at the class level (/grade), So the first method will return the jsp page to the user and second method will actually handle the request send from the client using xhr with GET method. So when it send the response I am able to handle it, but when i try to reload with the url http://localhost:8080/grade/12323 it returns me object not the page.
#GetMapping
public String getGradePage(HttpServletRequest request,Model model) {
HttpSession session = request.getSession();
User user = new User();
user.setUsername("1010000001");
user.setPassword("b");
session.setAttribute("user", user);
List<Course> courseList = gradeService.getAllClassById(user.getUsername());
model.addAttribute("courseList",courseList);
return "lecturer/submit-grade";
}
#GetMapping("/{courseCode}")
#ResponseBody
public List<Enrollment> submitGrade(#PathVariable String courseCode) {
List <Enrollment> enrollmentList = gradeService.getAllStudentEnrollmentById(courseCode);
return enrollmentList;
}
just solved it by changing the endpoint in my javascript xhr, what a silly mistake ..

Get all active HttpSession in RESTEasy implementaion

I need to get list of all the active Session so that I can manage them. Basically I need to manage all the logged in Users in application.
Using HttpServletRequest req I am able to get current session but
need to get all the sessions
Something like this:
public EmployeeTO getEmployeeById(int id, HttpServletRequest req) {
EmployeeTO employeeTO = null;
try{
HttpSession session = req.getSession();
HttpSessionContext httpSessionContext = session.getSessionContext();
}catch(Exception e){
e.printStackTrace();
}
return employeeTO;
}
Am using RESTFul implementation with JASS for Login
I have a screen which shows the list of all active Users. If I check one
User and click close session. I need to terminate that users session.
To do that I need to have sessions somewhere accessible.
Using the HttpServletRequest, you will be able to get only the current request's (user's) session object. But if you want to track all session objects, you can do that by implementing HttpSessionListener as shown below:
public class MyProjectSessionListenerAndInvalidator
implements HttpSessionListener {
private static Map<String,Session> sessions = new HashMap<>();
#Override
public void sessionCreated(HttpSessionEvent event) {
//add your code here,
//this will be invoked whenever there is a new session object created
//Get the newly created session
Session session = event.getSession();
//get userId or unique field from session
sessions.put(userId, session);
}
#Override
public void sessionDestroyed(HttpSessionEvent event) {
//add your code here
//this will be invoked whenever there is a new session object removed
//Get the removed session
Session session = event.getSession();
//get userId or unique field from session
sessions.remove(userId);
}
public R getSessions() {
//add code here
}
public void invalidateSession(String userId) {
//add code here
}
}
N.B.: I recommend to use getSessions() and invalidateSession() carefully.

EasyMock - request.getSession is null

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.

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 can I save information for current user in Spring & Hibernate?

I have a User table and a UserInfo table which keeps the personal information of the user. What I am trying to do is adding personel information after log in. There is OneToOne relationship between tables with userId column so I defined it like this :
UserInfo class :
public class UserInfo {
//...
#OneToOne
#JoinColumn(name="user_id")
private User user;
// ...
}
User class :
public class User implements UserDetails {
// ...
#OneToOne(mappedBy="user", cascade = CascadeType.ALL, fetch=FetchType.LAZY,optional=true)
private UserInfo userInfo;
...
}
After I log in, I want to add some user information to the db for current user. But I don't know how can i save user information in controller? Should I save User object like below? I've searched about it and there is a way to get current user's information:
(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
But when I try to use it in the controller it just returns null. How can I do such operations (adding pers. info) for logged in user?
#RequestMapping(value = "/show", method = RequestMethod.POST)
public ModelAndView newUser(ModelMap model, Principal principal) {
ModelAndView result = new ModelAndView("home");
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserInfo userinfo = new UserInfo();
userinfo.setPlacesVisit(userinfo.getPlacesVisit());
user.setUserInfo(userinfo);
userService.save(user);
String message = "Userinfo was successfully added.";
result.addObject("message", message);
return result;
}
instead of saving current object update current object. First get current user object in controller after that set UserInfo then update user object in database.
#RequestMapping(value = "/show", method = RequestMethod.POST)
public ModelAndView newUser(ModelMap model, Principal principal) {
String userName=principal.getName(); // username or email using user login
User user=userService.getUserByName(userName); // retrieve current user information
UserInfo userinfo = new UserInfo(); // create userinfor object
userinfo.setPlacesVisit(userinfo.getPlacesVisit());
user.setUserInfo(userinfo); // set userinfo to user
userService.update(user); // update user
String message = "Userinfo was successfully added.";
result.addObject("message", message);
return result;
}
You can retrieve to user with the Principal parameter :
public ModelAndView newUser(ModelMap model, Principal principal) {
User activeUser = (User) ((Authentication) principal).getPrincipal();
}
SecurityContextHolder is a part of Spring Security. If you want to use this component, you have to set up Spring Security for the log in of your application to be able to retrieve, in your REST controller, the current user (javax.security.Principal)
Spring Security Documentation
You can use session to save session attributes. In spring, you can access session using
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession();
You can save your logged user in session:
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
request.getSession().setAttribute("key", user);
and if you want get currently logged user, just:
(User) user = ((HttpServletRequest) request).getSession().getAttribute("key")
This example is in JSF, but I am sure that is also possible without JSF

Categories