filter、Interceptor

通过filter来将记住一个月之内的自动登录,通过interceptor来将不在范围之内的请求都让其跳转到指定的页面比如登陆页面

myFilter:

web.xml:

<filter>

<filter-name>myFilter</filter-name>

<filter-class>com.chenghan.yun.mp.filter.SysFilter</filter-class>

</filter>

<!-- 只拦截.do请求 -->

<filter-mapping>

<filter-name>myFilter</filter-name>

<url-pattern>*.do</url-pattern>

</filter-mapping>

class:

public class SysFilter implements Filter {

private IMpBasInfoService mpBasInfoService;

private IBasDao basDao;

@Override

public void init(FilterConfig filterConfig) throws ServletException {

//To change body of implemented methods use File | Settings | File Templates.

ServletContext context = filterConfig.getServletContext();

ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);

mpBasInfoService = (IMpBasInfoService) ctx.getBean("mpBasInfoService");

basDao =(IBasDao)ctx.getBean("basDao");

}

@Override

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

//To change body of implemented methods use File | Settings | File Templates.

HttpServletRequest request = (HttpServletRequest) servletRequest;

HttpSession session = request.getSession(true);

String account = "";

String sessionId = "";   // 此sessionid是上次用户登录时保存于用户端的识别码,用于用户后续访问的自动登录。不是本次访问的session id。

Cookie[] cookies;

CookieManager cm = new CookieManager(); // CookieManager是一个自定义的类,用于从Cookie数组中查找并返回指定名称的Cookie值。

boolean isAutoLogin;

// 如果session中没有user对象,则创建一个。

CrmMicroBusinessCardVO crmMicroBusinessCardVO = (CrmMicroBusinessCardVO) session.getAttribute("crmMicroBusinessCardVO");

// 如果user对象的username为"",表示用户未登录。则执行自动登录过程。

// 否则不自动登录。

if (crmMicroBusinessCardVO == null) {

crmMicroBusinessCardVO = new CrmMicroBusinessCardVO();

// 检查用户浏览器是否发送了上次登录的用户名和sessionid,

// 如果是,则为用户自动登陆。

cookies = request.getCookies();

if(cookies!=null&&cookies.length>0){

account = cm.getCookieValue(cookies, "autoLoginUser");

sessionId = cm.getCookieValue(cookies, "sessionId");

account = "".equals(account)?null:account;

sessionId = "".equals(sessionId)?null:sessionId;

Map<String,Object> map = new HashMap<String,Object>();

map.put("account", account);

map.put("sessionId",sessionId);

boolean isExist = basDao.isExist(MpAccountSessionId.class,map);

if (isExist) {

MpBasInfo userVO = new MpBasInfo();

userVO = basDao.queryOne(MpBasInfo.class,"account",account);

if(userVO!=null){

CrmMicroBusinessCardVO crmMicroBusinessCardVO1 = new CrmMicroBusinessCardVO();

UtilBean.copyBeanAllSimpleProperties(crmMicroBusinessCardVO1,userVO,false);

session.setAttribute("crmMicroBusinessCardVO", crmMicroBusinessCardVO1); // 将user bean添加到session中。

}

}

}

}

filterChain.doFilter(servletRequest, servletResponse);

}

@Override

public void destroy() {

//To change body of implemented methods use File | Settings | File Templates.

}

}

public class CookieManager {

public static String getCookieValue(Cookie cookies[],String cookieName){

String cookieValue = "";

for(int i=0;i<cookies.length;i++){

Cookie cookie = cookies[i];

if(cookie.getName().equals(cookieName)){

cookieValue = cookie.getValue().toString();

break;

}

}

return  cookieValue;

}

}

interceptor:springMVC的

public class SimpleAcInterceptor implements HandlerInterceptor {

public String[] allowUrls;//还没发现可以直接配置不拦截的资源,所以在代码里面来排除

public void setAllowUrls(String[] allowUrls) {

this.allowUrls = allowUrls;

}

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

String contextPath=request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+contextPath+"/";

String requestUrl = request.getRequestURI().replace(contextPath, "");

if(allowUrls == null){

//设置模块allowUril

allowUrls = new String[]{"/login.html"};

}

if(null != allowUrls && allowUrls.length>=1){

for(String url : allowUrls) {

if(requestUrl.contains(url)) {

return true;

}

}

}

CrmMicroBusinessCardVO crmMicroBusinessCardVO = (CrmMicroBusinessCardVO) request.getSession().getAttribute("crmMicroBusinessCardVO");

if(crmMicroBusinessCardVO == null){

if (!(request.getHeader("accept").indexOf("application/json") > -1 ||

(request.getHeader("X-Requested-With")!= null &&

request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {

//非JSON请求

response.sendRedirect(basePath + "login.html");

}else{

PrintWriter fs=response.getWriter();

Map<String,String> map = new HashMap<String,String>();

map.put("status","errors");

map.put("message","系统超时,请重新登录。");

response.setContentType("application/json");

fs.write(JsonUtils.getJsonString(map));

fs.flush();

fs.close();

}

return false;

}

return true;

}

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

//To change body of implemented methods use File | Settings | File Templates.

}

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

//To change body of implemented methods use File | Settings | File Templates.

}

}

springMVC的配置文件

<mvc:interceptors>

<!-- session超时 -->

<mvc:interceptor>

<mvc:mapping path="/*"/>

<bean class="com.chenghan.yun.mp.filter.SimpleAcInterceptor">

<property name="allowUrls">

<list>

<!-- 如果请求中包含以下路径,则不进行拦截 -->

<value>/login.html</value>

<value>/crm_micro_business_card_loginOut.html</value>

<value>/mp_ajax_vcf.html</value>

<value>/crm_micro_business_card_resetPassword_index_card.do</value>

<value>/crm_micro_business_card_resetPassword_card.do</value>

<value>/crm_micro_business_card_validate_index_card.do</value>

<value>/crm_micro_business_card_validate_card.do</value>

<value>/crm_micro_business_card_login_card.do</value>

<value>/crm_micro_business_card_registor_index_card.do</value>

<value>/crm_micro_business_card_validate_registor_card.do</value>

<value>/crm_micro_business_card_password_registor_card.do</value>

<value>/crm_micro_business_card_registor_setPassword_card.do</value>

<value>/business_card_businessCardFinishRegistor_index.do</value>

<value>/business_card_businessCardFinsishRegistor.json</value>

<value>/crm_micro_business_card_businessCard_index_card.do</value>

<value>/mp_ajax_vcf_index.html</value>

<value>/mp_ajax_vcf.html</value>

<value>/mp_save_relation.json</value>

<value>/crm_micro_business_card_detail.json</value>

</list>

</property>

</bean>

</mvc:interceptor>

</mvc:interceptors>

时间: 2024-10-24 11:25:39

filter、Interceptor的相关文章

非spring组件servlet、filter、interceptor中注入spring bean

问题:在filter和interceptor中经常需要调用Spring的bean,filter也是配置在web.xml中的,请问一下这样调用的话,filter中调用Spring的某个bean,这个bean一定存在吗?现在总是担心filter调用bean的时候,bean还没被实例化? 答案:因为spring bean.filter.interceptor加载顺序与它们在 web.xml 文件中的先后顺序无关.即不会因为 filter 写在 listener 的前面而会先加载 filter.最终得出

Spring 梳理 - filter、interceptor、aop实现与区别 -第一篇

前言 项目中我们经常需要对RESTful api进行拦截,主流实现方法有filter.interceptor.aop,先说一下他们各自的实现. Filter AnimalFilter实现javax.servlet.Filter,项目启动时已初始化完成,可在控制台看到打印的初始化日志. @Component    public class AnimalFilter implements Filter {             private Logger logger = LoggerFacto

Filter、Interceptor、Aspect 区别及实现

Fliter 过滤器 请求在到达Controller之前进行与返回去之后 调用 入参为 reuqest,response,chian,过滤器获取不了具体调用哪一个类,哪一个方法. 实现: 1.继承 Filter 接口 import java.io.IOException; import java.util.Date; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.Filter

Java的Servlet、Filter、Interceptor、Listener

写在前面: 使用Spring-Boot时,嵌入式Servlet容器可以通过扫描注解(@ServletComponentScan)的方式注册Servlet.Filter和Servlet规范的所有监听器(如HttpSessionListener监听器). Spring boot 的主 Servlet 为 DispatcherServlet,其默认的url-pattern为"/".一般情况系统默认的Servlet就够用了,如果需要自定义Servlet,可以继承系统抽象类HttpServlet

Spring 梳理 - filter、interceptor、aop实现与区别 -第二篇

spring mvc中的Interceptor可以理解为是Spring MVC框架对AOP的一种实现方式.一般简单的功能又是通用的,每个请求都要去处理的,比如判断token是否失效可以使用spring mvc的HanlderInterceptor, 复杂的,比如缓存,需要高度自定义的就用spring aop.一般来说service层更多用spring aop,controller层有必要用到request和response的时候,可以用拦截器. servlet filter和spring mvc

过滤器/拦截器/监听器 —— Filter、Interceptor、Listener

一.Filter的功能 filter功能,它使用户可以改变一个 request和修改一个response. Filter 不是一个servlet,它不能产生一个response,它能够在一个request到达servlet之前预处理request,也可以在离开 servlet时处理response.换种说法,filter其实是一个"servlet chaining"(servlet 链). 一个Filter包括: 1)在servlet被调用之前截获; 2)在servlet被调用之前检查

使用SpringMVC开发Restful API(2)-使用Filter、Interceptor对请求进行拦截和处理拦截顺序

一 使用Filter拦截请求: 1.使用Filter拦截只需要我们定义一个类并实现javax.servlet.Filter接口,然后将其注册为bean即可. 示例: import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; im

springboot filter and interceptor

1.1  filter.interceptor 1.1.1    filter 过滤器 1.1.1.1  实现方法 init(FilterConfig paramFilterConfig) - 当容器初始化filter时调用,该方法在filter的生命周期只会被调用一次(单例). doFilter(ServletRequest request, ServletResponse response, FilterChain chain) – web容器每一次请求都会调用该方法.注意这里是通过容器的回

过滤器(Filter)、拦截器(Interceptor)、监听器(Listener)

一.Filter 过滤器 1.简介 Filter也称之为过滤器,它是Servlet技术中最实用的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能.例如实现URL级别的权限访问控制.过滤敏感词汇.压缩响应信息等一些高级功能. 它主要用于对用户请求进行预处理,也可以对HttpServletResponse 进行后处理.使用Filter 的完整流程:Filter 对用户请求