过滤器和拦截器的使用
1.创建请求编码的过滤器
package com.ch.filter; 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; public class EncodeFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); chain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
1.2在web.xml中进行配置
<!-- 过滤器配置 --> <filter> <filter-name>encorder</filter-name> <filter-class>com.ch.filter.EncodeFilter</filter-class> </filter> <filter-mapping> <filter-name>encorder</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.创建关于用户登录拦截的拦截器
package com.ch.intercept; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionProxy; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class CheckedUser extends AbstractInterceptor{ @Override public String intercept(ActionInvocation invocation) throws Exception { // 获取ActionContext对象 ActionContext ac = invocation.getInvocationContext(); // 获取action的代理对象 ActionProxy proxy = invocation.getProxy(); // 获取当前执行的方法名 String methodName = proxy.getMethod(); // 判断 if (!"login".equals(methodName)) { if("register".equals(methodName)){ // 说明当前用户正在注册 return invocation.invoke(); }else{ // 先获取当前登陆的用户 Object obj = ac.getSession().get("username"); if (obj == null) { // 没有登陆 return "input"; } else { // 当前用户有登陆 return invocation.invoke(); } } } else { // 说明当前用户正在登陆 return invocation.invoke(); } } }
2.1在struts.xml中进行配置
<!-- 【拦截器配置】 -->
<interceptors>
<interceptor name="loginCheck" class="com.ch.intercept.CheckedUser"></interceptor>
<interceptor-stack name="myStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="loginCheck"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"></default-interceptor-ref>