HTML + Servlet 实现用户登陆系统
分别创建 login/success/error.html文件,再通过loginServlet.java文件获取用户输入的数据
login.html
创建登陆界面
<form action="login" method="post">
<div>用户名<input type="text" name="username" /></div>
<div>密 码<input type="password" name="password" />
</div> <div>验证码<input type="text" name="verifycoide" maxlength="4"/></div>
<button>登录</button>
</form>
success.html
成功登陆的界面
<h1>尊敬的会员,欢迎你回来~</h1>
error.html
提示密码错误
<h1>验证码错误,请重新输入</h1>
返回按钮
<a href="login.html">重新登录</a>
LoginServlet.java
创建Servlet文件
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//0.设置编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
//1.获取用户输入的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
String verifycoide = request.getParameter("verifycoide");
//2.验证验证码是否正确
if("1234".equals(verifycoide)) {
//验证码是正确 //3.1 验证用户名密码
//从数据库中查询一条数据 //username=zhangsan password=123456
if("zhangsan".equals(username) & "123456".equals(password)) {
//4.1用户名密码正确 //当用户输入账户信息时会将数据存入请求变量中,再转发到指定页面
request.setAttribute("username", "zhangsan");
request.getRequestDispatcher("success.html").forward(request, response);
}else {
//4.2用户名或密码错误
PrintWriter out = response.getWriter();
out.write("<h1>用户名或密码错误</h1>");
out.write("<br>");
out.write("<a href='login.html'>重新登录</a>");
}
}else {
//验证码不正确
//3.2跳转页面至
error.html response.sendRedirect("error.html");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}