[英]How to pass from one jsp to another jsp storing data in session with Spring
我想知道如何針對以下所述的特定方案使用sessionAttributes
和ModelAttributes
:
我有兩個帶有表單字段的jsp頁面。 當我在第一個jsp頁面中輸入表單字段值並單擊下一步時,這些填充的表單字段值應存儲在session屬性中,而不是存儲在數據庫中。 移至第二個jsp頁面后,再次填寫表單字段,然后單擊Submit。 這次,第一個jsp(來自控制器的session屬性)和第二個jsp頁面表單字段值應保存在DB中。
請指導我如何實現這一目標。 如果有任何示例代碼,那將是很大的幫助。
只需將數據存儲在HttpSession上。 您可以使用以下功能從控制器管理會話信息:
private static HttpSession getSession() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attr.getRequest().getSession();
}
public static void clear(String name) {
getSession().removeAttribute(name);
}
public static void clear() {
getSession().invalidate();
}
public static Object load(String name) {
return getSession().getAttribute(name);
}
public static void store(String name, Object value) {
getSession().setAttribute(name, value);
}
Yu可以使用以下命令從jsp訪問會話:
<%= session.getAttribute("attributeName") %>
或搭配
${requestScope.attributeName}
您不需要使用Spring即可實現。 HttpSession是J2EE標准。 在上面的代碼中,Spring用於以這種方式以靜態方式進入會話
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
要獲取會話,您只需要訪問HttpRequest。
在您的控制器中,將值設置為Session Attributes。下面是示例代碼。
@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMethod(HttpServletRequest request){
request.getSession().setAttribute("name", "value");
return "testJsp";
}
}
要在JSP中訪問相同的內容,請使用
${sessionScope.name}
。
Spring MVC文檔中對此進行了介紹:
@Controller
@RequestMapping("/step1")
@SessionAttributes("myModelObject")
public class ControllerOne{
@GetMapping
publid String loadForm(ModelMap modelMap){
//presence of class level @SessionAttributes puts this is session
modelMap.addAttribute("myModelObject", new MyModelObject());
return "form1";
}
@PostMapping
//model attribute retrieved from session
public String handleSubmit(@ModelAttribute("myModelObject") MyModelObject myModelObject){
return "/step2";
}
}
@Controller
@RequestMapping("/step2")
public class ControllerTwo{
@GetMapping
publid String loadForm(){
return "form2";
}
@PostMapping
//model attribute retrieved from session
public String handleSubmit(@ModelAttribute("myModelObject") MyModelObject myModelObject, SessionStatus sessionStatus){
//process
//clear down session
//http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/support/SessionStatus.html
sessionStatus.setComplete();
return "nextView"
}
}
通常,Spring Web Flow對多步驟表單具有更高級的支持:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.