美文网首页
Spring Boot学习day88:Spring Boot的整

Spring Boot学习day88:Spring Boot的整

作者: 开源oo柒 | 来源:发表于2019-11-21 20:42 被阅读0次

一、Spring Boot简介

1.SpringBoot的介绍:

SpringBoot 设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。 Spring Boot将很多魔法带入了Spring应用程序的开发之中,其中最重要的是以下四个核心。
(1)自动配置:针对很多Spring应用程序常见的应用功能,Spring Boot能自动提供相关配置。
(3)起步依赖:告诉Spring Boot需要什么功能,它就能引入需要的库。
(3)命令行界面:这是Spring Boot的可选特性,借此你只需写代码就能完成完整的应用程序,
无需传统项目构建。
(4)Actuator:让你能够深入运行中的Spring Boot应用程序,一探究竟。
每一个特性都在通过自己的方式简化Spring应用程序的开发。本书会探寻如何将它们发挥到极致,但就目前而言,先简单看看它们都提供了哪些功能吧

  • SpringBoot的原理:


    示例
    示例

2.Spring Boot启动器:

所谓的 springBoot 启动器其实就是一些 jar 包的集合。
(1)spring-boot-starter-web 支持全栈式的 web 开发,包括了 romcat 和 springMVC 等 jar;
(2)spring-boot-starter-jdbc 支持 spring 以 jdbc 方式操作数据库的 jar 包的集合;
(3)spring-boot-starter-redis 支持 redis 键值存储的数据库操作。

3.Spring Boot入门HelloWorld:

  • 创建Maven项目:


    示例
  • 修改POM文件注入SpringBoot启动坐标:
    <!-- 修改jdk版本 -->
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <!-- springboot的启动器 -->
    <dependencies>
        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId>spring-boot-starter-web </artifactId>
        </dependency>
    </dependencies>
  • 编写Controller:
@Controller
public class HelloWorld {
    
    @RequestMapping("hello")
    @ResponseBody
    public Map<String, Object> hello(){
        Map<String , Object> map = new HashMap<String, Object>();
        map.put("test", "Hello World");
        return map;
    }
}
  • 编写SpringBoot启动类:
/**
 * 启动类
 * @author zhang
 *
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
  • 注意:

启动器存放的位置。启动器可以和 controller 位于同一个包下,或者位于 controller 的上一级 包中,但是不能放到 controller 的平级以及子包下。

启动.png

4.

二、整合其它技术

1.整合Servlet:

1.1 方式一:

通过注解扫描完成Servlet 组件的注册。
在哪个类中添加了“@WebServlet(name = " ", urlPatterns = " ") ”这个注解表示这个类就是Servlet。

  • 编写Servlet:
/**
 * spring整合Servlet方式一
 * @author zhang
 *
 */
@WebServlet(name = "FirstServlet",urlPatterns = "/first")
public class FirstServlet extends HttpServlet{
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("FirstServlet!!!");
    }
}
  • 编写启动类:
@SpringBootApplication
@ServletComponentScan //在springBoot启动时扫描@WebServlet
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
示例
1.2方式二:

通过方法完成Servlet 组件的注册。
使用方法可以不用添加@WebServlet 注解声明。

  • 编写Servlet:
/**
 * springboot整合Servlet二
 * @author zhang
 */

public class SecondServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("SecondServlet!!!");
    }
    
}
  • 编写启动类:
@SpringBootApplication
public class App2 {
    public static void main(String[] args) {
        SpringApplication.run(App2.class, args);
    }
    
    @Bean
    public ServletRegistrationBean getServletRegistrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
        bean.addUrlMappings("/second");
        return bean;
    }
}
示例

2.整合Filter:

1.1方式一:

通过注解扫描完成Filter组件的注册。

  • 编写Filter:
/**
 * springboot整合Filter方式一
 * @author zhang
 *
 */
//@WebFilter(filterName="FirstFilter",urlPatterns={"*.do","*.jsp"})
@WebFilter(filterName = "FirstFilter",urlPatterns = "/first")
public class FirstFilter implements Filter{

    @Override
    public void destroy() {
        
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("进入Filter!!!");
        chain.doFilter(request, response);
        System.out.println("离开Filter!!!");
        
    }
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        
    }
}
  • 编写启动类:
@SpringBootApplication
@ServletComponentScan
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
1.2方式二:

通过方法完成Filter组件的注册。

  • 编写Filter:
public class SecondListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("SecondListener-init!!!");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
  • 编写启动类:
@SpringBootApplication
public class App2 {
    public static void main(String[] args) {
        SpringApplication.run(App2.class, args);
    }
    
    @Bean
    public ServletRegistrationBean getServletRegistrationBean() {
        // 通过ServletRegistrationBean完成对servlet的注册
        ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
        bean.addUrlMappings("/second");// 该方法完成的是对urlPattern的配置
        return bean; // 将对象返回
    }
    
    @Bean
    public  FilterRegistrationBean getFilterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
        bean.addUrlPatterns("/second");
        return bean;

    }
}

3.整合Listener:

3.1方式一:
  • 编写Listener:
@WebListener
public class FirstListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("FirstListener-init!!!");
    }
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        
    }
}
  • 编写启动类:
@SpringBootApplication
@ServletComponentScan
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
3.2方式二:
  • 编写Listener:
public class SecondListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("SecondListener-init!!!");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
  • 编写启动类:
/**
 * Listener方式二
 * @author zhang
 *
 */
@SpringBootApplication
public class App3 {

    public static void main(String[] args) {
        SpringApplication.run(App3.class, args);
    }

    @Bean
    public ServletListenerRegistrationBean<SecondListener> getServletListenerR() {
        ServletListenerRegistrationBean<SecondListener> bean = new ServletListenerRegistrationBean<SecondListener>(
                new SecondListener());
        return bean;
    }
}

4.访问静态资源:

4.1方式一:

通过classpath/static的目录下访问;目录名称必须是static;

示例
4.2方式二:

通过ServletContext根目录下;在src/main/webapp,目录名称必须是webapp。

示例

5.Spring Boot实现文件上传:

设置上传文件大小的默认值:
Spring Boot1.5 版本:
设置单个上传文件的大小 spring.http.multipart.maxFileSize=文件大小;
设置一次请求上传文件的总容量 spring.http.multipart.maxRequestSize=文件大小;
Spring Boot版本2.0以上:
设置单个上传文件的大小 spring.servlet.multipart.maxFileSize=文件大小;
设置一次请求上传文件的总容量 spring.servlet.multipart.maxRequestSize=文件大小;

  • HTML页面:
<body>
    <form action="fileUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="filename"/><br>
        <input type="submit" value="提交"/>
    </form>
</body>
  • 编写Controller:
@RestController
public class FileController {
    @RequestMapping("/fileUpload")
    public Map<String, Object> fileUpload(MultipartFile filename) throws Exception {
        System.out.println(filename.getOriginalFilename());
        filename.transferTo(new File("e:/" + filename.getOriginalFilename()));
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("msg", "ok");
        return hashMap;
    }
}
  • 编写启动类:
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
  • 设置上传文件的大小:

需要添加一个 springBoot 的配置文件 application.properties或者application.yml;

spring.http.multipart.maxFileSize=200MB
spring.http.multipart.maxRequestSize=200MB
yml

6.整合JSP技术:

  • 修改POM文件:
    <dependencies>
        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId>spring-boot-starter-web </artifactId>
        </dependency>
        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency> 
        <!-- jasper -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
  • 创建 springBoot 的全局配置文件,application.properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
  • 创建Controller:
@Controller
public class UserController {

    @RequestMapping("/show")
    public String show(Model model) {
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(01, "张三", 18));
        list.add(new User(02, "李四", 20));
        list.add(new User(03, "王五", 23));
        model.addAttribute("list", list);
        return "show";
    }
}
  • 创建JSP:


    示例
<body>
    <table border="1px" align="center" width="600px">
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>年龄</th>
        </tr>
        <c:forEach items="${list }" var="user">
            <tr>
                <td>${user.userid }</td>
                <td>${user.username }</td>
                <td>${user.userage }</td>
            </tr>
        </c:forEach>
    </table>
</body>
  • 创建启动类:
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
示例

7.整合Freemarker:

  • 修改POM文件:
    <dependencies>
        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId>spring-boot-starter-web </artifactId>
        </dependency>
        <!-- freemarker 启动器的坐标 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    </dependencies>
  • 编写视图:

springBoot 要求模板形式的视图层技术的文件必须要放到 src/main/resources 目录下必 须要一个名称为 templates;后缀为.ftl;

示例
<html>
    <head>
        <title>展示数据</title>
        <meta charset="utf-8" />
    </head>

    <body>
        <table border="1px" align="center" width="500px">
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>年龄</th>
            </tr>
            <#list list as user>
                <tr>
                    <td>${user.userid}</td>
                    <td>${user.username}</td>
                    <td>${user.userage}</td>
                </tr>
            </#list>
        </table>
    </body>
</html>
  • 创建Controller:
@Controller
public class UserController {

    @RequestMapping("/show")
    public String show(Model model) {
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(01, "张三", 18));
        list.add(new User(02, "李四", 20));
        list.add(new User(03, "王五", 23));
        model.addAttribute("list", list);
        return "userList";
    }
}
  • 创建启动器:
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
示例

三、Thymelea入门

1.Thymalea存放视图的目录:

src/main/resources/templates templates:该目录是安全的。意味着该目录下的内容是不允许外界直接访问的。
Thymelaef 是通过他特定语法对 html 的标记做渲染。

示例

2.创建简单的Thymeleaf项目:

  • 修改POM文件:
    <dependencies>
        <!-- springBoot 的启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- thymeleaf 的启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
  • 编写Controller:
@Controller
public class ShowController {
    @RequestMapping("/show")
    private String show(Model model) {
        model.addAttribute("msg", "thymeleaf!!!");
        return "show";
    }
}
  • 创建视图:.html
<body>
    <span th:text="hello"></span>
    <span th:text="${msg}"></span>
</body>
  • 编写启动类:
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
示例
2.1异常:
org.xml.sax.SAXParseException: 元素类型 "meta" 必须由匹配的结束标记 "</meta>" 终止。
  • 解决异常方式

(1)将标签正常结束;
(2)更换Thyeleaf.jar和thymeleaf-layout-dialect.jar的版本。

    <properties>
        <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version> 
    </properties>

相关文章

网友评论

      本文标题:Spring Boot学习day88:Spring Boot的整

      本文链接:https://www.haomeiwen.com/subject/ktfxwctx.html