JSP使用Servlet过滤器进行身份验证的方法
Java  /  管理员 发布于 7年前   163
本文实例讲述了JSP使用Servlet过滤器进行身份验证的方法。分享给大家供大家参考,具体如下:
1、Servlet过滤器的作用描述
(1)在HttpServletRequest到达Servlet 之前,拦截客户的HttpServletRequest。
根据需要检查HttpServletRequest,也可以修改HttpServletRequest头和数据。
(2)在HttpServletResponse 到达客户端之前,拦截HttpServletResponse。
根据需要检查HttpServletResponse,可以修改HttpServletResponse头和数据。
2、应用Servlet过滤器进行身份验证
假设网站根目录下的login1.htm、longin1.jsp用于用户登录,而chap08目录下的文件需要用户登录后才能访问。
(1)编写Servlet过滤器
@WebFilter("/FilterStation")public class FilterStation extends HttpServlet implements Filter {private FilterConfig filterConfig;public FilterStation() {super();}public void destroy() {}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpSession session=((HttpServletRequest)request).getSession();response.setCharacterEncoding("gb2312");if(session.getAttribute("me")==null){PrintWriter out=response.getWriter();out.print("<script>alert('请登录!');location.href='https:/article/../login1.htm'</script>");}else{// pass the request along the filter chainchain.doFilter(request, response);}}public void init(FilterConfig fConfig) throws ServletException {// TODO Auto-generated method stubthis.filterConfig=fConfig;}}
(2)配置web.xml
<filter><filter-name>filterstation</filter-name><filter-class>zhou.FilterStation</filter-class></filter><filter-mapping><filter-name>filterstation</filter-name><url-pattern>/chap08/*</url-pattern></filter-mapping>
(3)login1.htm代码
<html><head><title>用户登录</title></head><body><form method="POST" action="login1.jsp"><p>用户名:<input type="text" name="user" size="18"></p><p>密码:<input type="text" name="pass" size="20"></p><p><input type="submit" value="提交" name="ok"><input type="reset" value="重置" name="cancel"></p></form></body></html>
(4)login1.jsp代码
<%@ page contentType="text/html;charset=GB2312" %><html><head><title>Session 应用演示</title></head><% if (request.getParameter("user")!=null && request.getParameter("pass")!=null){String strName=request.getParameter("user");String strPass=request.getParameter("pass");if (strName.equals("admin") && strPass.equals("admin")){session.setAttribute("login","OK");session.setAttribute("me",strName);response.sendRedirect("chap08/welcome.jsp");}else{out.print("<script>alert('用户名或密码错误');location.href='https:/article/login1.htm'</script>");}}%></html>
希望本文所述对大家JSP程序设计有所帮助。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号