先在Servlet中创建一个LoginServlet 用来处理登录
然后用index.jsp用来提交表单
最后一个succ1.jsp作为登录成功的页面
首先是LoginServlet
package fun.afcraft; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取提交的账号和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); // 获取session HttpSession session = request.getSession(); // 提前设置一个username的session session.setAttribute("username", ""); // 因为没有连接数据库 所以将就用if判定代替一下 if (username.equals("zai02") && password.equals("123456")) { // 登录成功 发送session到attribute session.setAttribute("username", username); // 重定向到登录成功的页面 response.sendRedirect("succ1.jsp"); } else { // 如果账号或密码错误 // 这里用account 只是为了记住账号 session.setAttribute("account", username);//这里是保存已经输入的username 相当于记住账号 // 发送session 显示登录失败 String state = "Please enter the correct account and password"; session.setAttribute("state", state); // 重定向到登录页面 response.sendRedirect("index.jsp"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
index.jsp
<%-- Created by IntelliJ IDEA. User: 盲解 Date: 2021/10/27 Time: 20:33 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <%--表单--%> <form action="login" method="post"> <% // 提前定义一个usm 也就是username 不然如果没有值 会在输入框显示null String usm = ""; // 判断刚才的账号输入框有没有值 if ((String) session.getAttribute("account") != null) { // 如果有 就给usm赋值 usm = (String) session.getAttribute("account"); } %> username:<input type="text" name="username" value=<%=usm%>><br> password:<input type="password" name="password"><br> <input type="submit" value="login"> </form> <%--这里用来显示登录失败的提示语--%> <% String str = (String) session.getAttribute("state"); // 同样的 判断state里有没有值 如果没有会显示null if (str == null) { str = ""; } %> <%--输出提示语--%> <%=str%> </body> </html>
succ1.jsp
<%-- Created by IntelliJ IDEA. User: 盲解 Date: 2021/10/27 Time: 20:42 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% // 获取登录的账号 String username = (String) session.getAttribute("username");//如果LoginServlet中没有提前设置username 这里就会空指针报错 if (username.equals("")){ response.sendRedirect("index.jsp"); return; } %> <h1>Login Success</h1> <%--欢迎语--%> <h3>Welcome: </h3><%=username%> </body> </html>