Simple version user login function

login.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User login</title>
</head>
<body>
    <form action="loginServlet" method="post">
        姓名: <input type="text" name="uname"> <br>
        密码: <input type="password" name="upwd"> <br>
        <button>登录</button>   <span style="color: red;font-size: 12px"><%=request.getAttribute("msg")%></span>
    </form>
</body>
</html>

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <h2>Welcome<%=session.getAttribute("uname")%>login</h2>
  </body>
</html>

LoginServlet.java

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Set the encoding format of the client (to prevent garbled characters)
        req.setCharacterEncoding("UTF-8");
        //Accept the parameters passed by the client
        String uname = req.getParameter("uname");
        String upwd = req.getParameter("upwd");
        //Check if the parameter is empty
        if (uname == null ||"".equals(uname.trim())) {
            //Prompt user information
            req.setAttribute("msg", "User name cannot be empty");
            //Request forwarding jump to login.jsp
            req.getRequestDispatcher("login.jsp").forward(req, resp);
            return;
        }
        if (upwd == null||"".equals(upwd.trim())) {
            //Prompt user information
            req.setAttribute("msg", "User password cannot be empty");
            //Request forwarding jump to login.jsp
            req.getRequestDispatcher("login.jsp").forward(req, resp);
            return;
        }
        // Determine if the account password is correct
        if (!"admin".equals(uname)||!"admin".equals(upwd)) {
            //Prompt user information
            req.setAttribute("msg", "Login failed");
            //Request forwarding jump to login.jsp
            req.getRequestDispatcher("login.jsp").forward(req, resp);
            return;
        }
        //login successful
        //Set the login information to the session
        req.getSession().setAttribute("uname",uname);
        //Jump to index.jsp
        resp.sendRedirect("index.jsp");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324032086&siteId=291194637