Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the @ SessionAttributes annotation in Spring

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to understand the @ SessionAttributes annotation in Spring. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

The @ ModelAttribute annotation acts on the method or the parameter of the method, indicating that the return value of the annotated method or the annotated parameter is added to the Model as a property of Model, and then the Spring framework will pass the Model to ViewResolver. There is only one http request process in the life cycle of Model, and after the request is processed, the Model is destroyed.

If you want parameters to be shared among multiple requests, you can use the @ SessionAttribute annotation you want to talk about

SessionAttribute can only be used on classes

Here is a simple user login, @ SessionAttributes, used to store the model attribute in session

@ SessionAttributes ("user") public class LoginController {@ ModelAttribute ("user") public User setUpUserForm () {eturn new User ()}

The above code indicates that, with @ ModelAttribute and @ SessionAttributes annotations, the user property will be stored in session

@ SessionAttribute extracts attribute values from session

@ GetMapping ("/ info") public String userInfo (@ SessionAttribute ("user") User user) {/ /... /. Return "user";}

Project structure

Jar depends on 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 class 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 ";}}

Next, create another Controller,UserController and get the properties of use from session through @ SessionAttribute

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 page

Create a new directory under src\ main\ webapp\ WEB-INF\ views

Then create index.jsp, success.jsp, and user.jsp in this directory

Index.jsp

BORAJI.COM User Login Email Password Login ${message}

Success.jsp

BORAJI.COM Login Success Page

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

View profile

User.jsp

BORAJI.COM User profile Page First Name ${user.fname} Middle Name ${user.mname} Last Name ${user.lname} Age ${user.age}

Spring configuration

Create a WebConfig.java under the root directory

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 container initialization

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

Compile, package, deploy, and run the program through the following maven command

Mvn clean install (This command triggers war packaging)

Mvn tomcat7:run (This command run embedded tomcat and deploy war file automatically)

Visit http://localhost:8080/

After entering the user name and password to login successfully, you will see the following page

Click "View profi" on the page to view the properties in session

Delete session

@ RequestMapping ("/ endsession") public String nextHandlingMethod2 (SessionStatus status) {status.setComplete (); return "lastpage";} how to understand the @ SessionAttributes annotation in Spring is shared here. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report