我在控制器中創建了兩個會話範圍對象,如@SessionAttributes({"userObj","simpleValue"})
。如何在Spring中存儲數據是會話範圍
我加入這些變量中的用戶對象和字符串在我的控制器是這樣的:
modelAndView.addObject("userObj", user);
modelAndView.addObject("simpleValue", "Hello World");
User
類是一個簡單的類與2個屬性id
& name
。假設我在一個名爲Controller1
的控制器中創建了這個控制檯,它顯示了Page1
。我可以在page1
中看到我的會話變量的數據。
現在我創造了另一個控制器說Controller2
(該控制器具有page1
或Controller1
沒有關係),這顯示page2
,現在在這個新的一頁,我只能夠訪問單個會話屬性爲simpleValue
,我不能夠訪問userObj
,我得到空的結果。
按照該@SessionAttributes,它說:
注:由於使用這個註解來表示對應 到指定的處理器的模型屬性,越來越透明地儲存 在對話會話的會話屬性。一旦 處理程序指示完成其會話會話,那些屬性將被刪除。因此, 使用此功能的這種對話屬性 應該在 特定處理程序的對話過程中臨時存儲在會話中。
所以我有2個問題在這裏:
1)我無法理解爲什麼春天讓我訪問page2
簡單的屬性,但不是用戶對象。
2)該文件還說,我們必須使用傳統的session
或WebRequest
。我能夠使用sessison
並訪問變量,但有人可以幫助我如何使用WebRequest
在會話中存儲對象?
這是我使用的代碼:
Controller1.java
@Controller
@SessionAttributes({"mySessionAttr","userObj"})
public class Controller1 {
@RequestMapping(value="/page1")
public ModelAndView singleFieldPage() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("mySessionAttr", "Hello World");
modelAndView.addObject("userObj", new User(1,"Scott"));
modelAndView.setViewName("page1");
return modelAndView;
}
}
Controller2.java
@Controller
public class Controller2 {
@RequestMapping(value="/page2")
public ModelAndView singleFieldPage(HttpSession session) {
return new ModelAndView("page2");
}
}
的Page1.jsp & page2.jsp ,都有相同的代碼。
<p>Session variable : ${simpleValue}</p>
<p>Product's name is ${userObj.name}. The id is ${userObj.id}
這是我的用戶。java的:
公共類用戶{
private int id;
private String name;
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
// Setters & Getters
}
這是我的配置文件:
春基於配置
@Configuration
@ComponentScan("com.examples")
@EnableWebMvc
public class WebAppConfig {
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
基於Web的配置
public class Initializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
你可以發佈User類的實現嗎? –
好友發佈您的控制器1的代碼爲post方法,我有強烈的懷疑,你正在做status.setComplete(); – Mudassar
@FranciscoSpaeth,添加了我的代碼,請檢查並告訴我是否需要其他細節。 – Chaitanya