没有登录不能访问非index.jsp的JSP页面

Posted on 2008-04-10 10:30 wind_miao 阅读(1155) 评论(1)  编辑  收藏 所属分类: Servlet&JSP
loginFilter.java

/**
 * loginFilter.java
 */
package myFilter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 检查 session 中的 username 内容是否为空,为空则没有登录,转发到登录页面, 如果不为空,则分发请求。
 * @author wind
 *
 */
public class loginFilter implements Filter {
 private String onErrorUrl;

 @Override
 public void destroy() {
  // TODO Auto-generated method stub

 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse res = (HttpServletResponse) response;

  HttpSession session = req.getSession();
  String username = (String) session.getAttribute("username");
  boolean flag = true;

  if (username == null) {
   flag = false;
  } else {

  }
  if (flag) {

   /*
    * Causes the next filter in the chain to be invoked, or if the
    * calling filter is the last filter in the chain, causes the
    * resource at the end of the chain to be invoked.
    */
   chain.doFilter(request, response);
  } else {
   /*
    * Forwards a request from a servlet to JSP file on the server.
    */
   req.getRequestDispatcher(onErrorUrl).forward(req, res);
  }
 }

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {

  /*
   * Returns a String containing the value of the named initialization
   * parameter, or null if the parameter does not exist.
   */
  onErrorUrl = filterConfig.getInitParameter("onError");
  if (onErrorUrl == null || "".equals(onErrorUrl)) {
   onErrorUrl = "/index.jsp";
  }
 }

}

web.xml添加以下代码:
<filter>
  <filter-name>loginFilter</filter-name>
  <filter-class>myFilter.loginFilter</filter-class>
  <init-param>
   <param-name>onError</param-name>
   <param-value>/index.jsp</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>loginFilter</filter-name>
  <url-pattern>/havesession/*</url-pattern>
 </filter-mapping>

特别注意:<url-pattern>/havesession/*</url-pattern>这里意思是过滤/havasession/路径中的所有HTTP请求。

Feedback

# re: 没有登录不能访问非index.jsp的JSP页面[未登录]  回复  更多评论   

2012-05-02 18:32 by michael
如果要过滤多个文件夹呢?

只有注册用户登录后才能发表评论。


网站导航:
 

posts - 1, comments - 3, trackbacks - 0, articles - 7

Copyright © wind_miao