- login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/doLogin" method="post">
<label>账号: <input type="text" name="uid"></label>
<label>密码: <input type="text" name="pwd"></label>
<button>登陆</button>
</form>
</body>
</html>
- resutl.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
out.print(request.getAttribute("msg"));
if (request.getAttribute("res").equals("1")) {
out.print("<a href='/doLogin'>退出登录</a>");
}
%>
</body>
</html>
- LoginServlet
package com.stu.demo;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
- DoLoginServlet
package com.stu.demo;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "DoLoginServlet")
public class DoLoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
String uid = request.getParameter("uid");
String pwd = request.getParameter("pwd");
if (uid.equals("123") && pwd.equals("321")) {
request.setAttribute("msg", "登陆成功:" + uid);
request.setAttribute("res", "1");
} else {
request.setAttribute("msg", "登陆失败");
request.setAttribute("res", "0");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
网友评论