JavaWeb作业_用户登录

用户登录案例:
longin.html页面:设计表单,输入用户名、密码、爱好,“提交”至LoginServlet。
LoginServlet:获取login.html页面提交的用户名、密码;判断用户名和密码。
如果为“admin”和“123456”,请求转发跳转sucess.html
否则,如果错误,请求重定向跳转error.html
sucess.html:显示“登录成功”。
error.html:显示“登录失败”。

作业要求-Admin


login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录页</title>
</head>
<body>
<form action="/LoginServlet" method="post">
    用户名:<input type="text" name="username"/><br>
    密码:<input type="password" name="password"/><br>
    性别:<input type="radio" name="sex" value="男"/>男
    <input type="radio" name="sex" value="女"/>女<br>
    爱好:<input type="checkbox" name="hobby" value="学习"/>学习
    <input type="checkbox" name="hobby" value="游戏"/>游戏
    <input type="checkbox" name="hobby" value="看书"/>看书<br>
    <input type="submit" value="登录">
</form>
</body>
</html>

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;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");//设置编码格式,否则输出为乱码或"???"
        PrintWriter out=response.getWriter();
        request.setCharacterEncoding("utf-8");
        //获取参数值
        String name=request.getParameter("username");
        String pwd=request.getParameter("password");
        String sex=request.getParameter("sex");

        //复选框定义类型
        String hobby[]=request.getParameterValues("hobby");

        //输出获取到的参数值
        out.println("用户名:"+name+"<br>");
        out.println("密码:"+pwd+"<br>");
        out.println("性别:"+sex+"<br>");
        out.println("爱好:");

        //复选框输出方式
        for (int i=0;i<hobby.length;i++)
            out.println(hobby[i]+" ");
        if (name.equals("admin")&&pwd.equals("123456"))
            response.setHeader("Refresh","2;URL=http://localhost:8080/success.html");//此处可能有错误,因为不是请求转发方式,但是达到了跳转效果。
        else
            response.sendRedirect("/error.html");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户中心页</title>
</head>
<body>
登陆成功!
</body>
</html>

error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>错误页</title>
</head>
<body>
登录失败!
</body>
</html>

代码下载


项目打包下载