JSP使用Servlet过滤器进行身份验证的方法

   2015-12-14 0
核心提示:这篇文章主要介绍了JSP使用Servlet过滤器进行身份验证的方法,结合实例形式分析了Servlet过滤器的实现方法及jsp身份验证的具体使用技巧,需要的朋友可以参考下

本文实例讲述了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='../login1.htm'</script>");
}
else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
this.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='login1.htm'</script>");
}
}
%>
</html>

希望本文所述对大家JSP程序设计有所帮助。

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

点击排行