Home > Java > javaTutorial > body text

Briefly describe session usage and detailed records in java

Y2J
Release: 2017-05-08 13:33:27
Original
5744 people have browsed it

The following editor will bring you a brief discussion of session usage and detailed records in SpringMVC. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Preface

I am new to SpringMVC. Recently, I need to use it to log in to the system I built for the company. session.

I found a lot of information on the Internet and roughly mentioned two ways to save sessions:

1. HttpSession## that is common to javaWeb projects.

#2. SpringMVC-specific @SessionAttributes

I personally pay more attention to the usage of @SessionAttributes. After all, I am using SpringMVC now. But when I read the articles on the Internet, they basically only explained the basic usage, and there were basically no detailed usage and details. I thought this was not enough, so I did some tests myself, and then compiled the code and made a demo. Record and share it. If you have any shortcomings, you are welcome to discuss them.

Okay, enough of the nonsense, now the real show begins!

Conclusion

Well, in order to save some customers who don’t like to read code the trouble of reading the conclusion, I will first summarize my conclusion here. Let’s list the conclusions after the test first.

1. You can automatically save data to the session through SpringMVC's unique ModelMap and Model in the Controller, or you can save session data through traditional HttpSession and other parameters

2. The @SessionAttributes annotation must be used to save session data. This annotation has two parameter declaration methods (value and type), and the annotation declaration must be written on the class, not on the method.

3. The saved session data must correspond to the parameter list in the @SessionAttributes annotation. Undeclared parameters cannot be saved in the session.

4. Use SessionStatus to clear the session saves. Note that all the data is cleared, and the specified session data cannot be deleted individually. At the same time, the effective permissions during clearing follow the above rules 2 and 3 (this rule can be used to artificially achieve the effect of deleting the specified session data)

5. Read the data in the session through ModelMap, etc. , there are also the above parameter permission restrictions

6. When using ModelMap or Model to save session data, ModelMap must be passed in as a method parameter, and the newly defined one in the method is invalid. At the same time, as long as the ModelMap is passed in as a parameter, it will work even if it is called by other methods

#7. When using the @ResponseBody annotation (usually used with ajax), the session cannot be saved Data

8. The @SessionAttributes annotation can use two parameter lists: value and type

9. The traditional method of using HttpSession does not have the above annotations. And permissions and other restrictions, there is a simple test below, but no detailed explanation

There are a few common knowledge points below

10. The operation of session data can be across classes, and it has nothing to do with the package or URL path.

11. If the same session value is operated, the later value will overwrite the previous value

Test code and brief description

Development tools: Spring Tool Suite.

spring is an IDE development tool based on

Eclipse specially developed for SpringMVC. It integrates Maven and Tomcat. I feel pretty good about it after using it recently. I recommend it.

First let’s take a screenshot of the project structure

Briefly describe session usage and detailed records in java

Because the @ResponseBody annotation of ajax is used in the subsequent tests. So configure the jar package in the pom.xml file.

<!-- 使用@ResponseBody注解所需的2个包 -->
<dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-core-asl</artifactId>
 <version>1.9.13</version>
</dependency>
<dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
 <version>1.9.13</version>
</dependency>
Copy after login

The following is the main test code

package test.dmh.session;

import java.util.Enumeration;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

/**
 * @SessionAttributes 只声明了参数test1
 */
@Controller
@SessionAttributes(value={"test1"})
public class HomeController {
 
 private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
 
 @RequestMapping(value = "/show1")
 public String show(ModelMap modelMap, HttpSession session) {
  logger.info("show session");
  for (Object key : modelMap.keySet()) {
   Object value = modelMap.get(key);
   System.out.println(key + " = " + value);
  }
  System.out.println("***********************************");
  Enumeration<String> e = session.getAttributeNames();
  while (e.hasMoreElements()) {
   String s = e.nextElement();
   System.out.println(s + " == " + session.getAttribute(s));
  }
  System.out.println("***********************************");
  return "home";
 }
 
 @RequestMapping("/set1")
 public String setSession(ModelMap modelMap) {
  logger.info("set session 1");
  modelMap.addAttribute("test1", "value 1"); //设置一个在@SessionAttributes中声明过的参数
  modelMap.addAttribute("test2", "value 2"); //设置一个未在@SessionAttributes中声明过的参数
  return "home";
 }
 
 @RequestMapping("/setM")
 public String setSessionM(Model model) {
  logger.info("set session 1");
  model.addAttribute("test1", "value 1"); //设置一个在@SessionAttributes中声明过的参数
  model.addAttribute("test2", "value 2"); //设置一个未在@SessionAttributes中声明过的参数
  return "home";
 }
 
 @RequestMapping("/clear1")
 public String clear(SessionStatus status) {
  logger.info("clear session 1");
  status.setComplete();
  return "home";
 }
 
}
Copy after login
package test.dmh.session.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 没有使用@SessionAttributes注解
 */
@Controller
public class IndexController {
 
 private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
 
 @RequestMapping("/set2")
 public String setSession(ModelMap modelMap, HttpSession session) {
  logger.info("set session 2 : without @SessionAttributes");
  modelMap.addAttribute("test3", "value 3");
  session.setAttribute("test4", "value 4");
  return "home";
 }
 
}
Copy after login
package test.dmh.session.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes(value={"test5", "index"})
public class IndexController2 {
 
 private static final Logger logger = LoggerFactory.getLogger(IndexController2.class);
 
 @RequestMapping("/set3")
 public String setSession(ModelMap modelMap, HttpSession session) {
  logger.info("set session 3");
  modelMap.addAttribute("test5", "value 5");
  session.setAttribute("test6", "value 6");
  
  ModelMap map = new ModelMap();
  map.addAttribute("test7", "value 7");
  
  this.setValueToSession(modelMap, session, "Hello World");
  
  return "home";
 }
 
 @ResponseBody
 @RequestMapping(value="/login")
 public Map<String, Object> login(ModelMap modelMap, HttpSession session) {
  logger.info("login");
  
  Map<String, Object> map = new HashMap<String, Object>();
  
  map.put("success", true);
  map.put("info", "登录成功!");
  
  modelMap.addAttribute("testAjax", "test ajax value");
  session.setAttribute("httpTestAjax", "http test ajax Value");
  
  setValueToSession(modelMap, session, "This is Ajax");
  
  return map;
 }
 
 private void setValueToSession(ModelMap modelMap, HttpSession session, String value) {
  logger.info("set session private");
  modelMap.addAttribute("index", value);
  session.setAttribute("httpIndex", value);
 }
 
 @RequestMapping("/clear2")
 public String clear(SessionStatus status) {
  logger.info("clear session 2");
  status.setComplete();
  return "home";
 }
 
 @RequestMapping(value = "/show2")
 public String show(ModelMap modelMap, HttpSession session) {
  logger.info("show session");
  for (Object key : modelMap.keySet()) {
   Object value = modelMap.get(key);
   System.out.println(key + " = " + value);
  }
  System.out.println("***********************************");
  Enumeration<String> e = session.getAttributeNames();
  while (e.hasMoreElements()) {
   String s = e.nextElement();
   System.out.println(s + " == " + session.getAttribute(s));
  }
  System.out.println("***********************************");
  return "home";
 }
 
}
Copy after login

If this is a project built with STS like me, the default jsp file will have the configuration<%@ page session="false" %> ;, must be deleted or

commented out. Otherwise, the data in the session cannot be displayed on the page. Of course, it is also possible to directly view the background code through the /show test I wrote here.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
4 <html>
<head>
 <title>Home</title>
</head>
<body>
<h1>
 Hello world! 
</h1>

<p> The test1 is ${sessionScope.test1}. </p>
<p> The test2 is ${sessionScope.test2}. </p>
<p> The test3 is ${sessionScope.test3}. </p>
<p> The test4 is ${sessionScope.test4}. </p>
<p> The test5 is ${sessionScope.test5}. </p>
<p> The test6 is ${sessionScope.test6}. </p>
<p> The test7 is ${sessionScope.test7}. </p>
<p> The index is ${sessionScope.index}. </p>
<p> The httpIndex is ${sessionScope.httpIndex}. </p>

<br>
<input type="button" value="test" onclick="test();">

<script src="resources/js/jquery.min.js"></script>
<script type="text/javascript">
function test() {
 $.ajax({
  type : "POST",
  url : "login",
  dataType : "json",
  success : function(data) {
   console.log(data);
   window.open("/session/test", "_self");
  },
  error : function() {
   alert("出错了!");
  }
 });
}
</script>
</body>
</html>
Copy after login

There is also a test code specifically for @SessionAttributes parameter configuration

package test.dmh.session.controller;

import java.util.Enumeration;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes(value={"index1", "index2"}, types={String.class, Integer.class})
public class IndexController3 {
 
 private static final Logger logger = LoggerFactory.getLogger(IndexController3.class);
 
 @RequestMapping("/setIndex")
 public String setSession(ModelMap modelMap) {
  logger.info("set session index");
  modelMap.addAttribute("index1", "aaa");
  modelMap.addAttribute("index2", "bbb");
  modelMap.addAttribute("index2", "ccc");
  modelMap.addAttribute("DDD");
  modelMap.addAttribute("FFF");
  modelMap.addAttribute(22);
  
  return "home";
 }
 
 @RequestMapping(value = "/showIndex")
 public String show(ModelMap modelMap, HttpSession session) {
  logger.info("show session");
  for (Object key : modelMap.keySet()) {
   Object value = modelMap.get(key);
   System.out.println(key + " = " + value);
  }
  System.out.println("***********************************");
  Enumeration<String> e = session.getAttributeNames();
  while (e.hasMoreElements()) {
   String s = e.nextElement();
   System.out.println(s + " == " + session.getAttribute(s));
  }
  System.out.println("***********************************");
  return "home";
 }
 
 @RequestMapping("/clearIndex")
 public String clear(SessionStatus status) {
  logger.info("clear session index");
  status.setComplete();
  return "home";
 }
 
}
Copy after login

A brief description of the test process:

Because there are many parameters, I was too lazy to think of names, so the serialized test1, 2, and 3 passed.

When testing, enter the URL on the browser: localhost:8080/session/show1

Then change the suffix show1 to something else, such as set1, set2 and clear1, clear2, etc., specifically Please see the @RequestMapping configuration in my code.

Every time you enter set1 and set2, you need to enter show1 and show2 to view the contents of the session through the console. Of course, you can also view the display information directly on the browser.

Here I will talk about the main conclusions:

1. To use ModelMap to automatically save data to the session, you must configure the @SessionAttributes annotation

2. The @SessionAttributes annotation can only be declared on a class. After the declaration, the methods in the class can only operate on the parameters configured in @SessionAttributes, including saving, Clear and read.

Finally, there are some conclusions drawn about the parameter configuration in @SessionAttributes:

1. The configuration parameters provide value and type, which are stored in ArrayType. (When there is only one parameter, there is no need to write it in array form, such as @SessionAttributes(value="test1", types=Integer.class))

2. Use value to configure parameters similar to the key-value pairs in Map key

3. After configuring the parameters of the practical type, the key saved in the background is its type. Personally, I feel that it is only useful when saving custom classobject, such as types=User.class , for general common class objects such as String, I think it is better to use value key-value pairs. Of course, specific situations still need to be analyzed on a case-by-case basis.

【Related Recommendations】

1.Java Free Video Tutorial

2.Java Video Tutorial on Implementing Equal-proportion Thumbnails of Pictures

3.FastJson Tutorial Manual

The above is the detailed content of Briefly describe session usage and detailed records in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!