Spring : @SessionAttributes註解
@ModelAttribute註解作用在方法上或者方法的引數上,表示將被註解的方法的返回值或者是被註解的引數作為Model的屬性加入到Model中,然後Spring框架自會將這個Model傳遞給ViewResolver。Model的生命週期只有一個http請求的處理過程,請求處理完後,Model就銷燬了。
如果想讓引數在多個請求間共享,那麼可以用到要說到的@SessionAttribute註解
SessionAttribute只能作用在類上
下面是一個簡單的使用者登入, @SessionAttributes用來將model屬性存在session中
@SessionAttributes("user") public class LoginController { @ModelAttribute("user") public User setUpUserForm() { eturn new User(); } }
上面的程式碼表示,加上
@ModelAttribute
和
@SessionAttributes
註解的作用,
user屬性將會被儲存在session中
@SessionAttribute 提取session中的屬性值
@GetMapping("/info") public String userInfo(@SessionAttribute("user") User user) { //... //... return "user"; }
專案結構
jar 依賴pom.xml
ndency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.10.RELEASE</version> </dependency> <!-- JSTL Dependency --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- Servlet Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- JSP Dependency --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency></dependencies>
Model類 User.java
package com.boraji.tutorial.spring.model; public class User { private String email; private String password; private String fname; private String mname; private String lname; private int age; // Getter and Setter methods }
LoginController.java
package com.boraji.tutorial.spring.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.SessionAttributes; import com.boraji.tutorial.spring.model.User; @Controller@SessionAttributes("user") public class LoginController { /* * Add user in model attribute */ @ModelAttribute("user") public User setUpUserForm() { return new User(); } @GetMapping("/") public String index() { return "index"; } @PostMapping("/dologin") public String doLogin(@ModelAttribute("user") User user, Model model) { // Implement your business logic if (user.getEmail().equals("sunil@example.com") && user.getPassword().equals("abc@123")) { // Set user dummy data user.setFname("Sunil"); user.setMname("Singh"); user.setLname("Bora"); user.setAge(28); } else { model.addAttribute("message", "Login failed. Try again."); return "index"; } return "success"; } }
接下來建立另一個Controller,UserController,通過@SessionAttribute從session中取得use的屬性
package com.boraji.tutorial.spring.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttribute; import com.boraji.tutorial.spring.model.User; @Controller @RequestMapping("/user") public class UserController { /* * Get user from session attribute */ @GetMapping("/info") public String userInfo(@SessionAttribute("user") User user) { System.out.println("Email: " + user.getEmail()); System.out.println("First Name: " + user.getFname()); return "user"; } }
JSP頁面
在 src\main\webapp下 建立新目錄 \WEB-INF\views
然後在該目錄下建立
index.jsp
,
success.jsp
和
user.jsp
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%><!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>BORAJI.COM</title></head><body> <h1>User Login</h1> <form:form action="dologin" method="post" modelAttribute="user"> <table> <tr> <td>Email</td> <td><form:input path="email" /></td> </tr> <tr> <td>Password</td> <td><form:password path="password" /></td> </tr> <tr> <td><button type="submit">Login</button></td> </tr> </table> </form:form> <span style="color: red;">${message}</span> </body></html>
success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>BORAJI.COM</title> </head> <body> <h1>Login Success Page</h1> <p>You are logged in with email ${user.email}.</p> <!-- Click here to view the session attributes --> <a href="/user/info">View profile</a> </body> </html>
user.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>BORAJI.COM</title> </head> <body> <h1>User profile Page</h1> <table> <tr> <td>First Name</td> <td>${user.fname}</td> </tr> <tr> <td>Middle Name</td> <td>${user.mname}</td> </tr> <tr> <td>Last Name</td> <td>${user.lname}</td> </tr> <tr> <td>Age</td> <td>${user.age}</td> </tr> </table></body></html>
Spring配置
在根目錄下建立 WebConfig.java
package com.boraji.tutorial.spring.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration@EnableWebMvc @ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" }) public class WebConfig extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } }
Servlet容器初始化
MyWebAppInitializer.java
package com.boraji.tutorial.spring.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] {}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { WebConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
Build + Deploy + Run application
通過下面maven命令,編譯、打包、部署、執行程式
mvn clean install (This command triggers war packaging)
mvn tomcat7:run (This command run embedded tomcat and deploy war file automatically)
訪問 http :// localhost : 8080 /
輸入使用者名稱和密碼登入成功後,你將看到以下頁面
點選頁面上的“View profi”檢視session中的屬性
譯自: https://www.boraji.com/spring-mvc-4-sessionattributes-example
刪除session
@RequestMapping("/endsession") public String nextHandlingMethod2(SessionStatus status){ status.setComplete(); return "lastpage"; }
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10314474/viewspace-2212413/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Spring註解Spring
- 【Spring註解】事務註解@TransactionalSpring
- SPRING-spring註解整理Spring
- Spring boot註解Spring Boot
- Spring新註解Spring
- Spring註解大全Spring
- Spring常用註解Spring
- Spring Boot系列十八 Spring AOP + 註解實現統一註解Spring Boot
- Spring系列之新註解配置+Spring整合junit+註解注入Spring
- Spring 註解程式設計之模式註解Spring程式設計模式
- Spring: @ModelAttribute註解用法Spring
- Spring(使用註解配置)Spring
- Spring-註解注入Spring
- spring註解開發Spring
- spring boot 註解@ComponentSpring Boot
- Spring註解之@ConditionalSpring
- Spring註解?啥玩意?Spring
- Spring 註解開發Spring
- Spring註解之@ImportSpringImport
- Spring註解簡析Spring
- spring 框架常用註解Spring框架
- Spring註解系列——@PropertySourceSpring
- Spring IoC 公共註解詳解Spring
- Spring AOP的AspectJ註解Spring
- 【Spring 註解】@Configuration和@BeanSpringBean
- Spring Boot註解 之 @RequestXSpring Boot
- Spring條件註解@ConditionalSpring
- Spring Cache快取註解Spring快取
- Spring中重要的註解Spring
- Spring @Transactional註解淺談Spring
- Spring 框架快取註解Spring框架快取
- Spring的註解開發Spring
- Spring的@PropertySource註解使用Spring
- Spring典型註解-@Controller,@Component,@SpringController
- Spring註解補充(一)Spring
- 【spring 註解】第3篇:@Scope、@Lazy和@Conditional註解Spring
- Spring註解開發_Spring容器建立概述Spring
- spring通過註解註冊bean的方式+spring生命週期SpringBean