本文主要是介绍【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:响应数据给浏览器* */@Overrideprotected 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...");}}@Overrideprotected 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>
失败:
成功:
注意: System.out.println(“登录失败”) 和 pw.write(“login failed…”) 显示位置不同
这篇关于【ServletContext】存取数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!