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

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

  1. /**
  2. * Created by xiaxuan on 16/11/1.
  3. */
  4. @WebFilter(urlPatterns = "/*",filterName="CharacterEncodeFilter",
  5. initParams={
  6. @WebInitParam(name="encoding",value="UTF-8"),
  7. @WebInitParam(name = "forceEncoding", value = "true")
  8. })
  9. @Singleton
  10. public class CharacterEncodingFilter implements Filter {
  11. private String encoding = "UTF-8";
  12. private boolean forceEncoding = true;
  13. @Override
  14. public void init(FilterConfig filterConfig) throws ServletException {
  15. this.encoding = filterConfig.getInitParameter("encoding");
  16. String force = filterConfig.getInitParameter("forceEncoding");
  17. this.forceEncoding = (force == null) || Boolean.valueOf(force);
  18. }
  19. @Override
  20. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  21. if (this.forceEncoding || request.getCharacterEncoding() == null) {
  22. request.setCharacterEncoding(this.encoding);
  23. response.setCharacterEncoding(this.encoding);
  24. }
  25. chain.doFilter(request, response);
  26. }
  27. @Override
  28. public void destroy() {
  29. }
  30. public void setEncoding(String encoding) {
  31. this.encoding = encoding;
  32. }
  33. public void setForceEncoding(boolean forceEncoding) {
  34. this.forceEncoding = forceEncoding;
  35. }
  36. }

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

  1. @SpringBootApplication
  2. @ServletComponentScan
  3. @ComponentScan
  4. public class SpringBootWebApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(SpringBootWebApplication.class, args);
  7. }
  8. }

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

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

@ServletComponentScan的源码如下:

  1. /**
  2. * Enables scanning for Servlet components ({@link WebFilter filters}, {@link WebServlet
  3. * servlets}, and {@link WebListener listeners}). Scanning is only performed when using an
  4. * embedded Servlet container.
  5. * <p>
  6. * Typically, one of {@code value}, {@code basePackages}, or {@code basePackageClasses}
  7. * should be specified to control the packages to be scanned for components. In their
  8. * absence, scanning will be performed from the package of the class with the annotation.
  9. *
  10. * @author Andy Wilkinson
  11. * @since 1.3.0
  12. * @see WebServlet
  13. * @see WebFilter
  14. * @see WebListener
  15. */
  16. @Target(ElementType.TYPE)
  17. @Retention(RetentionPolicy.RUNTIME)
  18. @Documented
  19. @Import(ServletComponentScanRegistrar.class)
  20. public @interface ServletComponentScan {
  21. /**
  22. * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation
  23. * declarations e.g.: {@code @ServletComponentScan("org.my.pkg")} instead of
  24. * {@code @ServletComponentScan(basePackages="org.my.pkg")}.
  25. * @return the base packages to scan
  26. */
  27. @AliasFor("basePackages")
  28. String[] value() default {};
  29. /**
  30. * Base packages to scan for annotated servlet components. {@link #value()} is an
  31. * alias for (and mutually exclusive with) this attribute.
  32. * <p>
  33. * Use {@link #basePackageClasses()} for a type-safe alternative to String-based
  34. * package names.
  35. * @return the base packages to scan
  36. */
  37. @AliasFor("value")
  38. String[] basePackages() default {};
  39. /**
  40. * Type-safe alternative to {@link #basePackages()} for specifying the packages to
  41. * scan for annotated servlet components. The package of each class specified will be
  42. * scanned.
  43. * @return classes from the base packages to scan
  44. */
  45. Class<?>[] basePackageClasses() default {};
  46. }

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

  1. @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. gitlab中的CI

    https://blog.csdn.net/chengzi_comm/article/details/78778284

  2. Swift 发送邮件和附件

    public function send($filename, array $render = [],$subject = '审核通知') { // Create the Transport $tra ...

  3. react native配置ip真机测试

    首先保证真机和pc 保证在同一个网络下 根据红色错误判断自己是什么情况 例如 提示无法连接远程服务,说明你的不在同一网络下 提示500 可能配置的ip不对 设置ip方法 摇晃手机 ---> De ...

  4. unity快捷放置物体操作

    https://connect.unity.com/p/zui-jia-shi-jian-dui-xiang-fang-zhi-he-wu-li-xiao-guo 最佳实践系列文章将探讨我们在与客户合 ...

  5. MySQL之视图学习

    MYSQL---视图 1.概述: ​ 视图是从一个或者多个表中导出的,视图的行为与表非常类似,但视图是一个虚拟表.在视图中用户可以使用SELECT语句查询数据,以及使用INSERT.UPDATE和DE ...

  6. CDH管理节点扩容磁盘步骤

    把4个节点加12G内存,把hive的heap调到6G,按group重启服务让配置生效 注: 停服务前在yarn的application webui查flink的application id yarn ...

  7. day 01 常量 注释 int(整型) 用户交互input 流程控制语句if

    python的编程语言分类(重点) if 3 > 2: 编译型: 将代码一次性全部编译成二进制,然后再执行. 优点:执行效率高. 缺点:开发效率低,不能跨平台. 代表语言:C 解释型: 逐行解释 ...

  8. RabbitMQ入门教程(十):队列声明queueDeclare

    原文:RabbitMQ入门教程(十):队列声明queueDeclare 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https:// ...

  9. 如何在Ubuntu上在多个PHP版本之间切换 (for swoole)

    摘要: 之前一直用Php7.0,今天想用7.2试下一些特性,安装完之后,切换回7.0却不能再使用7.0的swoole了,原来是切换方式出现了问题 一 从PHP 7.0 切换到 PHP 7.2 Apac ...

  10. java复习(3)继承

    一.继承为题的提出 ---------------------------------------------------- 我们知道面向对象的三大特性是:封装.继承和多态,可以知道继承在java应用 ...