springboot servlet注册(@WebServlet实现)


springboot servlet注册(@WebServlet实现)

 

*********************************

相关注解

 

@WebServlet

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WebServlet {

    String name() default "";            //servlet的名称
    String[] urlPatterns() default {};   //servelt拦截的路径

    String[] value() default {};
    int loadOnStartup() default -1;
    WebInitParam[] initParams() default {};
    boolean asyncSupported() default false;

    String smallIcon() default "";

    String largeIcon() default "";

    String description() default "";

    String displayName() default "";
}

 

@ServletComponentScan:扫描创建servlet的实例bean

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({ServletComponentScanRegistrar.class})
public @interface ServletComponentScan {
    @AliasFor("basePackages")
    String[] value() default {};

    @AliasFor("value")
    String[] basePackages() default {};  //扫描指定的包

    Class[] basePackageClasses() default {};  //扫描指定的类
}

 

 

*********************************

示例

 

************************************

自定义servlet

 

@WebServlet(name="myServlet",urlPatterns = {"/hello","/hello2"})
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getOutputStream().println("hello world");
    }
}

说明:urlPatterns不支持通配符

 

************************************

扫描创建servlet的实例bean

 

@Configuration
@ServletComponentScan(basePackages = {"com.example.demo.pojo"})
public class WebConfig {

}

 

 

*********************************

测试输出

 

localhost:8080/hello2

                        

 

 

 

你可能感兴趣的:(springboot)