@WebServlet用在Servlet类上 要与 启动类上扫描注解 @ServletComponentScan 注解,一起使用。

    1、创建servlet类image.png

    2、 @WebServlet``(name = ``"MyServlet"``, value = ``"/myServlet"``) 。其中name = ``"MyServlet"是类名,value = ``"/myServlet" 相当于,urlPatterns = "/my" 是访问路径。

    1. package com.wzy.springbootweb02.servlet;
    2. import javax.servlet.*;
    3. import javax.servlet.http.*;
    4. import javax.servlet.annotation.*;
    5. import java.io.IOException;
    6. @WebServlet(name = "MyServlet", value = "/myServlet")//,urlPatterns = "/my"
    7. public class MyServlet extends HttpServlet {
    8. @Override
    9. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    10. response.getWriter().write("111111");
    11. }
    12. @Override
    13. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    14. }
    15. }

    3、在启动类上面加上扫描注解 @ServletComponentScan``(basePackages = ``"com.wzy.springbootweb02.servlet"``) 扫描Servlet程序。

    1. package com.wzy.springbootweb02;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.boot.web.servlet.ServletComponentScan;
    5. @ServletComponentScan(basePackages = "com.wzy.springbootweb02.servlet")
    6. @SpringBootApplication
    7. public class SpringbootWeb02Application {
    8. public static void main(String[] args) {
    9. SpringApplication.run(SpringbootWeb02Application.class, args);
    10. }
    11. }