过滤器。。
RequestFilter.java
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 org.activiti.engine.impl.util.json.JSONObject; import com.alibaba.druid.support.json.JSONUtils; import com.bcxcore.modules.util.JsonUtil; /** * @ClassName: RequestFilter * @Description:filter的三种典型应用: 1、可以在filter中根据条件决定是否调用chain.doFilter(request, * response)方法, 即是否让目标资源执行 * 2、在让目标资源执行之前,可以对request\response作预处理,再让目标资源执行 * 3、在目标资源执行之后,可以捕获目标资源的执行结果,从而实现一些特殊的功能 */ public class RequestFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { //System.out.println("----过滤器初始化----"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // 对request和response进行一些预处理 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); System.out.println("执行前!!!"); //处理url加密 问题 if (req.getMethod().equals("POST")){ System.out.println("post请求"); }else{ System.out.println("post请求"); } int code=0; String jsonStr=request.getParameter("jsonData"); JSONObject json = new JSONObject(jsonStr); if(json!=null&&json.get("date")!=null&&json.get("token")!=null){ String currentTime=json.getString("date"); String token=json.getString("token"); code=JsonUtil.getVerification(currentTime,token); } request.setAttribute("code", code); chain.doFilter(request, response); // 让目标资源执行,放行 System.out.println("RequestFilter执行后!!!"); } @Override public void destroy() { System.out.println("----过滤器销毁----"); } }
web.xml 配置
<!--配置过滤器--> <filter> <filter-name>RequestFilter</filter-name> <filter-class>com.javaweb.topmon.filter.RequestFilter</filter-class> </filter> <!--映射过滤器--> <filter-mapping> <filter-name>RequestFilter</filter-name> <!--“/*”表示拦截所有的请求 --> <url-pattern>/q/*</url-pattern> </filter-mapping>
不是很难。。