SpringBoot整合篇

打印 上一主题 下一主题

主题 872|帖子 872|积分 2616

目录

SpringBoot整合Servlet
整合方式一
1.1 创建servlet
1.2启动类中配置
1.3 启动测试
整合方式二
2.1创建servlet
2.2 修改启动类
2.3 启动程序测试
SpringBoot整合Filter
整合方式一
1.创建过滤器
2.创建启动类
3.启动测试
整合方式二
1.创建过滤器
2.创建启动类
3.启动测试
SpringBoot整合Listener
整合方式一
1.创建Listener
2.创建启动器
3.启动测试
整合方式二
文件上传和下载
上传操纵
下载操纵
SpringBoot整合Freemarker
SpringBoot整合Thymeleaf
Thymeleaf基本使用


SpringBoot整合Servlet

整合方式一

1.1 创建servlet

  在src对应的目录下创建一个servlet,添加相关的get方法,设置@WebServlet注解,如下:
  1. @WebServlet(name = "FirstServlet",urlPatterns = "/first")
  2. public class FirstServlet extends HttpServlet {
  3.     @Override
  4.     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5.         System.out.println("--doGet方法执行了----");
  6.         PrintWriter out = resp.getWriter();
  7.         out.write("success");
  8.         out.flush();
  9.         out.close();
  10.     }
  11. }
复制代码
1.2启动类中配置

在启动类的头部我们通过@ServletComponentScan注解来加载自界说的Servlet
  1. @SpringBootApplication
  2. //在 springBoot 启动时会扫描@WebServlet,并将该类实例化
  3. @ServletComponentScan()
  4. public class Springboot01ServletApplication {
  5.     public static void main(String[] args) {
  6.         SpringApplication.run(Springboot01ServletApplication.class, args);
  7.     }
  8. }
复制代码
1.3 启动测试

通过启动类启动程序访问:http://localhost:8080/first 如下
success
整合方式二

2.1创建servlet

第二种整合servlet的方式不必要在servlet的头部添加@WebServlet注解。
  1. public class SecondServlet extends HttpServlet {
  2.     @Override
  3.     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4.         System.out.println("--doGet方法执行了----");
  5.         PrintWriter out = resp.getWriter();
  6.         out.write("success  second");
  7.         out.flush();
  8.         out.close();
  9.     }
  10. }
复制代码
2.2 修改启动类

必要在启动类中单独注册servlet,创建一个新的启动类,具体如下:
  1. @SpringBootApplication
  2. public class App {
  3.     public static void main(String[] args) {
  4.         SpringApplication.run(App.class,args);
  5.     }
  6.     @Bean
  7.     public ServletRegistrationBean getServletRegistrationBean(){
  8.         // 直接获取ServletRegistrationBean对象 并关联自定义的servlet
  9.         ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
  10.         // 设置servlet对应的 UrlMapping
  11.         bean.addUrlMappings("/second");
  12.         return bean;
  13.     }
  14. }
复制代码
2.3 启动程序测试

通过新创建的App启动类启动程序,访问测试 http://localhost:8080/second
success second

SpringBoot整合Filter

整合方式一

1.创建过滤器

创建Filter,而且通过@WebFilter注解配置过滤信息,具体如下:
  1. @WebFilter(urlPatterns = "/first")
  2. public class FirstFilter implements Filter {
  3.     @Override
  4.     public void init(FilterConfig filterConfig) throws ServletException {
  5.     }
  6.     @Override
  7.     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  8.         System.out.println("First过滤器:firstServlet 执行之前");
  9.         filterChain.doFilter(servletRequest,servletResponse);
  10.         System.out.println("First过滤器:firstServlet 执行之后");
  11.     }
  12.     @Override
  13.     public void destroy() {
  14.     }
  15. }
复制代码
2.创建启动类

启动类和我们前面整合Servlet的第一种方式是一样的。
  1. @SpringBootApplication
  2. //在 springBoot 启动时会扫描@WebServlet,并将该类实例化
  3. @ServletComponentScan()
  4. public class Springboot01ServletApplication {
  5.     public static void main(String[] args) {
  6.         SpringApplication.run(Springboot01ServletApplication.class, args);
  7.     }
  8. }
复制代码
3.启动测试

通过启动器启动程序测试如下

整合方式二

1.创建过滤器

创建新的过滤器,不消配置@WebFilter注解,我们同样在启动类中注册过滤器。
 
  1. @WebFilter(urlPatterns = "/first")
  2. public class FirstFilter implements Filter {
  3.     @Override
  4.     public void init(FilterConfig filterConfig) throws ServletException {
  5.     }
  6.     @Override
  7.     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  8.         System.out.println("First过滤器:firstServlet 执行之前");
  9.         filterChain.doFilter(servletRequest,servletResponse);
  10.         System.out.println("First过滤器:firstServlet 执行之后");
  11.     }
  12.     @Override
  13.     public void destroy() {
  14.     }
  15. }
复制代码
2.创建启动类

添加获取FilterRegistrationBean对象的方法,并在该方法中注册Filter及配置拦截的请求的URL
  1. @SpringBootApplication
  2. public class App {
  3.     public static void main(String[] args) {
  4.         SpringApplication.run(App.class,args);
  5.     }
  6.     @Bean
  7.     public ServletRegistrationBean getServletRegistrationBean(){
  8.         // 直接获取ServletRegistrationBean对象 并关联自定义的servlet
  9.         ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
  10.         // 设置servlet对应的 UrlMapping
  11.         bean.addUrlMappings("/second");
  12.         return bean;
  13.     }
  14.     /**
  15.      * 获取FilterRegistrationBean 对象
  16.      *    注册过滤器并设置拦截的请求地址
  17.      * @return
  18.      */
  19.     @Bean
  20.     public FilterRegistrationBean getFilterRegistrationBean(){
  21.         FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
  22.         // 配置要拦截的请求
  23.         bean.addUrlPatterns("/second");
  24.         return bean;
  25.     }
  26. }
复制代码
 
3.启动测试

通过App启动类启动程序,访问测试如下:

 
SpringBoot整合Listener


整合方式一

1.创建Listener

   创建一个自界说的Listener,监听ServletContext的初始化和销毁的行为,具体如下:
  1. @WebListener
  2. public class FisrtListener implements ServletContextListener {
  3.     @Override
  4.     public void contextInitialized(ServletContextEvent sce) {
  5.         System.out.println("FirstListener:Servlet容器初始化...");
  6.     }
  7.     @Override
  8.     public void contextDestroyed(ServletContextEvent sce) {
  9.         System.out.println("FirstListener:Servlet容器被销毁了");
  10.     }
  11. }
复制代码
2.创建启动器

启动还是和之前一样,没什么区别。
  1. @SpringBootApplication
  2. //在 springBoot 启动时会扫描@WebServlet,并将该类实例化
  3. @ServletComponentScan()
  4. public class Springboot01ServletApplication {
  5.     public static void main(String[] args) {
  6.         SpringApplication.run(Springboot01ServletApplication.class, args);
  7.     }
  8. }
复制代码
3.启动测试

通过启动类启动程序,观察控制台。

 
整合方式二

1.创建Listener
创建自界说的监听器,不要添加@WebListener注解
  1. package com.edu.listener;
  2. import javax.servlet.ServletContextEvent;
  3. import javax.servlet.ServletContextListener;
  4. public class SecondListener implements ServletContextListener {
  5.     @Override
  6.     public void contextInitialized(ServletContextEvent sce) {
  7.         System.out.println("SecondListener : 初始化了....");
  8.     }
  9.     @Override
  10.     public void contextDestroyed(ServletContextEvent sce) {
  11.         System.out.println("SecondListener : 销毁了....");
  12.     }
  13. }
复制代码
2.创建启动器
创建启动类,同时创建注册Listener的方法,如下
  1. @SpringBootApplication
  2. public class App {
  3.     public static void main(String[] args) {
  4.         SpringApplication.run(App.class,args);
  5.     }
  6.     /**
  7.      * 注册自定义的监听器
  8.      * @return
  9.      */
  10.     @Bean
  11.     public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
  12.         ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());
  13.         return bean;
  14.     }
  15. }
复制代码
3.启动测试
启动程序,观察控制台的输出。

输出效果看到不但第二个Listener触发了,而且前面的Listener也触发了。搞定~

文件上传和下载

上传操纵

表单页面
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Title</title>
  6. </head>
  7. <body>
  8.     <h1>文件上传案例:</h1>
  9.     <form action="/user/upload" method="post" enctype="multipart/form-data">
  10.         <label>账号:</label><input type="text" name="username"><br/>
  11.         <label>照片:</label><input type="file" name="upload"><br>
  12.         <input type="submit" value="提交">
  13.     </form>
  14. </body>
  15. </html>
复制代码
 
控制层处理
添加控制器处理上传的文件信息
  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController  {
  4.     @RequestMapping("/upload")
  5.     public String upload(MultipartFile upload,String username) throws IOException {
  6.         System.out.println("账号:"+username+" "+upload.getOriginalFilename());
  7.         upload.transferTo(new File("c:/tools/",upload.getOriginalFilename()));
  8.         return "success:上传成功";
  9.     }
  10. }
复制代码
设置上传参数
在application.properties中添加配置参数,此处要注意SpringBoot2.x版本的参数和1.x版本的参数设置有区别,必要注意
  1. # SpringBoot 2.0 版本
  2. spring.servlet.multipart.enabled=true
  3. # 设置单个文件上传大小
  4. spring.servlet.multipart.max-file-size=200MB
  5. # 设置一次上传请求的文件的总大小
  6. spring.servlet.multipart.max-request-size=200MB
  7. # SpringBoot 1.5.9 版本
  8. #spring.http.multipart.enabled=true
  9. #spring.http.multipart.max-file-size=10MB
  10. #spring.http.multipart.max-request-size=100MB
复制代码
测试即可
下载操纵

  1. @RequestMapping("/exportExcel")
  2. public void exportExcel(HttpServletRequest request,HttpServletResponse response) throws IOException{
  3.         File file = new File("d://owned.xls");
  4.         //设置响应头和客户端保存文件名
  5.     response.setCharacterEncoding("utf-8");
  6.     response.setContentType("multipart/form-data");
  7.     response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
  8.     try {
  9.         //打开本地文件流
  10.         InputStream inputStream = new FileInputStream(file);
  11.         //激活下载操作
  12.         OutputStream os = response.getOutputStream();
  13.         //循环写入输出流
  14.         byte[] b = new byte[2048];
  15.         int length;
  16.         while ((length = inputStream.read(b)) > 0) {
  17.             os.write(b, 0, length);
  18.         }
  19.         // 这里主要关闭。
  20.         os.close();
  21.         inputStream.close();
  22.     } catch (Exception e){
  23.         
  24.         throw e;
  25.     }
  26. }
复制代码

SpringBoot整合Freemarker



添加依靠
我们必要额外添加freemarker的依靠,如下:
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-freemarker</artifactId>
  4. </dependency>
  5. <dependency>
  6.     <groupId>org.springframework.boot</groupId>
  7.     <artifactId>spring-boot-starter-web</artifactId>
  8. </dependency>
复制代码
 

创建controller
创建一个平凡的控制器,跳转到ftl中。
  1. @Controller
  2. public class UserController {
  3.     /*
  4.      * 处理请求,产生数据
  5.      */
  6.     @RequestMapping("/showUser")
  7.     public String showUser(Model model){
  8.         List<User> list = new ArrayList();
  9.         list.add(new User(1,"张三",20));
  10.         list.add(new User(2,"李四",22));
  11.         list.add(new User(3,"王五",24));
  12.         //需要一个 Model 对象
  13.         model.addAttribute("list", list);
  14.         //跳转视图
  15.         return "user";
  16.     }
  17. }
复制代码
创建ftl文件
注意:springBoot 要求模板形式的视图层技能的文件必须要放到 src/main/resources 目录下必须要一个名称为 templates
 

ftl代码
  1. <html>
  2. <head>
  3.     <title>展示用户数据</title>
  4.     <meta charset="utf-9"></meta>
  5. </head>
  6. <body>
  7. <table border="1" align="center" width="50%">
  8.     <tr>
  9.         <th>ID</th>
  10.         <th>Name</th>
  11.         <th>Age</th>
  12.     </tr>
  13.     <#list list as user >
  14.         <tr>
  15.             <td>${user.userid}</td>
  16.             <td>${user.username}</td>
  17.             <td>${user.userage}</td>
  18.         </tr>
  19.     </#list>
  20. </table>
  21. </body>
  22. </html>
复制代码
 
属性文件中添加后缀
spring.freemarker.suffix=.ftl
 
测试
创建启动类,然后启动访问测试。
  1. @SpringBootApplication
  2. public class Springboot03FreemarkerApplication {
  3.     public static void main(String[] args) {
  4.         SpringApplication.run(Springboot03FreemarkerApplication.class, args);
  5.     }
  6. }
复制代码
 
   
SpringBoot整合Thymeleaf

添加相关的依靠
  1. <!-- 添加父类的依赖 -->
  2. <parent>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-parent</artifactId>
  5.     <version>2.1.4.RELEASE</version>
  6. </parent>
  7. <dependencies>
  8.         <!-- 添加相关的启动器 -->
  9.     <dependency>
  10.         <groupId>org.springframework.boot</groupId>
  11.         <artifactId>spring-boot-starter-web</artifactId>
  12.     </dependency>
  13.     <dependency>
  14.         <groupId>org.springframework.boot</groupId>
  15.         <artifactId>spring-boot-starter-thymeleaf</artifactId>
  16.     </dependency>
  17. </dependencies>
复制代码

  • 创建存放视图的templates目录以及application.properties
    目录位置:src/main/resources/templates
    templates:该目录是安全的。意味着该目录下的内容是不允许外界直接访问的。

 
Thymeleaf基本使用


1.Thymeleaf 特点:
  thymeleaf是一种模板语言,可以动态大概静态显示文本内容,Thymelaef 是通过他特定语法对 html 的标志做渲染。具体语法介绍下篇文章单独介绍
2.编写controller
  1. @Controller
  2. public class DemoController {
  3.     @RequestMapping("/show")
  4.     public String showInfo(Model model){
  5.         model.addAttribute("msg","Thymeleaf入门案例...");
  6.         return "index";
  7.     }
  8. }
复制代码
 
创建视图页面
在我们刚刚创建的templates目录下创建index.html页面,在头部引入
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
 
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Thymeleaf入门案例</title>
  6. </head>
  7. <body>
  8.     <h1>Thymeleaf入门案例:</h1>
  9.         <span th:text="hello"></span>
  10.         <hr>
  11.         <span th:text="${msg}}"></span>
  12. </body>
  13. </html>
复制代码
 
创建启动类
在com.dpb.springboot目录下创建启动类
  1. @SpringBootApplication
  2. public class Start {
  3.     public static void main(String[] args) {
  4.         SpringApplication.run(Start.class,args);
  5.     }
  6. }
复制代码
 
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

知者何南

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表