Session management and generation verification code of BBS forum project (including detailed code comments)

Posted by kevinkorb on Mon, 07 Mar 2022 20:50:59 +0100

session management

Basic properties of HTTP

The official website of HTTP is:
It can be used as a reference manual.

Http is stateless and conversational

HTTP is stateless: there is no link between two consecutive requests on the same connection. This has immediate and problematic prospects for users trying to interact consistently with certain pages, for example, using an e-commerce shopping basket. However, although the core of HTTP itself is stateless, HTTP cookies allow stateful sessions to be used. Using header extensibility, HTTP cookies are added to the workflow, allowing sessions to be created on each HTTP request to share the same context or the same state.
Note: every request from the browser is irrelevant.
However, when processing business, it is often necessary to make contact between multiple businesses. At this time, cookies and session are needed


Cookie is not the original meaning of "cookie", but a simple text file saved in the client, which is associated with a specific Web document,
Save the information when the client accesses the Web document. When the client accesses the Web document again
This information is available to the document when the document is. Because "Cookie" has a magical feature that can be saved on the client, it can help us realize the function of recording users' personal information,
All these do not need to use complex CGI and other programs [2]. For example, a Web site may generate a unique ID for each visitor, and then
Cookie files are saved on each user's machine. If you use a browser to access the Web, you will see all the files saved on your hard disk
Cookie. In this folder, each file is a text file composed of "name / value" pairs, and another file holds all the corresponding Web files
Information about the site. Each Cookie file here is a simple and ordinary text file. Through the file name, you can see which Web
The site places cookies on the machine (of course, the site information is also saved in the file) [2].

The above comes from Baidu Encyclopedia:
In our own words, a Cookie is a small piece of data sent by the server to the user's browser and saved locally. It will be carried and sent to the server the next time the browser sends a request to the same server.

Function: tell the server whether the two requests come from the same browser.

How cokkie works: first of all, it must be clear that storing cookies is a function provided by the browser. Cookies are actually plain text stored in the browser. There will be a cookie folder under the installation directory of the browser to store cookies set under each domain.

When a web page wants to send an http request, the browser will first check whether there is a corresponding cookie, and if so, it will be automatically added to the cookie field in the request header. These are done by the browser automatically, and the browser will do them for us every http request. This feature is important because it relates to "what kind of data is suitable to be stored in cookies".

The data stored in the cookie will be automatically placed in the http request by the browser every time. If these data are not the data that needs to be sent to the server for each request, the automatic processing of the browser setting will undoubtedly increase the network overhead; However, if these data are the data that needs to be sent to the server for each request (such as identity authentication information), the automatic processing of the browser setting greatly eliminates the repeated addition operation. Therefore, the setting of "information to be carried in every request (the most typical is identity authentication information)" is particularly suitable for putting in cookies, and other types of data are not suitable.

But before the advent of localStorage, cookies were abused as a storage tool. Any data is put in the cookie, even if it is only used in the page and does not need to be transmitted to the server with the request. Of course, the cookie standard still makes some restrictions: the maximum size of cookies under each domain name is 4KB, and the maximum number of cookies under each domain name is 20 (but many browser manufacturers support more than 20 in specific implementation).
Original link:

    @RequestMapping(path = "/cookie/set",method = RequestMethod.GET)
    @ResponseBody//Return to a page
    public String setCookie(HttpServletResponse response){
        Cookie cookie =new Cookie("code", UUID.randomUUID().toString());//Randomly generate a UUID
        //The setting effective range is valid only under this path and sub path
        //Survival practice of setting cookie s
        cookie.setMaxAge(60*10);//Items that must be set

        return "set cookie";

    @RequestMapping(path = "/cookie/get",method = RequestMethod.GET)
    @ResponseBody//Return to a page
    public String getCookie(@CookieValue("code") String code){

        return "get cookie";


The cookie is stored in the request header and brought back in the request after the server responds.



Is the standard of Java EE, which is used to record the information of the client on the server

Data stored on the server is safer, but it will also increase the memory pressure on the server

Nginx is load balancing.
When talking about the lucky draw of last year's Spring Festival Gala, the leader mentioned the need to ensure that 2000 requests can be distributed evenly to seven servers and stress testing should be carried out.
The key here is:
The storage of session data means that the same ip is allocated to the same server
Synchronizing sessions is to synchronize sessions to all other servers, which has an impact on server performance
Then it is stored in the database redis, which reflects the advantages of redis.
Sessions are rarely used now, as shown in the following figure

Now the data is generally stored in the NoSql database redis, and there will be blog updates about redis later.
Session usage is similar to cookie s:

@RequestMapping(path = "/session/set",method = RequestMethod.GET)
    @ResponseBody//Return to a page
    //The session object is automatically injected into spring. You only need to create it
    public String setSession(HttpSession   session){
        session.setAttribute("id", 1);
        session.setAttribute("name", "Test");

        return "set session";


    @RequestMapping(path = "/session/get",method = RequestMethod.GET)
    @ResponseBody//Return to a page
    //The session object is automatically injected into spring. You only need to create it
    public String getSession(HttpSession   session){

        return "get session";


Generate verification code


Attach the official document of kaptcha:
It is a tool specially used to generate verification code on github

Configuration of kaptcha

Use the following configuration to change the corresponding information of the verification code. For example:

  • Font verification code
  • Font size of verification code
  • Font color of verification code font
  • Range of verification code content (numbers, letters, Chinese characters!)
  • Verification Code: picture size, border, border thickness, border color
  • Interference line of verification code
  • Style of verification code (fisheye style, 3D, normal blur,...)

Generation of verification code

Here we first introduce dependencies as follows:


Because kaptcha needs to set the configuration information, we create KaptchaConfig to configure the relevant properties of the verification code.
The core interface is producer producer
The object used is DefaultKaptcha DefaultKaptcha DefaultKaptcha
Configuration information is configured in the configuration file. There are many ways to configure it. Here, you can directly configure new Properties.

public class KaptchaConfig {
    //The core interface is producer
    public Producer kaptchaProducer(){
        Properties properties =new Properties();
        properties.setProperty("kaptcha.image.width", "100");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "32");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");//RGB color
        properties.setProperty("kaptcha.textproducer.char.string", "1234567890ABCDEFGHIGKLMNOPQRSTUVWXYZ");//A collection of text from which characters are taken
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Config config=new Config(properties);
        return kaptcha;

Note: the config here is different from the config of thymeleaf. It is used here
import is the config under kactcha.

The integration of verification code and springboot is based on login and registration function. Please follow up.

To yourself: hard work may be the most despised place by others, but it is also an effective measure to improve yourself!!!

Topics: Java