【ServletContext】存取数据

使用ServletContext来实现存取数据的功能
设计登录页面,成功后跳转,失败则提示
建立登录页面login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>请输入以下内容,完成登录</h2>
<form action="loginservlet" method="get">
    账号:<input type="text" name="username"/><br>
    密码:<input type="text" name="password"/><br>
    <input type="submit" value="登录">

</form>
</body>
</html>

添加loginservlet

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class loginservlet extends HttpServlet {

    /*
    *req:包含请求的信息
    *
    * response:响应数据给浏览器
    * */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取数据
       String username = req.getParameter("username");
       String password = req.getParameter("password");
        //2.校验数据
        PrintWriter pw = resp.getWriter();
        if("admin".equals(username) && "123".equals(password)){
            //成功跳转到login_success.html
            //设置状态码,重新定位 状态码
            resp.setStatus(302);
            //定位跳转的位置是哪一个页面
            resp.setHeader("Location","login_success.html");
        }else{
            System.out.println("登录失败");
            pw.write("login failed...");
        }

    }

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

添加成功跳转页面login_success.html

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

【ServletContext】存取数据_第1张图片
失败:
【ServletContext】存取数据_第2张图片
成功:
【ServletContext】存取数据_第3张图片
注意: System.out.println(“登录失败”) 和 pw.write(“login failed…”) 显示位置不同

你可能感兴趣的:(【Java】)