SpringBoot初级知识总结,太难了,未完待续.......

idea如何打包发布springboot

1.1.环境准备
window系统,jdk8环境,springboot项目,maven3.5.4环境

1.2.进行打包发布

打开idea编辑器,打开一个写好的demo项目

在这里插入图片描述在这里插入图片描述
然后打开idea编辑器下方的terminal窗口,当你打开这个窗口的时候,所在的位置就是目录的根位置了
在这里插入图片描述在这里插入图片描述
输入命令 mvn clean install -Dmaven.test.skip,这条命令就是用maven打成jar包的方式了,然后回车键。
在这里插入图片描述在这里插入图片描述
当看到BUILD SUCCESS的时候,就说明打包成功,在项目的target目录下就会出现一个jar包,默认的jar包名就是artifactId+version在这里插入图片描述在这里插入图片描述
此时再进入到target目录,输入java -jar SpringBoot-Mybatis-0.0.1-SNAPSHOT.jar命令就可以运行jar包了在这里插入图片描述在这里插入图片描述
当你看到Started DemoApplication in …的时候说明启动成功,就能在本地访问了在这里插入图片描述在这里插入图片描述

结论:这就是SpringBoot项目的在Windows环境发布,linux环境也是一样的,同样要安装jdk和maven环境。这也是springboot的神奇之处,不需要发布到Tomcat下,因为SpringBoot内嵌了web服务器包括Tomcat

特点简介

  • 由于传统的ssm、ssh等框架繁琐的配置文件,springboot的出现就是为了简化配置文件
  • 内嵌Web服务器包括Tomcat,只需要打成jar包就可以运行项目
  • SpringBoot基于全注解式的开发

SpringBoot整合Servlet

3.1.方式一

步骤:

  • 写一个类MyFirstServlet继承HttpServlet,并重写doGet方法
  • 在类的上面用@WebServlet标识Servlet并指明name和urlPatterns
  • 在标识有@SpringBootApplication的主类上加上
    @ServletComponentScan

FirstServlet.java

 1package com.example.servlet.myservlet;
2
3import javax.servlet.http.HttpServlet;
4import java.io.IOException;
5import javax.servlet.ServletException;
6import javax.servlet.annotation.WebServlet;
7import javax.servlet.http.HttpServletRequest;
8import javax.servlet.http.HttpServletResponse;
9
10/**
11 *SpringBoot整合Servlet方式一
12 *@WebServlet(name="MyFirstServlet",urlPatterns="/myFirst")相当于如下:
13 *
14 *<servlet>
15 * <servlet-name>MyFirstServlet</servlet-name>
16 * <servlet-class>ah.szxy.servlet.FirstServlet</servlet-class>
17 *</servlet>
18 *<servlet-mapping>
19 * <servlet-name>MyFirstServlet</servlet-name>
20 * <url-pattern>/first</url-pattern>
21 *</servlet-mapping>
22 *
23 */
24
25@WebServlet(name="MyFirstServlet",urlPatterns="/myFirst")
26public class FirstServlet extends HttpServlet {
27
28    @Override
29    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
30        System.out.println("MyFirstServlet init............");
31    }
32}

ServletApplication.java

 1package com.example.servlet;
2
3import org.springframework.boot.SpringApplication;
4import org.springframework.boot.autoconfigure.SpringBootApplication;
5import org.springframework.boot.web.servlet.ServletComponentScan;
6
7@SpringBootApplication
8@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
9public class ServletApplication {
10
11   public static void main(String[] args) {
12      SpringApplication.run(ServletApplication.class, args);
13   }
14
15}

然后启动项目

在这里插入图片描述在这里插入图片描述

最后在浏览器输入localhost:8080/myFirstServlet,页面显示空白,在控制台打印MyFirstServlet init…………

在这里插入图片描述在这里插入图片描述

3.2.方式二
步骤:
创建一个类SecondServlet继承HttpServlet,并重写doGet方法。
在@SpringBootApplication标识的主类中加@Bean的一个方法。
SecondServlet.java

 1package com.example.servlet.myservlet;
2
3import javax.servlet.ServletException;
4import javax.servlet.http.HttpServlet;
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7import java.io.IOException;
8
9/**
10 * 整合Servlet的第二种方式
11 */
12public class SecondServlet extends HttpServlet {
13
14    @Override
15    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
16        System.out.println("MySecondServlet init..........");
17    }
18}

ServletApplication.java

 1package com.example.servlet;
2
3import com.example.servlet.myservlet.SecondServlet;
4import org.springframework.boot.SpringApplication;
5import org.springframework.boot.autoconfigure.SpringBootApplication;
6import org.springframework.boot.web.servlet.ServletComponentScan;
7import org.springframework.boot.web.servlet.ServletRegistrationBean;
8import org.springframework.context.annotation.Bean;
9
10@SpringBootApplication
11//@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
12public class ServletApplication {
13
14   public static void main(String[] args) {
15      SpringApplication.run(ServletApplication.class, args);
16   }
17
18
19  /**
20 * 整合Servlet的第二种方式,创建ServletRegistrationBean并添加路径
21 * @return
22 */
23@Bean
24public ServletRegistrationBean getServletRegistrationBean(){
25   ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
26   bean.addUrlMappings("/mySecond");
27   return bean;
28}

然后启动项目,在浏览器中访问localhost:8080/mySecondServlet,页面也是空白,在控制台就会打印MySecondServlet init……….

在这里插入图片描述在这里插入图片描述

项目,结构如图所示

在这里插入图片描述在这里插入图片描述

结论:
上面的两种方式推荐使用第一种基于注解的整合
虽然现在几乎用不到servlet了,但是学习SpringBoot整合servlet有助于学习的深入了解,更好的理解框架

4.SpringBoot整合Filter
4.1.方式一
步骤:
创建一个MyFirstFilter类实现Filter接口,并在类上面标注@WebFilter
在@SpringBootApplication的主类上加上@ServletComponentScan注解
MyFirstFilter.java

 1package com.example.servlet.myfilter;
2
3import javax.servlet.*;
4import javax.servlet.annotation.WebFilter;
5import java.io.IOException;
6
7/**
8 * 基于@WebFilter注解整合Filter方式一
9 */
10@WebFilter(filterName = "MyFirstFilter",urlPatterns = "/myFirst")
11public class MyFirstFilter implements Filter {
12    @Override
13    public void init(FilterConfig filterConfig) throws ServletException {
14
15    }
16
17    @Override
18    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
19        System.out.println("进入Filter中了.....");
20        arg2.doFilter(arg0,arg1);
21        System.out.println("离开Filter了.......");
22    }
23
24    @Override
25    public void destroy() {
26
27    }
28}

ServletApplication.java

 1package com.example.servlet;
2
3import com.example.servlet.myservlet.SecondServlet;
4import org.springframework.boot.SpringApplication;
5import org.springframework.boot.autoconfigure.SpringBootApplication;
6import org.springframework.boot.web.servlet.ServletComponentScan;
7import org.springframework.boot.web.servlet.ServletRegistrationBean;
8import org.springframework.context.annotation.Bean;
9
10@SpringBootApplication
11@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
12public class ServletApplication {
13
14   public static void main(String[] args) {
15      SpringApplication.run(ServletApplication.class, args);
16   }
17
18   /**
19    * 整合Servlet的第二种方式,创建ServletRegistrationBean并添加路径
20    * @return
21    */
22   @Bean
23   public ServletRegistrationBean getServletRegistrationBean(){
24      ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
25      bean.addUrlMappings("/mySecond");
26      return bean;
27   }
28}

4.2.方式二
步骤:
创建一个类MySecondFilter实现Filter接口,重写方法。
在@SpringBootApplication标识的主类中加@Bean的一个方法,将MySecondFilter对象注入容器中。

MySecondFilter.java

 1package com.example.servlet.myfilter;
2
3import javax.servlet.*;
4import java.io.IOException;
5
6/**
7 * 整合Filter的第二种方式
8 */
9public class MySecondFilter implements Filter {
10    @Override
11    public void init(FilterConfig filterConfig) throws ServletException {
12
13    }
14
15    @Override
16    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
17        System.out.println("进入MySecondFilter了......");
18        arg2.doFilter(arg0, arg1);
19        System.out.println("离开MySecondFilter了......");
20    }
21
22    @Override
23    public void destroy() {
24
25    }
26}

ServletApplication.java

 1package com.example.servlet;
2
3import com.example.servlet.myfilter.MySecondFilter;
4import com.example.servlet.myservlet.SecondServlet;
5import org.springframework.boot.SpringApplication;
6import org.springframework.boot.autoconfigure.SpringBootApplication;
7import org.springframework.boot.web.servlet.FilterRegistrationBean;
8import org.springframework.boot.web.servlet.ServletComponentScan;
9import org.springframework.boot.web.servlet.ServletRegistrationBean;
10import org.springframework.context.annotation.Bean;
11
12@SpringBootApplication
13//@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
14public class ServletApplication {
15
16   public static void main(String[] args) {
17      SpringApplication.run(ServletApplication.class, args);
18   }
19
20   /**
21    * 整合Filter的第二种方式
22    * 注册Filter
23    */
24   @Bean
25   public FilterRegistrationBean getFilterRegistrationBean() {
26      FilterRegistrationBean bean = new FilterRegistrationBean(new MySecondFilter());
27      // bean.addUrlPatterns(new String[]{"*.do","*.jsp"});//拦截多个时
28      bean.addUrlPatterns("/mySecond");
29      return bean;
30   }
31}

然后在浏览器访问localhost:8080/mySecond,就可以看到控制台打印如下

在这里插入图片描述在这里插入图片描述

5.SpringBoot整合Listener
5.1.方式一
步骤:
创建一个类MyFirstListener实现ServletContextListener接口,重写方法
在该类上加上@WebListener注解

 1package com.example.servlet.mylistener;
2
3import javax.servlet.ServletContextEvent;
4import javax.servlet.ServletContextListener;
5import javax.servlet.annotation.WebListener;
6
7/**
8 * springBoot 整合Listener第一种方式
9 * 创建一个Servlet上下文的监听器
10 * @WebListener 自动注册,相当于在web.xml中添加如下代码
11 *
12 *<listener>
13 * <listener-class>ah.szxy.listener.FirstListener</listener-class>
14 *</listener>
15 */
16@WebListener
17public class MyFirstListener implements ServletContextListener {
18
19    @Override
20    public void contextDestroyed(ServletContextEvent arg0) {
21        // TODO Auto-generated method stub
22        System.out.println("MyFirstListener执行销毁了。。。");
23    }
24
25    @Override
26    public void contextInitialized(ServletContextEvent arg0) {
27        // TODO Auto-generated method stub
28        System.out.println("MyFirstListener执行初始化了。。。");
29    }
30}

执行项目会打印如下,因为用了@ServletComponentScan注解,在项目启动的时候就会扫描包中是否含有servlet,若有就初始化。由于FirstServlet是基于注解初始化的,所以在项目启动的时候,就会执行初始化servlet,被Listener监听到

在这里插入图片描述在这里插入图片描述

5.1.方式二
步骤:
创建一个类MySecondListener实现ServletContextListener接口,重写方法
在@SpringBootApplication标识的主类中加@Bean的一个方法,将MySecondListener对象注入容器中。

 1package com.example.servlet.mylistener;
2
3import javax.servlet.ServletContextEvent;
4import javax.servlet.ServletContextListener;
5
6/**
7 * 整合Listener的第二种方式
8 */
9public class MySecondListener implements ServletContextListener {
10
11    @Override
12    public void contextDestroyed(ServletContextEvent arg0) {
13        // TODO Auto-generated method stub
14        System.out.println("MySecondListener执行销毁了。。。");
15    }
16
17    @Override
18    public void contextInitialized(ServletContextEvent arg0) {
19        // TODO Auto-generated method stub
20        System.out.println("MySecondListener执行初始化了。。。");
21    }
22
23}
 1package com.example.servlet;
2
3import com.example.servlet.myfilter.MySecondFilter;
4import com.example.servlet.mylistener.MySecondListener;
5import com.example.servlet.myservlet.SecondServlet;
6import org.springframework.boot.SpringApplication;
7import org.springframework.boot.autoconfigure.SpringBootApplication;
8import org.springframework.boot.web.servlet.FilterRegistrationBean;
9import org.springframework.boot.web.servlet.ServletComponentScan;
10import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
11import org.springframework.boot.web.servlet.ServletRegistrationBean;
12import org.springframework.context.annotation.Bean;
13
14@SpringBootApplication
15@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
16
17public class ServletApplication {
18
19   public static void main(String[] args) {
20      SpringApplication.run(ServletApplication.class, args);
21   }
22
23   /**
24    * 注册listener
25    */
26   @Bean
27   public ServletListenerRegistrationBean<MySecondListener> getServletListenerRegistrationBean() {
28      ServletListenerRegistrationBean<MySecondListener> bean = new ServletListenerRegistrationBean<MySecondListener>(
29            new MySecondListener());
30      return bean;
31   }
32
33}

执行项目,在控制台可以看到输出如下,两个Servlet监听器都执行了

在这里插入图片描述在这里插入图片描述

总的项目目录包结构如下:

在这里插入图片描述在这里插入图片描述
6.SpringBoot整合静态资源
6.1.在resource/static路径下
在这里插入图片描述在这里插入图片描述
然后启动项目,在浏览器访问localhost:8080/images/1.jpg
在这里插入图片描述在这里插入图片描述
6.2.在webapp目录路径下
6.2.1.idea中为SpringBoot项目添加web
因为SpringBoot的初始化后是没有webapp目录的,需要在idea中手动加入,但不是直接创建,而是配置出来的,下面是SpringBoot项目配置webapp的教程

6.2.2.选中项目然后是ctrl+alt+shift+s,就会弹出如下页面

在这里插入图片描述在这里插入图片描述

6.2.3.选中Modules,然后点击+号,如下

在这里插入图片描述在这里插入图片描述
配置的目录的路径分别为:
E:\liduchang\servlet\src\main\webapp\WEB-INF\web.xml
E:\liduchang\servlet\src\main\webapp

6.2.4出现如下界面,点击铅笔进行编辑web.xml的路径,然后双击第二处同理编辑webapp的路径

在这里插入图片描述在这里插入图片描述
6.2.5最后配置出来的目录结构,如下图所示
在这里插入图片描述在这里插入图片描述

6.2.6然后再webapp先新建一个images文件夹,复制一张图片到images文件夹下,名为2.jpg,并再webapp下新建一个index.html内容如下

 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><hr>
9<img alt="" src="images/2.jpg">
10</body>
11</html>

6.2.7启动项目,然后再浏览器访问localhost:8080,出现如图所示,配置成功

在这里插入图片描述在这里插入图片描述

7.SpringBoot文件上传
7.1.文件上传
项目结构图

在这里插入图片描述在这里插入图片描述

  • 上传到本地磁盘,名字为原文件名
  • 上传到本地磁盘,名字为随机名
  • 上传到项目webapp文件夹下的images文件夹下

upload.html(文件上传主页)

 1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <title>Title</title>
6</head>
7<body>
8<!--
9    表单提交的方式为   :  post
10    enctype的值为 : multipart/form-data
11    file类型的输入框的name属性要和 MultipartFile 的形参一样 ,这样才能进行文件的上传
12-->
13<h1>文件上传到本地e盘</h1><hr>
14<form action="/uploadToPC" method="post" enctype="multipart/form-data">
15    <input type="file" name="file" ><br>
16    <input type="submit" value="点击上传">
17</form>
18
19<h1>文件上传到e盘名字随机</h1><hr>
20<form action="/fileUploadToPCWithNameRandom" method="post" enctype="multipart/form-data">
21    <input type="file" name="file" ><br>
22    <input type="submit" value="点击上传">
23</form>
24
25<h1>文件上传到本项目</h1><hr>
26<form action="/uploadToProject" method="post" enctype="multipart/form-data">
27    <input type="file" name="file" ><br>
28    <input type="submit" value="点击上传">
29</form>
30
31</body>
32
33</html>

FileUploadController.java(文件上传Controller)

 1package com.example.servlet.controller;
2
3import com.example.servlet.util.FileUtils;
4import org.springframework.web.bind.annotation.RequestMapping;
5import org.springframework.web.bind.annotation.RestController;
6import org.springframework.web.multipart.MultipartFile;
7
8import javax.servlet.http.HttpSession;
9import java.io.File;
10import java.io.IOException;
11import java.util.HashMap;
12import java.util.Map;
13
14/**
15 * 文件上传Controller
16 */
17@RestController
18public class FileUploadController {
19
20    /**
21     * 测试文件上传到本地e磁盘
22     * @return
23     */
24    @RequestMapping("/uploadToPC")
25    public Map<String,Object> fileUploadToPC(MultipartFile file) throws IOException {
26        // 获取文件名 df8306e403c49fdf701230317dc99d9.jpg
27        System.out.println(file.getOriginalFilename());
28        // 将上传的文件放在e盘下
29        file.transferTo(new File("e:/"+file.getOriginalFilename()));
30        Map<String, Object> map= new HashMap<>();
31        map.put("msg", "上传文件成功");
32        return map;
33    }
34
35    @RequestMapping("/fileUploadToPCWithNameRandom")
36    public Map<String, Object> fileUploadToPCWithNameRandom(MultipartFile file) throws IOException {
37        String name = file.getOriginalFilename();
38        String prefix = FileUtils.getRandomName();
39        String suffix = name.substring(name.lastIndexOf("."));
40        name = prefix+suffix;
41        file.transferTo(new File("e:/"+name));
42        Map<String, Object> map = new HashMap<String, Object>();
43        map.put("msg", "ok");
44        return map;
45    }
46
47    /**
48     * 上传文件到项目的webapp下的images文件夹下
49     * 不过一般文件不会上传到项目下,一般上传到本
50     * 服务器的其它磁盘上,或者上传到专门的服务器
51     * 上,所以这个方法只要了解就好
52     * @param file
53     * @return
54     */
55    @RequestMapping("/uploadToProject")
56    public String uploadToProject(MultipartFile file, HttpSession session){
57        // 通过session获取绝对路径,方法内部加上/WEB-INF/images,
58        // 表示在项目的images目录下,需要创建该文件夹并进行静态资源放行
59        String path= session.getServletContext().getRealPath("/images");
60        System.err.println(path);
61        String fileName= file.getOriginalFilename();
62        File f= new File(path, fileName);
63        try {
64            file.transferTo(f);
65        } catch (IOException e) {
66            e.printStackTrace();
67        }
68        return "ok";
69    }
70}

FileUtils.java(文件随机命名工具类)

 1package com.example.servlet.util;
2
3import java.util.Random;
4import java.util.UUID;
5
6/**
7 * 文件名随机生成工具类
8 * @version 1.0
9 */
10public class FileUtils {
11
12    /**
13     * 图片名生成
14     */
15    public static String getRandomName() {
16        //取当前时间的长整形毫秒数
17        long millis = System.currentTimeMillis();
18        Random random = new Random();
19        //获取0-1000不包含1000,的整形
20        int end3 = random.nextInt(1000);
21        //如果不足三位前面补0
22        String str = millis + String.format("%03d", end3);
23        return str;
24    }
25
26    /**
27     * 商品id生成
28     */
29    public static long getRandomId() {
30        //取当前时间的长整形值包含毫秒
31        long millis = System.currentTimeMillis();
32        Random random = new Random();
33        //随机获取0-99不包含99,之间的整形
34        int end2 = random.nextInt(99);
35        //如果不足两位前面补0
36        String str = millis + String.format("%02d", end2);
37        long id = new Long(str);
38        return id;
39    }
40
41}

在配置文件配置文件的上传的配置信息

1application.properties
2#设置单个文件上传大小
3spring.http.multipart.maxFileSize=200MB
4#设置一次请求上传文件的总容量
5spring.http.multipart.maxRequestSize=200MB

猜你喜欢

转载自www.cnblogs.com/liduchang/p/12071399.html