這篇文章主要介紹了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程序設計有所幫助。
新聞熱點
疑難解答