PDA

View Full Version : session attribute in spring mvc 2.5


hikozaemon
Dec 7th, 2007, 03:48 AM
Hello,

I want to get object from HttpSession in Spring MVC2.5.

Now, I am get User object from session like below.

@RequestMapping("/foo.htm")
public String foo(HttpSession session) {
User u = (User)session.getAttribute("login-user");
Integer id = u.getId();
List<Product> list = service.getProducts(id);

...
}


I think many method need to reference login-user object.
but, I don't know how to get it without HttpSession class on method parameter.

For testability, I dont want to use HttpSession class on Controller.
Any good idea?

mirror303
Dec 7th, 2007, 05:26 AM
Using bean session scope maybe what you need.

Take a look at:
http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes-session

and

http://www.memestorm.com/blog/session-scoped-beans-in-spring-20/

Good luck,
hans

Marten Deinum
Dec 7th, 2007, 05:42 AM
Or simply use the SessionAttribute annotation...



@SessionAttributes("login-user")
public class YourClass {

@RequestMapping("/foo.htm")
public String foo(@ModelAttribute("login-user") User u) {
Integer id = u.getId();
List<Product> list = service.getProducts(id);
}

hikozaemon
Dec 9th, 2007, 11:48 PM
thanks mdeinum, that is the code I really want.

thanks mirror303, it is interesting.
I think it is very good to save objects to HttpSession.
Is there any good way to set authentication object to field on initilalizing this controller?
Annotation-based is much better.

villaruzeric
Feb 13th, 2008, 11:47 AM
Hi Marten,

I have a similar implementation to your sample but it is failing. I hope you could assist.
I have a login_user 'session' bean defined
<bean id="login_user" class="com.villaruz.tipunan.user.User" scope="session">
</bean>
On my annotated controller
...
@SessionAttributes("login_user")
@Controller
public class TipunanController {
....
@RequestMapping("/welcome.egv")
public ModelMap welcomeHandler(@ModelAttribute("login_user") User user) {
logger.info("executing request mapping... welcome.egv with hard coded U630339 user");
user = this.tipunan.getUser("U630339");

return new ModelMap(user);
}
...

However, I am getting the following error
SEVERE: Servlet.service() for servlet tipunan threw exception
org.springframework.web.HttpSessionRequiredExcepti on: Session attribute 'login_user' required - not found in session

I am using Spring 2.5 and Java 1.6

Any assistance you could provide is greatly appreciated.
-Eric

Or simply use the SessionAttribute annotation...



@SessionAttributes("login-user")
public class YourClass {

@RequestMapping("/foo.htm")
public String foo(@ModelAttribute("login-user") User u) {
Integer id = u.getId();
List<Product> list = service.getProducts(id);
}

Marten Deinum
Feb 13th, 2008, 01:10 PM
session scoped beans ans properties/beans which are a SessionAttribute are 2 completly different things.