千家信息网

Spring中的 @SessionAttributes注解怎么理解

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,这篇文章将为大家详细讲解有关Spring中的 @SessionAttributes注解怎么理解,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。@Mode
千家信息网最后更新 2025年02月05日Spring中的 @SessionAttributes注解怎么理解

这篇文章将为大家详细讲解有关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>    org.springframework    spring-webmvc    4.3.10.RELEASE          javax.servlet.jsp.jstl    javax.servlet.jsp.jstl-api    1.2.1        taglibs    standard    1.1.2          javax.servlet    javax.servlet-api    3.1.0    provided          javax.servlet.jsp    javax.servlet.jsp-api    2.3.1    provided  

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.jspuser.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"%>BORAJI.COM  

User Login

Email
Password
${message}

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  pageEncoding="ISO-8859-1"%>     BORAJI.COM        

Login Success Page

You are logged in with email ${user.email}.

View profile

user.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  pageEncoding="ISO-8859-1"%>BORAJI.COM  

User profile Page

First Name ${user.fname}
Middle Name ${user.mname}
Last Name ${user.lname}
Age ${user.age}

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中的属性

删除session

@RequestMapping("/endsession")public String nextHandlingMethod2(SessionStatus status){      status.setComplete();      return "lastpage";}

关于Spring中的 @SessionAttributes注解怎么理解就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

0