文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习

这几天使用spring boot编写公司一个应用,在编写了一个filter,用于指定编码的filter,如下:

/**
 * Created by xiaxuan on 16/11/1.
 */
@WebFilter(urlPatterns = "/*",filterName="CharacterEncodeFilter",
    initParams={
        @WebInitParam(name="encoding",value="UTF-8"),
        @WebInitParam(name = "forceEncoding", value = "true")
    })
@Singleton
public class CharacterEncodingFilter implements Filter {
  private String encoding = "UTF-8";
  private boolean forceEncoding = true;
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    this.encoding = filterConfig.getInitParameter("encoding");
    String force = filterConfig.getInitParameter("forceEncoding");
    this.forceEncoding = (force == null) || Boolean.valueOf(force);
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (this.forceEncoding || request.getCharacterEncoding() == null) {
      request.setCharacterEncoding(this.encoding);
      response.setCharacterEncoding(this.encoding);
    }
    chain.doFilter(request, response);
  }
  @Override
  public void destroy() {
  }
  public void setEncoding(String encoding) {
    this.encoding = encoding;
  }
  public void setForceEncoding(boolean forceEncoding) {
    this.forceEncoding = forceEncoding;
  }
}

但是在实际使用的时候,却是完全没有起作用,后来查看了一下springboot的官方文档,filter和servlet、listener之类的需要单独进行注册才能使用,但是spring boot里面提供了一个注解来替代,为@ServletComponentScan,这个注解直接加在对应的Application启动类上即可,如下:

@SpringBootApplication
@ServletComponentScan
@ComponentScan
public class SpringBootWebApplication {
  public static void main(String[] args) {
    SpringApplication.run(SpringBootWebApplication.class, args);
  }
}

这样编写完之后,如果对应的filter是在自己当前模块下的某个package中的时候是可以起作用的,但是如果本身项目中有多个模块的时候,如果filter在一个类似与core下的package中,这样注解加上去并没有多大用处,最后会发现这个filter仍然没有起作用。

我自己编写的应用有两个,最开始的做法是把filter从core包中拆出来,然后在两个模块中各自添加一个,但是这样未免有些代码冗余,并且实现方式并不优雅,然后我查看了下@ServletComponentScan的源码,里面确实是有更好的解决方法。

@ServletComponentScan的源码如下:

/**
 * Enables scanning for Servlet components ({@link WebFilter filters}, {@link WebServlet
 * servlets}, and {@link WebListener listeners}). Scanning is only performed when using an
 * embedded Servlet container.
 * <p>
 * Typically, one of {@code value}, {@code basePackages}, or {@code basePackageClasses}
 * should be specified to control the packages to be scanned for components. In their
 * absence, scanning will be performed from the package of the class with the annotation.
 *
 * @author Andy Wilkinson
 * @since 1.3.0
 * @see WebServlet
 * @see WebFilter
 * @see WebListener
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ServletComponentScanRegistrar.class)
public @interface ServletComponentScan {
  /**
   * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation
   * declarations e.g.: {@code @ServletComponentScan("org.my.pkg")} instead of
   * {@code @ServletComponentScan(basePackages="org.my.pkg")}.
   * @return the base packages to scan
   */
  @AliasFor("basePackages")
  String[] value() default {};
  /**
   * Base packages to scan for annotated servlet components. {@link #value()} is an
   * alias for (and mutually exclusive with) this attribute.
   * <p>
   * Use {@link #basePackageClasses()} for a type-safe alternative to String-based
   * package names.
   * @return the base packages to scan
   */
  @AliasFor("value")
  String[] basePackages() default {};
  /**
   * Type-safe alternative to {@link #basePackages()} for specifying the packages to
   * scan for annotated servlet components. The package of each class specified will be
   * scanned.
   * @return classes from the base packages to scan
   */
  Class<?>[] basePackageClasses() default {};
}

这里有一个value()属性,上面的注解默认为basePackage,那么在扫描的时候就只扫描当前模块下面的包,其他不扫描,如果要连同其他模块一起扫描的话,给这个属性加上值即可,如下:

@ServletComponentScan(value = "cn.com")

如上,自定义的filter和servlet就可以正常起作用。

总结

以上就是本文关于springboot扫描自定义的servlet和filter代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以参阅:浅谈Java注解和动态代理 、Java之Spring注解配置bean实例代码解析、浅谈Springboot之于Spring的优势等。有什么问题可以随时留言,小编会及时回复大家。同时希望朋友们对嗨学网多多支持!

原文地址是:http://www.piaodoo.com/thread-13237-1-2.html 丝袜控www.txdah.com 131www.buzc.org学习之外可赏心悦目有助更好地学习!

springboot扫描自定义的servlet和filter代码详解_java - JAVA的更多相关文章

  1. Spring Boot 2.X(十):自定义注册 Servlet、Filter、Listener

    前言 在 Spring Boot 中已经移除了 web.xml 文件,如果需要注册添加 Servlet.Filter.Listener 为 Spring Bean,在 Spring Boot 中有两种 ...

  2. Shiro的Filter机制详解---源码分析

    Shiro的Filter机制详解 首先从spring-shiro.xml的filter配置说起,先回答两个问题: 1, 为什么相同url规则,后面定义的会覆盖前面定义的(执行的时候只执行最后一个). ...

  3. Shiro的Filter机制详解---源码分析(转)

    Shiro的Filter机制详解 首先从spring-shiro.xml的filter配置说起,先回答两个问题: 1, 为什么相同url规则,后面定义的会覆盖前面定义的(执行的时候只执行最后一个). ...

  4. 代码详解:TensorFlow Core带你探索深度神经网络“黑匣子”

    来源商业新知网,原标题:代码详解:TensorFlow Core带你探索深度神经网络“黑匣子” 想学TensorFlow?先从低阶API开始吧~某种程度而言,它能够帮助我们更好地理解Tensorflo ...

  5. Java中String的intern方法,javap&cfr.jar反编译,javap反编译后二进制指令代码详解,Java8常量池的位置

    一个例子 public class TestString{ public static void main(String[] args){ String a = "a"; Stri ...

  6. 委托与事件代码详解与(Object sender,EventArgs e)详解

    委托与事件代码详解 using System;using System.Collections.Generic;using System.Text; namespace @Delegate //自定义 ...

  7. BM算法  Boyer-Moore高质量实现代码详解与算法详解

    Boyer-Moore高质量实现代码详解与算法详解 鉴于我见到对算法本身分析非常透彻的文章以及实现的非常精巧的文章,所以就转载了,本文的贡献在于将两者结合起来,方便大家了解代码实现! 算法详解转自:h ...

  8. ASP.NET MVC 5 学习教程:生成的代码详解

    原文 ASP.NET MVC 5 学习教程:生成的代码详解 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 添加模型 创建连接字符串 ...

  9. Github-karpathy/char-rnn代码详解

    Github-karpathy/char-rnn代码详解 zoerywzhou@gmail.com http://www.cnblogs.com/swje/ 作者:Zhouwan  2016-1-10 ...

随机推荐

  1. VS2013配置curl

    http://blog.csdn.net/totodum/article/details/51059380 安装完成之后,要注意url的传值, curl中需要传char*

  2. vtkTestHull将多个平面围成一个凸面体

    1.vtkHull produce an n-sided convex hull vtkHull is a filter which will produce an n-sided convex hu ...

  3. 【HANA系列】SAP 【第二篇】EXCEL连接SAP HANA的方法(ODBC)

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[HANA系列]SAP [第二篇]EXCEL连接 ...

  4. gitlab ssh 免密登录

    打开本地git   使用 ssh-keygen 工具 输入命令  ssh-keygen -t rsa -C '你的邮箱账号' 接下来输入密码 确认密码 找到目录 找到公钥 在 gitlab 用户设置  ...

  5. Java网络爬虫

    一.前言 首先我们把准备工作做好:IDEA 2019.1.JDK1.8.Maven3.5 Jsoup的Maven依赖: <dependency> <groupId>org.js ...

  6. 第十四周课程总结&&实验总结

    课程总结: 1.Java实现跨平台操作的工具:JDBC. 它的意思是java数据库连接,可以方便的实现多种关系型数据库的统一操作,它由一组用java语句编写的类和接口组成. 2.JDBC驱动分类: J ...

  7. 2019JAVA第三次实验报告

    Java实验报告 班级 计科二班 学号 20188442 姓名 吴怡君 完成时间 2019.9.24 评分等级 实验三 String类的应用 一.实验目的 掌握类String类的使用: 学会使用JDK ...

  8. FPGA —— LED控制

    第一次接触新东西的时候,难免会磕磕碰碰,不过遇到问题不要着急,慢慢来.原因总归是我们自己引起的,一步步找到问题的根源,然后彻底解决它,避免下次再犯. 在开始之前先分享一下工具:(Quartus II ...

  9. AKKA学习(二) 未完

    Actor调用 从上面的例子中,我们可以大概的对AKKA在JAVA中的使用有一个全局的概念.这里我们在稍微细致的讲解一下. 在JAVA中使用AKKA进行开发主要有这几个步骤: 定义消息模型. 创建Ac ...

  10. CF 1136B Nastya Is Playing Computer Games

    题目链接:codeforces.com/problemset/problem/1136/B 题目分析 首先,读完题目,看了是个B题,嗯嗯...... 果断找规律,然后交了一波,居然过了!!! 代码区 ...