SpringWeb

Java servlets are programs that run on a Web server or application server as an intermediate layer between requests from a Web browser or other HTTP client and a database or application on an HTTP server.

The HTTP protocol

Hyper Text Transfer Protocol

Features:

  • HTTP is connectionless: connectionless means to limit processing to one request per connection. The server disconnects from the customer after processing the request and receiving the reply from the customer. In this way, transmission time can be saved.
  • HTTP is media independent: this means that any type of data can be sent over HTTP as long as clients and servers know what to do with the data content.
  • HTTP is stateless: stateless means that the protocol has no memory for transaction processing. The lack of state means that if the previous information is needed for subsequent processing, it must be retransmitted, which can result in an increase in the amount of data transferred per connection. On the other hand, the server responds faster when it doesn’t need the previous information.

The HTTP request:

Request line/header/Request body (request body)

  • Get has no request body because it is already displayed in the address bar;
  • Post has a request body that passes the request data to the server

The HTTP response:

Status line/message header/response body (something seen in the browser)

The following are common HTTP status codes:

  • 200 – Request successful
  • 301 – Resources (web pages, etc.) are permanently transferred to another URL
  • 404 – Requested resource (web page, etc.) does not exist
  • 500 – Internal server error
The serial number methods describe
1 GET Requests the specified page information and returns the entity body.
2 HEAD Similar to a GET request, except that there is no concrete content in the response returned, which is used to retrieve the header
3 POST Submit data to a specified resource for processing requests (such as submitting a form or uploading a file). The data is contained in the request body. POST requests may result in the creation of new resources and/or the modification of existing resources.
classification Classification description
1 * * Message, the server receives the request and requires the requester to proceed with the operation
2 * * Success, the operation is received and processed successfully
3 * * Redirect, requiring further action to complete the request
4 * * Client error, request contains syntax error or request cannot be completed
5 * * Server error. The server encountered an error while processing the request
The message header

Request header:

  • Regerer: The request header specifies the source of the request

    Usually used for Baidu bid advertising (drainage)/invite friends (invite links)

Header:

  • Location: redirects

  • Refresh: Indicates automatic redirection

    (1. Refresh the page every few seconds / 2. Jump to a new page after a few seconds)

Tomcat

Tomcat server is an open source lightweight Web application server. It is widely used in small and medium-sized systems and small concurrency situations. It is the first choice for developing and debugging Servlet and JSP programs.

Servlet

Servlet life cycle:

Init to create:

The service invocation:

Destory destruction:

Get the request parameters:

Request garble problem:

Get: No garbled characters

Post: Chinese will be garbled (because the default encoding does not support Chinese)

Solution: request. SetCharacterEncoding (utf-8)

Request forwarding:

request.getRequestDispatcher(url).forward(request,response)

  • == Server behavior ==
  • The address bar does not change
  • One request from beginning to end
  • Data can be shared
Response data:

GetWriter () : character output stream (output string)

GetOutputStream () : byte output stream (output any data)

Response to garble problem:

GetWriter () : Chinese will be garbled (because the default encoding does not support Chinese)

GetOutputStream () : Chinese is garbled (because the default encoding does not support Chinese)

Solutions:

  1. Set the encoding format of the server first:

response.setCharacterEncoding(UTF-8)

  1. Then set the encoding format of the client:

response.setHeader(“context-type”,”text/html; charset=UTF-8″)

  • Set the encoding format of both client and server:

    response.setContentType("text/html; charset=UTF-8")

redirect

response.sendRedirect()

  • == The client behavior ==
  • Two requests
  • The address bar will change
  • Data Not shared

The client sends the first request, and the server responds to the request and returns a new address to the client. When the client receives the response, it immediately issues a second request, the server processes the response, and the redirect is complete.

The difference between request forwarding and redirection
Forward requests redirect
Server behavior Client behavior
Address bar unchanged Address bar change
One request, data sharing Two requests, data not shared
The forwarding address can only be the resource under the current project It can be any address, it can cross domains
Cookie object
/ / negative integer
Cookie cookie1 = new Cookie("username"."leehom1");
cookie1.setMaxAge(-1);// The browser is invalid when closed
response.addCookie(cookie1);
/ / positive integer
Cookie cookie2 = new Cookie("username"."leehom2");
cookie2.setMaxAge(30);// Survive 30 seconds
response.addCookie(cookie2);
/ / zero
Cookie cookie3 = new Cookie("username"."leehom3");
cookie3.setMaxAge(0);/ / delete the cookie
response.addCookie(cookie3);

// Function: 7 days free login/remember account password
Copy the code
Cookie Set expiration time
  • Negative integer

    If the value is negative, the cookie is not stored.

    The default value of the cookie’s maxAge attribute is “-1”, which means that the cookie only lives in the browser memory and disappears once the browser window is closed.

  • Positive integer

    If it is an integer greater than 0, it represents the number of seconds stored.

    When the life is greater than 0, the browser saves the Cookie to the hard disk and the Cookie will survive for the corresponding time even if the browser is closed or the client computer is restarted.

  • zero

    If the value is 0, the Cookie is deleted.

    If the browser has already saved the Cookie, the Cookie setMaxAge(0) can be used to delete the Cookie, either in the browser’s memory or on the client’s hard drive.

Note the Cookie
  1. Cookies can’t change computers, can’t change browsers;
  2. Cookie cannot store Chinese;
  3. Duplicate cookies overwrite the original Cookie;
  4. Browsers store a limited number of cookies and a limited size (about 4KB).
The path of the Cookie

The setPath of cookies sets the path of cookies that determines whether the server’s request will load some cookies from the browser.

  1. Cookie objects can be obtained by any project under the current server
// The current project path is s01
Cookie cookie = new Cookie ("name"."leehom");
// Set the path to "/", indicating that any project under the current server can obtain Cookie objects
cookie.setPath("/");
response.addCookie(cookie);
Copy the code
  1. Resources under the current project can get Cookie objects (Cookie path is not set by default)
// The current project path is s01
Cookie cookie = new Cookie ("name"."leehom");
// Set the path to /s01, indicating that only resources under the current project can obtain Cookie objects
cookie.setPath("/s01");// By default, the value of path can not be set
response.addCookie(cookie);
Copy the code
  1. Specifies that resources under the project can get Cookie objects
// The current project path is s01
Cookie cookie = new Cookie ("name"."leehom");
// Set the path to /s02, indicating that only resources under the current project can obtain Cookie objects
cookie.setPath("/s02");
response.addCookie(cookie);
Copy the code
  1. Resources in a specified directory can get Cookie objects
// The current project path is s01
Cookie cookie = new Cookie ("name"."leehom");
// Set the path to /s01/cook, which indicates that cookies can be obtained only in the s01/cook directory
cookie.setPath("/s01/cook");
response.addCookie(cookie);
Copy the code
The HttpSession object

HttpSession session = request.getSession()

Get if it exists, create if it does not

The Session domain object
// Get the session object
HttpSession session = request.getSession();

// Set the session domain object
session.setAttribute("uname"."admin");
// Get the session domain object with the specified nameString uname = (String) request.getSession().getAttribute ("uname");// Set the Request domain object
request.setAttribute("uname"."leehom");
// Get the request domain object with the specified nameString uname = (String) request.getAttribute ("leehom");// Removes the session domain object with the specified name
session.removeAttribute("uname");
Copy the code
The lifetime of the Session

⌛️ : The Tomcat session lasts for 30 minutes by default (when no operation is performed). Once the operation is performed, the session is timed again.

  1. Default maturity

You can modify it in the web. CML file in the Tomcat conf directory (not recommended).

<! -- The default maximum inactivity time of a session. Unit: min -->
<session-config>
	<session-timeout>30</session-timeout>
</session-config>
Copy the code
  1. Manually set the expiration time
// Set the expiration time manually
session.setMaxInactiveInterval(15)/ / is due for 15 seconds
// Check the expiration date
getMaxInactiveInterval()
Copy the code
  1. Immediate destruction (commonly used)
session.invalidate();
Copy the code
  1. Closing the browser is invalid

    The underlying session relies on cookies. If the browser is closed, the session becomes invalid.

  2. Shut down the server

    The session is destroyed when the server is shut down.

ServletContext object

Get the servletContext object

//1. Obtain the file from the Request object
ServletContext servletContext = request.getServletContext();

//2. Obtain it from the session object
ServletContext servletContext = request.getSession().getServletContext();

//3. Obtain the file from the ServletConfig object
ServletContext servletContext = getServletConfig().getServletContext();

//4
ServletContext servletContext = getServletContext();
Copy the code

Commonly used method

// Obtain the version information of the current server
String serverInfo = request.getServletContext().getServerInfo();

// Get the real path of the project
String realPath = request.getServletContext().getRealPath("/");
Copy the code
ServletContext domain object
// Get the ServletContext object
ServletContext servletContext = request.getServletContext();
// Set the domain object
servletContext.setAttribute("name"."leehom");
// Get the domain object
String name = (String) servletContext.getAttribute("name");
// Remove the domain object
servletContext.removeAttribute("name");
Copy the code
Servlet three domain objects
  1. Request a domain object

    Valid on a single request. Request forwarding is valid, rescheduling is invalid.

  2. The session domain object

    This parameter is valid in one session. Request forwarding and redirection are valid, but expire after session destruction.

  3. ServletContext domain object

    Valid throughout the application. The server becomes invalid after being shut down.

File upload and download

The front desk page

<! Prepare the form. 2. Set the form submission method to POST request method=" POST "3. Set the form type to file upload form encType ="multipart/form-data" 4. Prepare file submission address 5. Prepare form elements * Common form item type="text" * file item type="file" 6. Set the name attribute value of the form element (otherwise the background cannot accept the data) -->
<form action="uploadServlet" method="post" enctype="multipart/form-data">Name:<input type="text" name="uname"> <br>File:<input type="file" name="myfile"> <br>
    <! --button defaults to submit type="submit"-->
    <button>submit</button>
</form>
Copy the code

The background implementation

Use @multipartConfig to identify a Servlet as supporting file uploads. The Servlet encapsulates the MUliPart /form-data POST request into a Part, and uses the Part to operate the uploaded file.

@MultipartConfig // If it is a file upload, this annotation must be set;
@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("File upload");
        // Set the encoding format of the request
        req.setCharacterEncoding("UTF-8");
        // Get the normal form entry
        String uname = req.getParameter("uname");// The corresponding name value in the form
        System.out.println("uname:" + uname);
        // Get the Part object
        Part part = req.getPart("myfile"); // The name attribute value of the file field in the form
        // Use Part to get the file name for the upload
        String fileName = part.getSubmittedFileName();
        System.out.println("Upload filename:" + fileName);
        // Get the file path
        String filePath = req.getServletContext().getRealpath("/");
        System.out.println("File path:" + filePath);
        // Upload the file to the specified directory
        part.write(filePath + "/"+ fileName); }}Copy the code
File download

Hyperlink download

The default download

<! -- When the hyperlink encounters a resource that the browser does not know, it will automatically download -->
<a href="test.zip">Hyperlink download</a>
Copy the code

Specify the Download attribute to download (default file name will be used if download is not set)

<! If the hyperlink encounters a browser-recognized resource, it can be downloaded with the Download attribute -->
<a href="test.txt" download="test02.txt">Hyperlink download</a>
Copy the code

Background implementation download

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("File download...");

        // Set the encoding format of the request
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        // Get parameters (get the file name to download)
        String fileName = req.getParameter("fileName");
        Trim () : Removes whitespace before and after the string
        if(fileName ! =null || "".equals(fileName.trim())) {
            resp.getWriter().write("Please enter the file name to download!");
            resp.getWriter().close();
            return;
        }
        // Get the path to the image
        String path = req.getServletContext().getRealPath("/download/");
        // Get the file object from the path
        File file = new File(path + fileName);
        // Check whether the file object exists and is a standard file
        if (file.exists() && file.isFile()){
            // Set the response type that the browser cannot activate
            resp.setContentType("application/x-msdownload");
            // Set the response header
            resp.setHeader("Content-Disposition"."attachment; filename=" + fileName);
            // Get the input stream of file
            InputStream in = new FileInputStream(file);
            // Get the output stream of bytes
            ServletOutputStream out = resp.getOutputStream();
            // Define a byte array
            byte[] bytes = new byte[1024];
            // Define the length
            int len = 0;
            // Loop output
            while((len = in.read(bytes))! = -1) {/ / output
                out.write(bytes,0,len);
            }
            / / close your flow
            out.close();
            in.close();
        }else {
            resp.getWriter().write("File not found, please try again!"); resp.getWriter().close(); }}}Copy the code

JSP and JSTL

JSP :(Java Server Page), is the dynamic web programming technology provided by Sun company, is the dynamic resource of Java web Server.

  • Whereas HTML can only provide static data, JSP can nest Java code in a page to provide dynamic data to the user.
  • Servlets are hard to type data, whereas JSPS are easy to type.

Servlets are now commonly used as controller components in Web applications, while JSP technology is used as a data display template.

JSP comment
  • Explicit comments (the client can see, inheriting HTML-style comments)

    <! -- HTML comment -->

  • Implicit comments (invisible to clients)

    • JSP’s own annotations<%-- JSP's own comments -->
    • Inherit Java-style annotations// Single-line comment/* Multi-line comments */

Java code in JSPS is not recommended (coupling can be very high)

Scriptlet
  1. The first:The < % % >: A Java script segment that defines local variables and writes statements
  2. The second:The < %! % >: declaration that defines global (member) variables, methods, and classes
  3. The third:< % = % >: expression that outputs a variable or specific content
JSP instruction tag
  • Static includes

    Format:

    <%@include file=" page path to include "%>

    Features:

    1. The content is replaced directly

    2. Static inclusion generates only one source file

    3. Variables with the same name cannot appear

    4. Running efficiency is a little bit higher, but the coupling degree is higher, not flexible enough

  • Dynamic includes

    Format:

    < JSP :include page=” page path to include “>

    Features:

    1. Dynamic includes are equivalent to method calls
    2. Dynamic inclusion generates multiple source files
    3. You can define variables with the same name
    4. High efficiency, low coupling degree

    ⚠️ Note: When dynamic include does not require passing parameters, do not include any content between the double tags, including Spaces and line breaks, otherwise an error will be reported.

    Using dynamic include pass parameters:

    <jsp:include page="Page path to include">
        <jsp:param name="Parameter name" value="Parameter value"/>
    </jsp:include>
    Copy the code

    ⚠️ Note: The name attribute does not support expressions, and the value attribute does.

JSP’s four domain objects
  1. PageContext (valid for current page, invalid after jump)

    pageContext.setAttribute("name1","zhangsan");

  2. Request (Common) (Valid in a single request. The server redirect is valid but the client redirect is invalid.)

    request.setAttribute("name2","lisi");

  3. Session (valid for a single session, both server and client jumps)

    session.setAttribute("name3","wanger");

  4. Application (valid throughout the application)

    application.setAttribute("name4","mazi");

JSP jump mode:

  • Server redirect:

    < JSP :forward page=" jump to the address "></ JSP :forward>

  • Client redirect:

    <a href="跳转的地址">跳转</a>

EL expression

${domain object name}

EL expressions typically operate on data in domain objects, not local variables.

⚠ ️ note:

1. If the value of the field object obtained by the EL expression is empty, an empty string is displayed by default.

2. By default, the EL expression is found from the smallest to the largest, so that no empty string is found.

Gets the domain object of the specified range

  • Page range:${pageScope.uname}
  • Scope of the request:${requestScope.uname}
  • Scope of the session:${sessionScope.uname}
  • Scope of application:${applicationScope.uname}
JSTL

Java Server Pages Standard Tag Library (JSTL)

JSP standard tag library for solving common problems such as iterating over a map or collection, conditional testing, XML processing, and even database and database access operations.

User login exercises

  1. User table tb_user of the database

  2. Front end:

  • Login page login.jsp

    User login js verification

    Login form validation

    1. Bind the click event to the login button (via id selector binding)

    2. Gets the values of the user name and password

    3. Check if the name is empty

      If the name is empty, prompt the user (span tag assignment), and return;

    4. Check whether the password is empty

      If the password is empty, prompt the user (span tag assignment) and return;

    5. If none is empty, submit the form manually

  • Home page

  1. The backend:
  • The login function

    Ideas:

    1. Receiving requests from clients (receiving parameters: username, password)

    2. Nonnull judgment of parameters

      If the parameter is null:

      Return results (set status, set prompts, echo data) via message model objects

      Set the message model object to the Request scope

      The request forwarding redirects to the login page

      The return;

    3. Query user objects by user name

    4. Determines whether the user object is empty

      If empty:

      Return results (set status, set prompts, echo data) via message model objects

      Set the message model object to the Request scope

      The request forwarding redirects to the login page

      The return;

    5. Compare the user password queried in the database with the password passed by the foreground

      If not equal:

      Return results (set status, set prompts, echo data) via message model objects

      Set the message model object to the Request scope

      The request forwarding redirects to the login page

      If yes, the login succeeds:

      Sets the user information to the session scope

      Redirect to home page

Controlelr layer :(receives requests, responds to results)

  1. Receiving requests from clients (receiving parameters: username, password)

  2. Call a method on the Service layer to return a message model object

  3. Determine the status code of the message model

    If status code = failed

    By setting the message model object into the Request scope, request forwarding jumps to login.jsp

    If status code = success

    Set the user information in the message model to the session scope and redirect to index.jsp

Service layer :(business logic)

  1. Nonnull judgment of parameters

    If the parameter is null

    Returns the message model object by setting the status code, prompt, and echo data to the message model object

  2. Call the DAO layer’s query method to query user objects by user name

  3. Determines whether the user object is empty

    If empty:

    Returns the message model object by setting the status code, prompt, and echo data to the message model object

  4. Compare the user password queried in the database with the password passed from the front desk

    If not equal:

    Returns the message model object by setting the status code, prompt, and echo data to the message model object

  5. Login successful, success status, prompt, user object Set message model object, and return.

Mapper layer (Dao layer)

Define the corresponding interface.

Layered thinking (decoupling: high cohesion, low coupling)

The controller layer:

Receiving a request

(Call the service layer and return the result)

Returns the result

Service layer:

Process business logic judgments

Mapper layer:

Interface class

Mapper. XML mybatis and database related operations

Entity Layer (POJO, Model)

JavaBean entity class

Util:

Utility classes (generic methods/classes)

The test:

Test classes/methods

Project file directory screenshot:

Front page:

login.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java"%> < HTML > <head> <title> </head> <body> <div style="text-align: center">
    <form action="login" method="post" id="loginForm"> User name: <input type="text" name="uname" id="uname" value="${messageModel.object.userName}"> <br> Password: <input type="password" name="upwd" id="upwd" value="${messageModel.object.userPwd}"> <br>
        <span id="msg" style="font-size: 12px; color: red">${messageModel.msg}</span> <br>
        <button type="button" id="loginBtn"</button> <button type="button"> register < / button > < / form > < / div > < / body > < % - the introduction of Jquery js file - % > < script SRC ="https://code.jquery.com/jquery-3.6.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
   /* * login page login.jsp user login js verification login form verification 1. Bind the click event to the login button (via id selector binding) 2. Get the username and password values 3. If the name is empty, prompt the user (span tag assignment), and return; 4. Check whether the password is empty. If the password is empty, prompt the user (value assigned by span tag) and return. 5. If none is empty, manually submit the form */

    $("#loginBtn").click(function (){
        // Get the user name and password
        var uname = $("#uname").val();
        var upwd = $("#upwd").val();
        // Check whether the user name is empty
        if (isEmpty(uname)){
            // Check whether the name is empty
            // If the name is empty, prompt the user (span tag assignment), and return;
            $("#msg").html("User name cannot be empty!");
            return ;
        }
        // Check whether the password is empty
        if (isEmpty(upwd)){
            // Check whether the password is empty
            // If the password is empty, prompt the user (span tag assignment) and return;
            $("#msg").html("Passwords cannot be empty!");
            return ;
        }
        // If none is empty, submit the form manually
        $("#loginForm").submit();

    });

    // Determine if the string is empty.
    // Return true if null,
    // If not empty, return false;
    function isEmpty(str){
        if (str == null || str.trim() === "") {return true;
        }
            return false;
    }
</script>
</html>

Copy the code
Back-end implementation:

UserServlet

@WebServlet("/login")
public class UserServlet extends HttpServlet {
    // instantiate the UserService object
    private UserService userService = new UserService();

    /** * user login * controlelr layer :(receive request, response result) * 1. Receive the client request (receive parameters: username, password) * 2. Call the method of the service layer and return the message model object * 3. Determine the status code of the message model * If the status code = failure * Sets the message model object to the Request scope, and the request forward jumps to login.jsp * If the status code = success * sets the user information in the message model to the session scope, Redirect to index.jsp * *@param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Receive requests from clients (user name and password)
        String uname = req.getParameter("uname");
        String upwd = req.getParameter("upwd");
        //2. Call the service layer method and return the message model object
        MessageModel messageModel = userService.userLogin(uname,upwd);
        //3. Determine the status code of the message model
        if (messageModel.getCode() == 1) {// Set the user information in the message model to the session scope, redirecting to index.jsp
            req.getSession().setAttribute("user",messageModel.getObject());
            resp.sendRedirect("index.jsp");
        }else {
            // Set the message model object to the Request scope to redirect the request forward to login.jsp
            req.setAttribute("messageModel",messageModel);
            req.getRequestDispatcher("login.jsp").forward(req,resp); }}}Copy the code

MessageModel

/** * Message model Object (data response) * status code: * 1: success, 0: failure * Prompt message: * string * Output data: * Object Object */
public class MessageModel {
    private Integer code = 1;// status code :(1= successful, 0= failed)
    private String msg = "Success";// Prompt message
    private Object object;// Echo objects (basic data types, string types, List, Map, etc.)

    public Integer getCode(a) {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg(a) {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getObject(a) {
        return object;
    }

    public void setObject(Object object) {
        this.object = object; }}Copy the code

User

public class User {
    private Integer userId;
    private String userName;
    private String userPwd;

    public Integer getUserId(a) {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName(a) {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd(a) {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd; }}Copy the code

UserMapper

public interface UserMapper {
    public User queryUserByName(String userName);
}

Copy the code

UserMapper.xml


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<! First parse namespace: namespace, which is usually used to map Dao (Mapper) layer interfaces.
<mapper namespace="com.nanfu.mapper.UserMapper">
    <! -- id: indicates the Dao (Mapper) layer interface method name. ParameterType: specifies the input parameterType -->
    <! -- useGeneratedKeys="true" -- useGeneratedKeys="true"
    <select id="queryUserByName" parameterType="string" resultType="com.nanfu.entity.User">
        select * from tb_user where userName = #{userName}
    </select>
</mapper>
Copy the code

UserService

/** * Business logic * user login */
public class UserService {
    /** * service layer :(business logic) * 1. Non-null judgment of parameters * if parameters are null * set status code, prompt, echo data to message model object, return message model object * 2. Call the dao layer query method, query the user object * by the user name 3. Determine whether the user object is empty * If it is empty, set the status code, prompt information, and output data to the message model object, and return the message model object * 4. Compare the user password queried in the database with the password passed from the foreground * if it is not equal, set the status code, prompt message, and output data to the message model object, and return the message model object * 5. Login successful, success status, prompt, user object Set message model object, and return. *@param uname
     * @param upwd
     * @return* /
    public MessageModel userLogin(String uname, String upwd) {
        MessageModel messageModel = new MessageModel();

        // Data is displayed
        User u = new User();
        u.setUserName(uname);
        u.setUserPwd(upwd);
        messageModel.setObject(u);
        //1. Non-null judgment of parameters
        if (StringUtil.isEmpty(uname) || StringUtil.isEmpty(upwd)) {
            // Set the status code, prompt information, and echo data to the message model object
            messageModel.setCode(0);
            messageModel.setMsg("Username and password cannot be empty!");
            return messageModel;
        }

        //2. Invoke the query method of the DAO layer to query user objects by user names
        SqlSession session = GetSqlSession.createSqlSession();
        UserMapper usermapper = session.getMapper(UserMapper.class);
        User user = usermapper.queryUserByName(uname);

        //3. Check whether the user object is empty
        if (user == null) {
            // Set the status code, prompt information, and echo data to the message model object
            messageModel.setCode(0);
            messageModel.setMsg("The user does not exist!");
            return messageModel;
        }

        //4. Compare the user password queried in the database with the password transmitted from the foreground
        if(! upwd.equals(user.getUserPwd())){// If not, set the status code, prompt information, and echo data to the message model object, return the message model object
            messageModel.setCode(0);
            messageModel.setMsg("User password is incorrect!");
            return messageModel;
        }

        //5. Login succeeds, success status, prompt message, user object Set message model object, and return.
        messageModel.setObject(user);
        returnmessageModel; }}Copy the code

Test

public class Test {
    public static void main(String[] args) {
        // Get the sqlSession object
        SqlSession session = GetSqlSession.createSqlSession();
        // Get the corresponding Mapper
        UserMapper userMapper = session.getMapper(UserMapper.class);
        // Call the method to return the user object
        User user = userMapper.queryUserByName("admin"); System.out.println(user); }}Copy the code

GetSqlSession

public class GetSqlSession {

    // Get the SqlSession object

    public static SqlSession createSqlSession(a){
        SqlSessionFactory sqlSessionFactory = null;
        InputStream input = null;
        SqlSession session =null;
        try {
            // Get mybatis environment configuration file
            String resource = "mybatis-config.xml";
            // Stream resource (mybatis environment configuration file)
            input = Resources.getResourceAsStream(resource);
            // Create a session factory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);
            // Get the SqlSession from the factory
            session = sqlSessionFactory.openSession();
            return session;
        }catch (IOException e){
            e.printStackTrace();
            return null; }}public static void main(String[] args) { System.out.println(createSqlSession()); }}Copy the code

StringUtil

/** * string utility class * Determine if the string is empty: * If it is empty, return true; * If not empty, return false; * /
public class StringUtil {
    public static boolean isEmpty(String str){
        if (str == null || "".equals(str.trim())){
            return true;
        }else {
            return false; }}}Copy the code

mybatis-config.xml


      
<! DOCTYPEconfiguration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <! Manage transaction and link pool configuration -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/java_test? useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <! --mappers mapper -->
    <mappers>
        <! -- Mode 1: Configure mapper one by one
<! -- <mapper resource="mapper/userMapper.xml"/>-->

        <! -- Mode 2: Automatically scan the mapper interface and configuration file in the package -->
        <package name="com.nanfu.mapper"></package>
    </mappers>



</configuration>
Copy the code

mysql.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/java_test? useUnicode=true& characterEncoding=utf8& useSSL=false& serverTimezone=UTC"
username=root
password=root
Copy the code