Creating a session cookie inside a controller - spring

I'm new to Tomcat, servlets and Spring Web. I'm coming from a PHP background so I'm a little disoriented to say the least. I want a controller to create a session cookie for me.
I've been told that I can get the session like this in a standard servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Somewhere inside the method...
HttpSession session = request.getSession(true);
// Set a cookie
session.setAttribute("hello", "world");
// More stuff...
}
How does this translate into the Spring Web MVC way of doing things? Can I create session cookies inside a controller?

What you are doing in your example have nothing to do with cookies.
session.setAttribute("key", valueObject);
Sets a java-object in the session. The session is kept at the server. The sessionid is the only thing communicated back to the client. It can be a cookie or it can be in the URL. The attributes in the session is not serialized to strings.
Cookies on the other hand are strings that are sent back to the client. It is the clients responsibility to store their cookies (and some people turn them off) and return them to the server.
Setting a cookie value from a complex object-graph will require serialization and deserialization. A session attribute will not.
If you want to read a cookie, use this:
#CookieValue("key") String cookie
In the controller parameter list. The cookie variable will be populated with the value from the cookie named "key".
To set a cookie, call:
response.addCookie(cookie);

In Java Servlets (and Spring MVC in particular) you don't interact with session cookie directly, actually properly written servlet based application should work without cookies enabled, automatically falling back to URL based session id.
The way you provided is correct, although Spring is giving you much better (higher level) approaches like session-scoped beans. This way you never interact with the session itself.

You can get access to the HttpSession object by including it as a parameter in your controller's method(s):
public String get(Long id, HttpSession session) {
}
Spring will inject the current HttpSession object for you, and from there you can set attributes (like you did in your question).

Related

Save the Spring Security Context back to session for subsequent use

My SpringBoot application is a packaged software application, to customize it I want to manipulate the authentication object when users first login, and I expect this object would be pushed back to the user's session for subsequent connection.
I managed to use an Around advice to intercept a REST endpoint that will be triggered when first login:
#Around("execution( * com.myproject.CurrentUser.get(..)))"
public ResponseEntity getCurrentUser(ProceedingJoinPoint pjp) throws Exception {
SecurityContextHolder.getContext().setAuthentication(getNewAuthentication());
((ServletRequestAttributes) RequestContextController.currentRequestAttributes())
.getRequest().getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING.SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
ResponseEntity response = (ResponseEntity) pjp.proceed();
return response;
}
The getNewAuthentication() method is confirmed OK, it returns a PreAuthenticatedAuthenticationToken that includes additional authorities.
However in the subsequent REST calls when I check the Security Context object the authentication is still the original one.
May I know what would be the proper way to do this? I need to manipulate the authentication object at the very beginning and make sure the subsequent calls will make use of it.
Any idea?

how many way to access the scope variables in spring-mvc

Some one please me to find out the spring mvc examples,
Because usually, once we log in into the application we will create a session and put some objects into session . we will access later point of time , request scope as well. but spring MVC3 is difficult to understand even documentation also confusing, but every one giving example is basic examples only.
You can access these objects in a JSP/JSTL:
applicationScope
cookie
header
headerValues
initParam
pageContext
pageScope
param
paramValues
requestScope
sessionScope
As well as any request attributes that you add, including model attributes (who's default name is command).
More info here: http://www.informit.com/articles/article.aspx?p=30946&seqNum=7
If you want to access HttpRequest, HttpResponse, HttpSession, add them as arguments to a Spring Controller Handler Method . Spring will pass them in for you.

Java Spring 3 - read cookie on application init

I'm writing an very simple authorization system. I doesn't want to use Spring Security.
I want to write very simple auth, based on sessions, cookie and MySQL.
Now, for remember me functionality I want that every time that an page loads, an method will check cookies.
I create init-bean, it works. But when I try read cookie, it fails.
For cookies I need HttpServletRequest. So this is what I do in init-bean:
#Override
public void afterPropertiesSet() throws Exception {
System.out.println("Init-Bean started");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
// Cookie cookies[] = request.getCookies();
//
// for (Cookie c : cookies) {
// System.out.println(c.toString());
// }
}
I fails on getRequest
I get: Error creating bean with name 'auth': Invocation of init method failed; nested exception is java.lang.NullPointerException
Is there any way get HttpServletRequest from init-bean? Is there any other way to this?
What I want is: Page load, read cookies, if cookie exists -> check if user exists in DB -> start session
Tnx.
P.S
I feel lost after mooving from PHP to Spring (in PHP it just global array, 1 row of code). iN asp.net MVC I did it in MvcApplication. But in Java SPRING 3 I has no luck...
I feel lost after mooving from PHP to Spring (in PHP it just global array, 1 row of code)
This sentence makes this question make a whole lot more sense. In Java, the servlet classes are instantiated at server startup, not at request time so when afterPropertiesSet() is called, no request has come in yet (in fact, there's no way a request could have come in because the server hasn't started accepting connections yet). I suggest you check out this SO question. The accepted answer does a great job of explaining the lifecycle of beans, etc. Fundamentally, you will need to rethink the way you handle requests in a Java/Spring environment coming from a PHP environment.

GWT - How to check session in a datasourceservlet?

I have a visualization DataSourceServlet in a GWT application, which is used to generate a data table and return data table to visualization api.
The datasourceservlet can only be accessed by a authenticated user.
I am using getThreadLocalRequest to check for session in other RemoteServiceServlet, but it is not available for DatasourceServlet.
How can i check if the user has a valid session in DatasourceServlet?
According to the javadoc below, DataSourceServlet exposes doGet and doPost methods which contain HttpServletRequest and HttpServletResponse as parameters.
http://code.google.com/apis/chart/interactive/docs/dev/dsl_javadocs/com/google/visualization/datasource/DataSourceServlet.html
You would get the session object from the request parameter like it is done for servlets in general. request.getSession()

Spring MVC, how to have a controller handler handle all the requests before the mapped handlers?

I've wrote a web app with its brave controllers and handler mapping, everything with Spring 3.0 and controller annotations. Now turns out that I need simple and custom autentication. I don't want to use ACEGI for the moment, because I've no time to learn it. I'd like ideally that I could have a routine that gets called before every mapped handler, gets from the HttpSession the userId, checks if he is logged in and the session key and if not redirects to a login page. I've been thinking about an interceptor... the problem is that you have to use HandlerInterceptorAdapter, which has the following method:
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
that won't let me access the HttpSession associated with the request. How do I solve this?
Are you sure? You should be able to obtain the session through request.getSession().

Resources