spring boot 整合servlet 两种方式

方式一

@WebServlet(name = "FirstServlet",urlPatterns = "/first")
public class ServletOne extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ServletOne!");
    }
}

启动类

//Springboot启动项注解
@SpringBootApplication
//自动扫描Servlet注解
@ServletComponentScan
public class ServletAppOne {
    public static void main(String[] args){
        SpringApplication.run(ServletAppOne.class,args);
    }
}

运行结果

方式二

public class ServletTwo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ServletTwo!");
    }
}

启动类

//Springboot启动项注解
@SpringBootApplication
public class ServletAppTwo {
    public static void main(String[] args){
        SpringApplication.run(ServletAppTwo.class,args);
    }

    //自动扫描获取servlet对象
    @Bean
    public ServletRegistrationBean getServletRegistrationBean(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new ServletTwo());
        bean.addUrlMappings("/second");
        return bean;
    }
}

运行结果


spring boot 进行文件上传

@RestController
public class FileUpLoadController {
    //处理文件上传  
    @RequestMapping("/fileUploadController")
    public Map<String, Object> fileUpload(MultipartFile filename)throws Exception{
        System.out.println(filename.getOriginalFilename());
        //设置文件上传的路径
        filename.transferTo(new File("f:/"+filename.getOriginalFilename()));
        //定义map
        Map<String, Object> map = new HashMap<>();
        //返回提示信息
        map.put("msg", "ok");
        return map;
    }
}

测试html页:

<body>
    <form action="fileUploadController" method="post" enctype="multipart/form-data">
        上传文件:<input type="file" name="filename"><br/>
        <input type="submit"/>
    </form>
</body>

亲测有效!

spring boot 访问静态资源

1. resources目录下的static文件夹

2. src\main目录下的webapp文件夹

好记性不如烂笔头!

发布了214 篇原创文章 · 获赞 281 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/lk1822791193/article/details/89740471