清梳联工序:请问怎么用Filter实现安全访问的代码啊,

来源:百度文库 编辑:中科新闻网 时间:2024/04/29 15:33:07
在struts里比如说有index.jsp,a.jsp,b.jsp,c.jsp.登陆页面是index.jsp,要是没有通过index.jsp登陆直接进入其它页面将自动跳转到index.jsp请问怎么用filter实现啊,

LoginFilter.java:

public class LoginFilter extends HttpServlet implements Filter {
private FilterConfig filterConfig;
//Handle the passed-in FilterConfig
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}

//Process the request/response pair
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain){
HttpServletRequest re = (HttpServletRequest)request;
HttpServletResponse rs = (HttpServletResponse)response;
HttpSession session = re.getSession();
try {
request.setCharacterEncoding("gb2312");
Object o = session.getAttribute("loginuser");
if (o == null) {
System.out.print("对不起你还没登陆");
rs.sendRedirect("index.jsp");
} else {

filterChain.doFilter(request, response);
}
} catch (ServletException ex) {
} catch (UnsupportedEncodingException ex) {
} catch (IOException ex) {
}
}

//Clean up resources
public void destroy() {
}
}

Action类如下:
public class UserAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
SQLException {
UserActionForm um = (UserActionForm) form;
String username = um.getUsername();
String userpass = um.getUserpass();
HttpSession session = request.getSession();
ConnDb c = new ConnDb();
if (username == null || username.trim().equals("")) {
session.setAttribute("loginuser", "alang");
return mapping.findForward("error");
}
if (c.loginuser(username, userpass)) {
session.setAttribute("loginuser", username);
return mapping.findForward("ok");
} else {
return mapping.findForward("error");
}
}
}

web.xml中filter配置如下:
<filter>
<filter-name>loginfilters</filter-name>
<filter-class>struts1.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginfilters</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
现在运行连首页都打不开了,请各位高手指教,
还是不行

把a.jsp,b.jsp,c.jsp放到一个目录下比如放到page下,把index.jsp放到根目录下然后在web.xml里<url-pattern>/page/*</url-pattern>应该可以的