The interceptor in struts2 can intercept actions, but cannot intercept page requests. However, some pages can be accessed only after they have the permission, but cannot be accessed directly. One solution is to use the Filter
1. To create a Filter class, you must implement the Filter interface:
[Java]
Package filter;
Import java. io. IOException;
Import java. util. Map;
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. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Import javax. servlet. http. HttpSession;
Import model. Admin;
Public class LoginFilter implements Filter {
// Private Map session;
Public void destroy (){
}
Public void doFilter (ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
HttpSession session = request. getSession ();
Admin admin = (Admin) session. getAttribute ("nowUser ");
System. out. println (admin );
If (admin = null ){
Response. sendRedirect ("login.html ");
}
Chain. doFilter (request, response );
}
Public void init (FilterConfig arg0) throws ServletException {
}
}
In dofiltercontext, the filter function is used to verify whether the user logs on to the index.html page. If the user logs on, the system continues to run. Otherwise, the system returns to the logon page.
You also need to configure web. xml: Add the following code
[Html]
<Filter>
<Filter-name> loginFilter </filter-name>
<Filter-class> filter. LoginFilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-name> loginFilter </filter-name>
<Url-pattern>/index.html </url-pattern>
</Filter-mapping>
Configuration file:
1. filter all requests:
[Html]
<Filter-mapping>
<Filter-name> filter </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>
2. filter the specified type of requests: Filter only the. html files.
[Html]
Filter-mapping>
<Filter-name> filter </filter-name>
<Url-pattern> *. html </url-pattern>
</Filter-mapping>
3. filter multiple types: You need to configure two <filter-mapping>
[Html]
<Filter-mapping>
<Filter-name> filter </filter-name>
<Url-pattern> *. html </url-pattern>
</Filter-mapping>
<Filter-mapping>
<Filter-name> filter </filter-name>
<Url-pattern> *. jsp </url-pattern>
</Filter-mapping>
4. filter the specified file: this is the case just now. Add "/".
[Html]
<Filter-mapping>
<Filter-name> loginFilter </filter-name>
<Url-pattern>/index.html </url-pattern>
</Filter-mapping>