這篇文章將為大家詳細講解有關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>
<h2>User Login</h2>
<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>
<h2>Login Success Page</h2>
<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>
<h2>User profile Page</h2>
<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;
}
}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[] { "/" };
}
}通過下面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中的屬性

刪除session
@RequestMapping("/endsession")
public String nextHandlingMethod2(SessionStatus status){
status.setComplete();
return "lastpage";
}關于Spring中的 @SessionAttributes注解怎么理解就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。