Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the session from a Java class

I need to write a small Java class that will enable me to add to and read from the current user session.

Everything I see refers to Servlets but I'd ideally like to just use a plain old class.

Can anyone please help this Java Newbie?

Thanks

like image 986
griegs Avatar asked Oct 13 '22 23:10

griegs


2 Answers

The general concept of a "Session" is really just a data storage for an interaction between a HTTP client and server. Session management is automatically handled by all HTTP Servlets. What framework?

If you're just wanting to store information for a console app to remember information between runs, then consider using Xml to save/load data from a file.

like image 175
Sam Day Avatar answered Oct 19 '22 02:10

Sam Day


Use a component based MVC framework which abstracts all the ugly Servlet API details away so that you ends up with zero javax.servlet imports. Examples of such are JSF2 and Struts2.

In JSF2 for example, you'd just declare User class as a session scoped managed bean:

@ManagedBean
@SessionScoped
public class User {
    // ...
}

Then in the "action" bean which you're using to processing the form submit, reference it as managed property:

@ManagedBean
@RequestScoped
public class SomeFormBean {

    @ManagedProperty(value="#{user}")
    private User user;

    public void submit() {
        SomeData someData = user.getSomeData();
        // ...
    }
}

That's it.

If you'd like to stick to raw Servlet API, then you've to live with the fact that you have to pass the raw HttpServletRequest/HttpServletResponse objects around. Best what you can do is to homegrow some abstraction around it (but then you end up like what JSF2/Struts2 are already doing, so why would you homegrow -unless for hobby/self-learning purposes :) ).

like image 42
BalusC Avatar answered Oct 19 '22 03:10

BalusC