JAVA Session session Thymeleaf - view template technology configuration steps


Session session

HTTP is stateless: the server cannot distinguish whether the two requests are sent by the same client or different clients. The
real problem: the first request is to add a product to the shopping cart, and the second request is to check out ; If the two requests cannot be distinguished from the same user, it will cause confusion
Solve the stateless problem through session tracking technology

insert image description here

Sample code:

public class Demo03Servlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取session,如果获取不到,则创建一个新的
        HttpSession session = request.getSession();
        System.out.println("session ID"+session.getId());
    }
}

operation result:
insert image description here

Session Tracking Technology

1. The client sends a request to the server for the first time, and the server gets the session. If it cannot get it, it creates a new one, and then responds to the client. 2.
When the client sends a request to the server, the server can get it, then The server judges that this request is the same client as the last request, so that the client can be distinguished
Commonly used API:
request.getSession() -> Get the current session, if not, create a new session
request.getSession(true) -> The effect is the same as without parameters
request.getSession(false) -> Get the current session, if not, return null, and will not create a new
session.getId() -> Get sessionID
session.isNew() -> Determine whether the current session is It is the new
session.getMaxInactiveInterval() -> the inactive interval of the session, the default is 1800 seconds
session.invalidate() -> force the session to be invalid immediately
session.getCreationTime() -> get the session creation time
session.getLastAccessedTime() -> Get last access time

session save scope

insert image description here
The session storage scope corresponds to a specific session
Commonly used API:
session.setAttribute(k,v)
Object session.getAttribute(k)

Demo code:

//演示向HttpSession保存数据
public class Demo04Servlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.getSession().setAttribute("uname","lina");
    }
}
public class Demo05Servlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        Object unameObj = request.getSession().getAttribute("uname");
        System.out.println(unameObj);
    }
}

operation result:
insert image description here


Thymeleaf - View Template Technology

configuration process

Thymeleaf is a technology used to help us do view rendering
1) Add the jar package of thymeleaf
insert image description here
2) Add configuration in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">

    <!--配置上下文参数-->
    <context-param>
        <param-name>view-prefix</param-name>
        <param-value>/</param-value>
    </context-param>
    <context-param>
        <param-name>view-suffix</param-name>
        <param-value>.html</param-value>
    </context-param>


</web-app>
  • Configuration prefix prefix
  • Configure the suffix suffix
    3) Create a new Servlet file to add configuration
public class ViewBaseServlet extends HttpServlet {
    
    

    private TemplateEngine templateEngine;

    @Override
    public void init() throws ServletException {
    
    

        // 1.获取ServletContext对象
        ServletContext servletContext = this.getServletContext();

        // 2.创建Thymeleaf解析器对象
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
        // 3.给解析器对象设置参数
        // ①HTML是默认模式,明确设置是为了代码更容易理解
        templateResolver.setTemplateMode(TemplateMode.HTML);

        // ②设置前缀
        String viewPrefix = servletContext.getInitParameter("view-prefix");

        templateResolver.setPrefix(viewPrefix);

        // ③设置后缀
        String viewSuffix = servletContext.getInitParameter("view-suffix");

        templateResolver.setSuffix(viewSuffix);

        // ④设置缓存过期时间(毫秒)
        templateResolver.setCacheTTLMs(60000L);

        // ⑤设置是否缓存
        templateResolver.setCacheable(true);

        // ⑥设置服务器端编码方式
        templateResolver.setCharacterEncoding("utf-8");

        // 4.创建模板引擎对象
        templateEngine = new TemplateEngine();

        // 5.给模板引擎对象设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);

    }

    protected void processTemplate(String templateName, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    
    
        // 1.设置响应体内容类型和字符集
        resp.setContentType("text/html;charset=UTF-8");

        // 2.创建WebContext对象
        WebContext webContext = new WebContext(req, resp, getServletContext());

        // 3.处理模板数据
        templateEngine.process(templateName, webContext, resp.getWriter());
    }
}

4) Make our Servlet inherit ViewBaseServlet
5) Get the physical view name according to the logical view name

//此处的视图名称是index
//那么thymeleaf会将这个 逻辑视图名称 对应到物理视图 名称上去
//逻辑视图名称  index
//物理视图名称 view-prefix + 逻辑视图名称 + view-suffix
//所以真是的视图名称是 / index .html

6) Use thymeleaf's tags
th:if, th:unless, th:each

Guess you like

Origin blog.csdn.net/m0_62434717/article/details/129773739
Recommended