使用servlet完成简单的登录功能(servlet与html之间跳转(重定向))
程序员文章站
2022-05-31 10:45:30
...
1.新建web项目
直接在web下面创建html文件
2.login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<h2>用户登录</h2>
<form action="login" method="post">
<table>
<tr>
<td>
用户名:
</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>
密码:
</td>
<td>
<input type="password" name="pwd">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登录">
</td>
</tr>
</table>
</form>
</body>
</html>
3.LoginServlet
package servlet;
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;
/**
* zt
* 2020/8/29
* 15:14
*/
@WebServlet(value = "/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1处理乱码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//2接收数据
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
System.out.println(username+" "+pwd);
//4直接判断
if(username.equals("admin")&&pwd.equals("888")){
//重定向到BooKList
response.sendRedirect(" BookServlet");
}else{
//重定向
response.sendRedirect("login.html");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
4.运行结果
像我这样登陆成功跳转到BookServlet页面(response.sendRedirect(" BookServlet");),
失败跳转回原界面( response.sendRedirect(“login.html”);)