target
- Understand HTTP request/response headers and common properties;
- Learn how to use SpringBoot to process header information;
- Learn how to use SpringBoot to handle cookies;
- Learn how to read and write Session s;
- Learn how to pass flash parameters between different requests
1. Http Header Information
HTTP headers are additional content independent of request and response content.
A large number of features in the HTTP protocol are achieved through Header information interaction, such as content coding, caching, connection preservation, and so on.
Response to one of the following requests:
Request
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cache-Control: max-age=0 Connection: keep-alive Host: www.cnblogs.com If-Modified-Since: Wed, 18 Jul 2018 13:47:45 GMT Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Name | purpose |
---|---|
Accept | List of MIME types expected by the client |
Accept-Encoding | Client Expected Codec Method |
Accept-Language | The language expected by the client |
Cache-Control | Cache Control |
Connection | Connection behavior (keep-alive) |
Host | Host requesting access |
If-Modified-Since | Cache Control |
Upgrade-Insecure-Requests | Supports Secure Encryption Tags |
User-Agent | User Agent (Client Identity) |
Response
Cache-Control: private, max-age=10 Connection: keep-alive Content-Encoding: gzip Content-Type: text/html; charset=utf-8 Date: Wed, 18 Jul 2018 13:47:51 GMT Expires: Wed, 18 Jul 2018 13:48:01 GMT Last-Modified: Wed, 18 Jul 2018 13:47:51 GMT Transfer-Encoding: chunked Vary: Accept-Encoding X-Frame-Options: SAMEORIGIN X-UA-Compatible: IE=10
Name | purpose |
---|---|
Cache-Control | Cache Control |
Connection | Connection behavior (keep-alive) |
Content-Encoding | Codec method |
Content-Type | Content Type (MIME) |
Date | Current Response Time |
Expires | Document expiration time |
Last-Modified | Last Update Time |
Transfer-Encoding | Transmit Encoding Method |
Vary | Request Header that needs refresh |
X-Frame-Options | FRAME Display Strategy (for Homology Control) |
X-UA-Compatible | IE Compatibility Properties |
More ** Http Header ** can be obtained from Find it here
2. SpringBoot processes header information
The previous section has described how to complete the Controller method and the requested mapping.
SpringBoot can be annotated via @RequestHeader
Map the request header information to the parameters, as in the following snippet:
@GetMapping("/some") @ResponseBody public String someHeader(@RequestHeader(value = "Host") String host, @RequestHeader(value = "User-Agent") String userAgent, @RequestHeader(value = "Cache-Control", required = false) String cacheControl, HttpServletResponse response) { logger.info("host:{}", host); logger.info("User-Agent:{}", userAgent); logger.info("Cache-Control:{}", cacheControl); // Set Response Header response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); return "OK"; }
Instead, a response header can be declared by declaring an HttpServletResponse parameter.
The above code is easy to understand by setting it up with this object.
If you want to get all the request headers, you can use the HttpHeaders object:
@GetMapping("/all") public ResponseEntity<Map<String, List<String>>> allHeaders(@RequestHeader HttpHeaders headers) { Map<String, List<String>> valueMap = new HashMap<String, List<String>>(); for (String header : headers.keySet()) { valueMap.put(header, headers.get(header)); logger.info("header[{}]={}", header, headers.get(header)); } // Set Response Header via ResponseEntity ResponseEntity<Map<String, List<String>>> entity = ResponseEntity.status(HttpStatus.OK) .header("new header", UUID.randomUUID().toString()).body(valueMap); return entity; }
In the above section of code, you can print out all the request header information.
Also note that the return response uses a ResponseEntity object, which is a direct representation
Response Header information can be easily set by ResponseEntity for objects that respond to information headers and content.
3. Cookie Processing
Cookie s begin with information that the server logs on the browser to identify user information.
Cookie s as client-side storage have so far been used in many scenarios.
SpringBoot provides @CookieValue to support parameter injection as follows:
@GetMapping("/some") @ResponseBody public String someCookie(@CookieValue(value = "counter", defaultValue = "0") int counter, HttpServletResponse response) { logger.info("counter:{}", counter); counter += 1; String newValue = counter + ""; // Set Cookie s response.addCookie(new Cookie("counter", newValue)); return newValue; }
In the above code, access/some to get a counter cookie value.
And each visit increases itself, which is a simple access counter function.
If you want to get all Cookie s, you can refer to the following code:
@GetMapping("/all") public ResponseEntity<Map<String, String>>allCookies(HttpServletRequest request, HttpServletResponse response) { Map<String, String> valueMap = new HashMap<String, String>(); for (Cookie cookie : request.getCookies()) { valueMap.put(cookie.getName(), cookie.getValue()); logger.info("cookie[{}]={}", cookie.getName(), cookie.getValue()); } // Set Cookie s response.addCookie(new Cookie("key", UUID.randomUUID().toString())); return new ResponseEntity<Map<String, String>>(valueMap, HttpStatus.OK); }
Clean up all cookies
@GetMapping("/clear") public ResponseEntity<Map<String, String>> clearCookies(HttpServletRequest request, HttpServletResponse response) { Map<String, String> valueMap = new HashMap<String, String>(); for (Cookie cookie : request.getCookies()) { valueMap.put(cookie.getName(), cookie.getValue()); logger.info("cookie[{}]={}", cookie.getName(), cookie.getValue()); // Eliminate cookie.setMaxAge(0); response.addCookie(cookie); } return new ResponseEntity<Map<String, String>>(valueMap, HttpStatus.OK); }
Cookie mechanism has some drawbacks and should be used when possible with some risk in mind
- Security cannot be guaranteed unless HTTPS is used;
- Browser-side storage limit of only 4KB;
IV. Session Processing
Session refers to a session and is an identification method based on a Cookie mechanism.
Because of the security and capacity limitations of cookies themselves, most applications store a unique credential in a Cookie.
The service side accesses identity information through credentials, which is the origin of the session.
Different languages and frameworks use different implementations, such as JavaEE with JSESSION_ID and PHP with PHPSESSID
Session's interaction principle can be referred to in the following figure:
Springboot has a built-in Servlet container, which is the JSESSION_ID that is followed.So you'll find this Cookie when you browse some Java Web sites.
Use @SessionAttribute to map attributes in a session to method parameters;
If you want to manipulate the Session property, you can declare the @SessionAttributes annotation on the Controller to specify the property you want to change.
After that, write through the Model parameter (Session is automatically detected and modified by the framework)
@SessionAttributes("seed") public class SessionController { private static final Logger logger = LoggerFactory.getLogger(SessionController.class); @GetMapping("/some") @ResponseBody public String someSession(@SessionAttribute(value = "seed", required = false) Integer seed, Model model) { logger.info("seed:{}", seed); if (seed == null) { seed = (int) (Math.random() * 10000); } else { seed += 1; } model.addAttribute("seed", seed); return seed + ""; }
The above example is the same as Cookie's ability to implement access counters!
If you want to get all the sessions, you can use HttpSession
@GetMapping("/all") public ResponseEntity<Map<String, Object>> allSessions(HttpSession session) { Map<String, Object> valueMap = new HashMap<String, Object>(); Enumeration<String> iSession = session.getAttributeNames(); while (iSession.hasMoreElements()) { String sessionName = iSession.nextElement(); Object sessionValue = session.getAttribute(sessionName); valueMap.put(sessionName, sessionValue); logger.info("sessoin[{}]={}", sessionName, sessionValue); } // Write session session.setAttribute("timestmap", new Date()); return new ResponseEntity<Map<String, Object>>(valueMap, HttpStatus.OK); }
Clear Session
@GetMapping("/clear") public ResponseEntity<Map<String, Object>> clearSessions(HttpSession session) { Map<String, Object> valueMap = new HashMap<String, Object>(); Enumeration<String> iSession = session.getAttributeNames(); while (iSession.hasMoreElements()) { String sessionName = iSession.nextElement(); Object sessionValue = session.getAttribute(sessionName); valueMap.put(sessionName, sessionValue); logger.info("sessoin[{}]={}", sessionName, sessionValue); session.removeAttribute(sessionName); } return new ResponseEntity<Map<String, Object>>(valueMap, HttpStatus.OK); }
5. Flash parameter transfer
Flash means a flash, passing by, so it's understandable that it's a type of parameter that only consumes once, some of which are like burning after reading.
Imagine a scenario where you confirm your shopping cart, enter the order management interface after your order payment is completed, and the interface prompts you to "Order successfully, please wait for shipment".
This can be achieved by Flash parameterization.
Flash is meant to be used as an instantaneous parameter transfer between requests and is no longer used after only one consumption.
Here is an example:
/** * Perform jumps and set pass values * * @param counter * @param response * @return */ @GetMapping("/first") public String first(final RedirectAttributes redirectAttrs) { logger.info("redirect start:{}"); redirectAttrs.addFlashAttribute("flash", UUID.randomUUID().toString()); return "redirect:/flash/second"; } /** * Get the passed value * * @param session * @param response * @return */ @GetMapping("/second") @ResponseBody public String second(@ModelAttribute("flash") String flash) { logger.info("redirect receive {}", flash); return flash; }
Interaction principle
The Flash mechanism in Sprintboot is also implemented by Session, where the FlashMapManager interface implements the management of Flash parameters.
The default implementation is SessionFlashMapManager, which can obtain FlashMapManager objects in the context through RequestContextUtils.
RequestContextUtils accesses objects through Request Scope
This is also a scope field that is not mentioned in this article, and the Request context is implemented using thread variables and is typically used for data interaction with intra-thread business processes.
Code Cloud Synchronization Code
Summary
HTTP header information is an additional content used to implement various features of the HTTP protocol, and common header information definitions are introduced at the beginning.
This paper mainly introduces several common access methods of HTTP scope information, including how to read and modify header s and cookie s.
springboot has a built-in Servlet container and uses JSESSIONID as the session processing mechanism. Code examples are provided to illustrate how sessions are handled.
The Flash parameter is a read-and-burn data, and its underlying implementation uses session's implementation as well.
Welcome to continue following the "Codemaker's tutorial series - springboot" and look forward to more exciting content ^-^
Author: zale