springboot掃描自定義的servlet和filter代碼詳解
這幾天使用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中,這樣注解加上去并沒有多大用處,最后會發(fā)現這個filter仍然沒有起作用。
我自己編寫的應用有兩個,最開始的做法是把filter從core包中拆出來,然后在兩個模塊中各自添加一個,但是這樣未免有些代碼冗余,并且實現方式并不優(yōu)雅,然后我查看了下@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注解和動態(tài)代理 、Java之Spring注解配置bean實例代碼解析、淺談Springboot之于Spring的優(yōu)勢等。有什么問題可以隨時留言,小編會及時回復大家。同時希望朋友們對腳本之家網站多多支持!
- SpringBoot集成WebServlet出現自定義servlet請求失敗的問題解決方案
- SpringBoot里使用Servlet進行請求的實現示例
- Springboot注入成員變量HttpServletRequest的原理分析
- SpringBoot3.1.2 引入Swagger報錯Type javax.servlet.http.HttpServletRequest not present解決辦法
- 解決IDEA啟動springboot項目報錯java.lang.ClassNotFoundException:?javax.servlet.ServletContext
- SpringBoot獲取HttpServletRequest的3種方式總結
- Springboot如何添加server.servlet.context-path相關使用
- SpringBoot項目找不到javax.servlet.Filter的問題及解決
- SpringBoot如何切換成其它的嵌入式Servlet容器(Jetty和Undertow)
相關文章
IDEA創(chuàng)建Spring項目無法選擇Java8的問題及解決
文章描述了在使用Spring創(chuàng)建項目時遇到的問題,通過將服務器地址從https://start.spring.io/替換為https://start.aliyun.com/,成功解決了無法選擇Java8的問題2025-01-01
Java并發(fā)編程之詳解CyclicBarrier線程同步
在之前的文章中已經為大家介紹了java并發(fā)編程的工具:BlockingQueue接口,ArrayBlockingQueue,DelayQueue,LinkedBlockingQueue,PriorityBlockingQueue,SynchronousQueue,BlockingDeque接口,ConcurrentHashMap,CountDownLatch,本文為系列文章第十篇,需要的朋友可以參考下2021-06-06

