作业

本文展示了一个基于Java Servlet的Web应用案例,包括用户登录和注册功能的实现。通过使用HttpServletRequest和HttpServletResponse处理用户请求,利用ServletContext存储用户信息,实现了基本的身份验证流程。
摘要由CSDN通过智能技术生成

在这里插入图片描述

@WebServlet(name = "loginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("username"));
        System.out.println(req.getParameter("password"));

        ServletContext servletContext = getServletContext();
        String paw = (String)servletContext.getAttribute(req.getParameter("username"));
        if(paw == null){
            resp.sendRedirect("/Day55/loginfalse.html");
        }else {
            if ( req.getParameter("password").equals(paw))
            resp.sendRedirect("/Day55/logintrue.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}

@WebServlet(name = "registerServlet",urlPatterns = "/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("username"));
        System.out.println(req.getParameter("password"));

        ServletContext servletContext = getServletContext();
        if(servletContext.getAttribute(req.getParameter("username")) == null){
            servletContext.setAttribute(req.getParameter("username"),req.getParameter("password"));
            resp.sendRedirect("/Day55/registertrue.html");
        }else {
            resp.sendRedirect("/Day55/registerfalse.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}

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

<form action="/Day55/loginServlet" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <button type="submit">登录</button>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
<form action="/Day55/registerServlet" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <button type="submit">注册</button>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值