这篇文章将为大家详细讲解有关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注解怎么理解就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/10314474/viewspace-2212413/