<%-- Created by IntelliJ IDEA. User: xrilang Date: 30/12/2021 Time: 17:31 --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="${pageContext.request.contextPath}/login" name="myform" id="myform" method="post" enctype="application/x-www-form-urlencoded"> <label for="username">用户名</label> <input name="username" id="username" type="text" placeholder="用户名"> <label for="password">密码</label> <input name="password" id="password" type="password"> <input type="submit" name="btn" value="登录"> </form> </body> </html>
点击查看代码 | Servlet
import jakarta.servlet.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "login", value = "/login") public class login extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("username"); String pwd = request.getParameter("password"); // System.out.println(name+" | "+pwd); if(name.equals("")){ response.getWriter().write("<h1>请输入账号</h1><br/><a href='index.jsp'>返回</a>"); }else if(pwd.equals("")){ response.getWriter().write("<h1>请输入密码</h1><br/><a href='index.jsp'>返回</a>"); }else if(name.equals("mllt9920")){ if(pwd.equals("123456")){ response.getWriter().write("<h1>登录成功</h1><br/>欢迎您,"+name+"<br/><a href='index.jsp'>返回</a>"); }else{ response.getWriter().write("<h1>密码错误</h1><br/><a href='index.jsp'>返回</a>"); } }else{ response.getWriter().write("<h1>账号错误</h1><br/><a href='index.jsp'>返回</a>"); } } }
点击查看代码 | pom.xml的
<dependencies> <!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api --> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>5.0.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/jakarta.servlet.jsp/jakarta.servlet.jsp-api --> <dependency> <groupId>jakarta.servlet.jsp</groupId> <artifactId>jakarta.servlet.jsp-api</artifactId> <version>3.0.0</version> <scope>provided</scope> </dependency> </dependencies>
Tomcat 10