SpringBoot Web development, access to static resources, automatically return json format data, capture global exceptions, use template engine to render Web pages, simple use of FreeMarker, JSP-day02 in SpringBoot

5. SpringBoot Web Development

5.1 Access to static resources

  • When we develop web applications, we need to reference a large number of static resources such as js, css, and pictures.
  • Spring Boot provides static resource directory location by default and needs to be placed under the classpath, and the directory name must comply with the following rules:
    • /static
    • /public
    • /resources
    • /META-INF/resources
  • SpringBoot can also develop War (web) projects in jar type projects
  • Such as accessing static image resources: create static in the src/main/resources/ directory, and place an image file in this location. After starting the program, try to visit http://localhost:8080/images/1.jpg. If the picture can be displayed, the configuration is successful.
    Insert picture description here

5.2 Automatically return json format data

Insert picture description here
Insert picture description here

package com.it.web.controller;

import com.it.model.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName HelloController
 * @Author shuyy
 * @Date 2020/10/25
 **/
@RestController//相当于声明Controller,并提供restful风格
//@EnableAutoConfiguration//自动配置不需要写Spring配置文件
public class UserController {
    
    

    @RequestMapping("user/{id}")//映射路径【restful风格】
    @ResponseBody//响应体
    public User userInfo(@PathVariable Integer id){
    
    

        User user = new User("shu","123");
        user.setId(id);
        return user;
    }

    @RequestMapping("login")//映射路径
    @ResponseBody//响应体-自动返回json格式的字符串
    public Map<String,Object> login(String username,String password){
    
    
        Map<String,Object> map = new HashMap<String,Object>();
        //模拟从数据库查数据
        if ("shu".equals(username) && "123".equals(password)){
    
    
            map.put("success",1);
            map.put("errMsg","");
        }else {
    
    
            map.put("success",0);
            map.put("errMsg","用户名或密码不正确");
        }
        return map;
    }

    /*public static void main(String[] args) {
        //启动程序(这里只是测试一下,以后一般不这样启动)
        SpringApplication.run(HelloController.class,args);
    }*/
}

5.3 Catch global exceptions

  • @ExceptionHandler: means to intercept exceptions
  • @ControllerAdvice: An auxiliary class of controller, the most commonly used is the aspect class for global exception handling
  • @ResponseBody: json conversion

Insert picture description here

package com.it.web.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/*
 * @Author ShuYY
 * @Description 用于捕获全局异常
 * @Date 2020/10/25
 **/
@ControllerAdvice//切面
public class GlobalExceptionHandler {
    
    

    @ExceptionHandler(RuntimeException.class)//捕获运行时异常
    @ResponseBody//返回json
    public Map<String,Object> exceptionHandler(){
    
    //异常处理方法,自定义
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("errorCode", "101");
        map.put("errorMsg", "系统错误!");
        return map;
    }

}

  • Configure annotation scan package
    Insert picture description here
  • effect
    Insert picture description here
  • Errors not caught before
    Insert picture description here

5.4 Rendering web pages

Template engine

  • In the dynamic HTML implementation, Spring Boot is still perfectly competent, and provides a variety of template engine default configuration support, so under the recommended template engine, we can quickly get started developing dynamic websites.

  • Spring Boot provides the following template engines with default configuration:

    • Thymeleaf
    • FreeMarker
    • Velocity
    • Groovy
    • Mustache
  • Spring Boot recommends using these template engines to avoid using JSP. If you must use JSP, you will not be able to realize the various features of Spring Boot . For details, see the following text: Support JSP configuration

  • When you use any of the above template engines, their default template configuration path is: src/main/resources/templates . Of course, you can also modify this path, and how to modify it can be queried and modified in the configuration properties of the subsequent template engines.

5.5 Using FreeMarker in SpringBoot

Step 1: Introduce freeMarker's dependency package

Insert picture description here

<!--引入freeMarker的依赖包-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>

Step 2: Write a controller and return some data

  1. Write a Student entity, provide parameterless, parameterized structure, get/set, toStringInsert picture description here
  2. Write a StudentController
    Insert picture description here
package com.it.web.controller;

import com.it.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName StudentController
 * @Author shuyy
 * @Date 2020/10/25
 **/
/*
    @RestController 一般用于写API,给移动客户端提供数据,一般返回的是json格式的数据
    @Controller 一般写后端页面时使用
*/
@Controller//这里访问freeMarker模板,不使用@RestController
@RequestMapping("stu")
public class StudentController {
    
    

    @RequestMapping("list")
    public String list(Model model){
    
    
        //在Spring提供的model接口中存数据,在页面中取出
        model.addAttribute("username","shuyy");
        model.addAttribute("age",18);
        List<Student> stuList = new ArrayList<>();
        stuList.add(new Student(1,"shu1","男"));
        stuList.add(new Student(2,"shu2","男"));
        stuList.add(new Student(3,"shu3","男"));
        model.addAttribute("stuList",stuList);
        return "stu/list";
    }
}

Step 3: Create .ftl template file

  • Create a templates folder in src/main/resources/, then create a stu folder below, create a list.html, and rename it directly to list.ftl
    Insert picture description here
    Insert picture description here
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
欢迎${username}登录<br>
<#if (age < 18)>未成年人请在家长的陪同下访问
<#elseif (age >= 18 && sex == "男")>欢迎帅哥访问
<#else>欢迎美女访问
</#if>
<br>
<table border="1">
    <tr>
        <td>ID</td>
        <td>姓名</td>
        <td>性别</td>
    </tr>
    <#list stuList as stu>
        <tr>
            <td>${stu.id}</td>
            <td>${stu.username}</td>
            <td>${stu.sex}</td>
        </tr>
    </#list>
</table>
</body>
</html>
  • Make a slight modification and output in reverse order according to id (?sort_by("id")?reverse)
    Insert picture description here

Insert picture description here

5.6 Use jsp in SpringBoot

The first step: create a Mavenweb project

Insert picture description here
Insert picture description here
Insert picture description here

Step 2: Introduce dependencies in pom

Insert picture description here

<parent>
    <!--SpringBoot的父依赖-->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
  </parent>

  <dependencies>
    <!--SpringBoot配置web依赖的核心组件-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <!--jsp解析-->
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

Step 3: Write application.properties under src/main/resources

  • The application.properties file name is fixed and the location is fixed
    Insert picture description here
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

server.port=8888
server.context-path=/test

Step 4: Write a simple controller

Insert picture description here

  • Just write something
    Insert picture description here
  • Effect (the port number and project name are the contents we modified)
    Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43414199/article/details/109276143