SpringMVC framework (all basics)

Table of contents

What is MVC

Overview of Spring MVC

Common development methods of SpringMVC

SpringMVC execution process

Introduction to SpringMVC Core Components

Quickly build Spring MVC programs

SpringMVC parameter binding

SpringMVC jump method

SpringMVC handles json requests and responses

SpringMVC static resource processing

SpringMVC operates session and cookie

SpringMVC interceptor

SpringMVC file upload

SpringMVC global exception unified processing

SSM framework integration

1. Introduce pom dependencies

2. Set the configuration file

3. Project directory structure


What is MVC

The MVC design pattern generally refers to the MVC framework, M (Model) refers to the data model layer, business model layer, V (View) refers to the view layer, and C (Controller) refers to the control layer. The purpose of using MVC is to separate the implementation codes of M and V, so that the same program can have different expressions.

MVC is a kind of architectural pattern, the so-called architecture is how to design the structure of a program. MVC divides the program structure into three layers, and each layer provides an interface for the upper layer to call, which can not only maintain the connection between the three layers, but also maintain relative independence.

This form of code organization that separates business logic, data, and interfaces reduces the coupling between modules and is conducive to future maintenance and expansion.

Overview of Spring MVC

springmvc is an mvc framework derived from spring Framwork. It mainly solves the problem of the controller (Controller) in the original mvc architecture. Common controllers include servlet, struts2, etc. The core function of the controller is to call the corresponding controller according to the user's request. Business functions, and then control the running process of the program according to the results of business processing.

Problems with servlet implementation controllers:

1. When receiving client request parameters, there is code redundancy

2. Can only receive data of string type, other data types need manual conversion

3. Unable to receive parameters of object type

4. There is coupling in calling business objects (new)

5. There is coupling in the process jump (path coupling, view coupling)

Common development methods of SpringMVC

1. Traditional development methods

Realize data transfer through scope (request, session)

View rendering through view technology (jsp thymleaf freeMarker)

2. Front-end and back-end separate development methods

Multiple new access methods (get, post, put, delete)

Restful style access

SpringMVC execution process

The Spring MVC framework is highly configurable and includes multiple view technologies such as JSP, FreeMarke, and POI. The Spring MVC framework does not care about the view technology used, nor does it force developers to use only JSP.

The Spring MVC execution flow is shown in the figure:

 

The execution flow of SpringMVC is as follows:

  1. The user clicks on a request path to initiate an HTTP request request, which will be submitted to DispatcherServlet (front controller);

  2. DispatcherServlet requests one or more HandlerMapping (processor mapper), and returns an execution chain (HandlerExecutionChain).

  3. DispatcherServlet sends the Handler information returned by the execution chain to HandlerAdapter (processor adapter);

  4. HandlerAdapter finds and executes the corresponding Handler (often called Controller) according to the Handler information;

  5. After the Handler is executed, it will return a ModelAndView object to the HandlerAdapter (the underlying object of Spring MVC, including the Model data model and View view information);

  6. After the HandlerAdapter receives the ModelAndView object, it returns it to the DispatcherServlet;

  7. After DispatcherServlet receives the ModelAndView object, it will request ViewResolver (view resolver) to resolve the view;

  8. ViewResolver matches the corresponding view result according to View information, and returns it to DispatcherServlet;

  9. After receiving the specific View view, DispatcherServlet renders the view, fills the model data in the Model into the request field in the View view, and generates the final View (view);

  10. The view is responsible for displaying the results to the browser (client)

Introduction to SpringMVC Core Components

The components involved in Spring MVC are DispatcherServlet (front controller), HandlerMapping (processor mapper), HandlerAdapter (processor adapter), Handler (processor), ViewResolver (view resolver) and View (view). The functions of each component are described below.

1)DispatcherServlet

DispatcherServlet is the front controller. As can be seen from Figure 1, all requests of Spring MVC must be uniformly distributed through DispatcherServlet. DispatcherServlet is equivalent to a forwarder or a central processor, which controls the execution of the entire process and uniformly schedules each component to reduce the coupling between components and facilitate the expansion between components.

2) Handler Mapping

HandlerMapping is a handler mapper, its function is to find matching handler (Handler) information through annotation or XML configuration according to the URL path of the request.

3)HandlerAdapter

HandlerAdapter is a processor adapter, whose function is to execute the relevant processor (Handler) according to specific rules according to the processor (Handler) information found by the mapper.

4)Handler

Handler is a processor, which is consistent with the role played by Java Servlet. Its function is to execute related request processing logic, return corresponding data and view information, and encapsulate it into ModelAndView object.

5)View Resolver

View Resolver is a view resolver, its role is to perform parsing operations, and resolve the logical view name into a real view View through the View information in the ModelAndView object (such as returning a real JSP page through a JSP path)

6)View

View is a view, which itself is an interface, and the implementation class supports different View types (JSP, FreeMarker, Excel, etc.).

Among the above components, the processor (Handler, often called Controller) and the view (View) need to be developed by developers. In layman's terms, it is necessary to develop the specific code logic for processing the request, and finally display the interface to the user

Quickly build Spring MVC programs

The construction steps are as follows:

  1. Create a web application and import the JAR package

    spring-webmvc

  2. Spring MVC configuration: configure Servlet in web.xml, create Spring MVC configuration file

 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:springmvc-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

springmvc configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
    <!--Annotation implements mvc-->
    <!-- Automatically scan packages to implement IOC that supports annotations -->
    <context:component-scan base-package="cn.kgc.spring" /> 
    <!-- Support mvc annotation-driven registration processor mapper registration processor adapter parameter type conversion page jump response processing --> 
    <mvc :annotation-driven /> 
    <!-- view resolver --> 
    <bean 
        class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
        id="internalResourceViewResolver"> 
        <!-- prefix --> 
        <property name ="prefix" value="/view/" /> 
        <!-- suffix--> 
        <property name="suffix" value=".jsp" /> 
    </bean> 
</beans>

Create a Controller (the controller that handles the request)

@Controller
@RequestMapping("/Hello")
public class HelloWorld {
    @RequestMapping("/Say.do")
    public String SayHi(Model model) {
        return "index";
    }
}

Create View (use JSP as view)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    hello springmvc
</body>
</html>

Deploy and run

Detailed explanation of @RequestMapping

1. A method matches multiple paths

@RequestMapping(value={"hello1.do","hello2.do"}) 
    public String test01(){ 
​System.out.println
        ("hello"); 
​//
        The jump path uses forwarding by default and will be parsed through the view return 
        "index"; 
    }

2. Specify the request method received by the method

@RequestMapping(value = "hello1.do",method = RequestMethod.GET) 
    public String test01(){ 
​System.out.println
        ("hello GET"); 
​//
        The jump path uses forwarding by default and passes through the view parser 
        return "index"; 
    }

 

@RequestMapping(value = "hello1.do",method = RequestMethod.POST) public String test02(){ ​ System.out.println("hello POST"); ​ //The jump path defaults to forwarding and will go through the view resolver return "index"; }

 

3. One method specifies multiple types of requests

@RequestMapping(value = "hello1.do", method = {RequestMethod.GET, RequestMethod.POST}) 
    public String test01(){ 
​System.out.println
        ("hello GET OR POST"); 
​//
        jump path By default, forwarding will go through the view resolver 
        return "index"; 
    }

 

 

 

SpringMVC parameter binding

Pass parameters from view to controller

1. Basic data type binding

The name of the formal parameter is consistent with the name of the passed parameter. All parameters need to be passed, otherwise a 500 error will be reported. In order to solve the error of not passing the parameter, you can set the default value for the basic type of parameter

/** 
     * Set the default value of the basic parameter type @RequestParam(defaultValue = "xx") 
     * If the parameter is passed through the url, the passed parameter is the final parameter 
     * @param age 
     * @param score 
     */ 
    @RequestMapping(" /login2") 
    public void login2(@RequestParam(defaultValue = "20") int age , @RequestParam(defaultValue = "24.7") double score){ 
        System.out.println(age); 
        System.out.println(score) ; 
    }

Set the alias of the parameter

 public void login3(@RequestParam(defaultValue = "20" ,name = "Age") int age , double score)
 {
        System.out.println(age);
        System.out.println(score);
 }

2. Transfer of packaging data types

Using the wrapper type can solve the problem that the basic type does not pass a value and a 500 error occurs, but it is still necessary to keep the parameter name and the formal parameter consistent.

 @RequestMapping("/login4")
    public void login3(Integer age , Double score){
        System.out.println(age);
        System.out.println(score);
    }

3. Binding of string type data

Just refer to the packaging class

4. Array type

 public void login3(String[] ids){
        for (int i = 0; i < ids.length; i++) {
            System.out.println(ids[i]);
        }
  }

5. javaBean type

The field of the parameter name should be consistent with the property in the Javabean

 public void login3(User user){
        System.out.println(user);
    }
url:http://localhost:8080/user/login6?age=12&username=lisi&height=1.7

Return data to the view layer

@RequestMapping(path = "/res1")
    public ModelAndView test01(){

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");
        modelAndView.addObject("msg", "ModelAndView");
        return modelAndView;
    }

    @RequestMapping(path = "/res2")
    public String test02(Model model){
        model.addAttribute("msg", "model");
        return "hello";
    }

    @RequestMapping(path = "/res3")
    public String test03(ModelMap map){
        map.addAttribute("msg", "ModelMap");
        return "hello";
    }

SpringMVC jump method

By default, Spring MVC displays page information in the form of internal forwarding of the server, and also supports redirection pages

Redirect (302 status code to browser)

@Controller
public class HelloController3 {

    @RequestMapping("/r1")
    public void test01(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("redirect.jsp");
    }

    @RequestMapping("/r2")
    public String test02(){
        return  "redirect:redirect.jsp";
    }

    @RequestMapping("/f1")
    public void test03(HttpServletRequest request,HttpServletResponse response) throws 	ServletException, IOException {
        request.getRequestDispatcher("redirect.jsp").forward(request, response);
    }

    @RequestMapping("/f2")
    public String test04(){
        return  "forward:redirect.jsp";
    }

    @RequestMapping("/f3")
    public String test05(){
        return  "redirect";
    }

SpringMVC handles json requests and responses

Respond to data in json format

public class JsonController {

    @GetMapping("/login/{username}/{password}")
    public void login(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        //响应json格式的字符串
        res.setContentType("application/json;charset=utf-8");
        JsonResult result = JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
        res.getWriter().write(result.toJSONString());
    }

    @GetMapping("/login2/{username}/{password}")
    @ResponseBody
    public Object login2(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        return JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
    }

    @RequestMapping("/login3")
    @ResponseBody
    public Object login3(User user) {
        System.out.println(user);
        return user;
    }

   

The request data type is JSON

/**
     * 接收json格式的参数
     * @param user
     * @return
     */
    @RequestMapping("/login4")
    @ResponseBody
    public Object login4(@RequestBody User user) {
        System.out.println(user);
        return user;
    }
}


前台ajax请求
<script type="text/javascript">
    $(function () {
        $("#jsbutton").click(function () {
            $.ajax({
                    url:'/login3',
                    type:'post',
                    data:{
                        username:"lisi",
                        age:20,
                        height:170,
                        birth:new Date()
                    },
                    dataType:'json',
                    success:function (result) {
                        console.log(result);
                    },
                    error:function () {
                         console.log("请求失败!")
                     }
            })
        })


        $("#jsbutton2").click(function () {
            var user = {
                username:"lisi",
                age:20,
                height:170,
                birth:'1999-9-9'
            }
            $.ajax({
                url:'/login4',
                type:'post',
                data:JSON.stringify(user),
                contentType:'application/json;charset=utf-8',
                dataType:'json',
                success:function (result) {
                    console.log(result);
                },
                error:function () {
                    console.log("请求失败!")
                }
            })
        })

    })

</script>

Restful style

A software architectural style, design style, rather than a standard, just provides a set of design principles and constraints. It is mainly used for client and server interaction software. Software designed based on this style can be more concise, more layered, and easier to implement mechanisms such as caching

URL definition

Resources: All things on the Internet can be abstracted as resources Resource operations: use POST, DELETE, PUT, GET, and use different methods to operate on resources. Respectively corresponding to add, delete, modify, query

Manipulating resources in the traditional way

http://127.0.0.1/item/queryUser.action?id=1 Query, GET 
http://127.0.0.1/item/saveUser.action Add, POST 
http://127.0.0.1/item/updateUser.action update, POST 
http://127.0.0.1/item/deleteUser.action?id=1 delete, GET or POST

RestFul request method You can operate resources on the server side through GET, POST, PUT, PATCH, DELETE, etc. in:

  • GET is used to query resources,

  • POST is used to create resources,

  • PUT is used to update all information of resources on the server side,

  • DELETE is used to delete resources on the server side.

public class RestController {

    @GetMapping("/rest")
    public void test01(){
        System.out.println("test01: ");
    }  

    @PostMapping("/rest")
    public void test02(){
        System.out.println("test02: ");
    }

    @DeleteMapping("/rest")
    public void test03(){
        System.out.println("test03:");
    }

    @PutMapping("/rest")
    public void test04(){
        System.out.println("test04: ");
    }

    @PatchMapping("/rest")
    public void test05(){
        System.out.println("test05: ");
    }

}

Form sending PUT request setting method

 <form action="rest/r" method="post">
        <input type="hidden" name="_method" value="PUT">
        <p><input type="text" placeholder="请输入id" name="id"></p>
        <p><input type="text" placeholder="请输入姓名" name="username"></p>
        <p><input type="date" placeholder="请输入生日" name="birth"></p>
        <p><input type="submit"></p>
 </form>

set web.xml

<filter>
       <filter-name>Hidden</filter-name>
       <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

<filter-mapping>
    <filter-name>Hidden</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

REST style parameter passing problem

 @GetMapping("/login/{username}/{password}")
    public void login(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        //响应json格式的字符串
        res.setContentType("application/json;charset=utf-8");
        JsonResult result = JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
        res.getWriter().write(result.toJSONString());
    }

Handling of Chinese garbled characters in data submission

<!--解决中文乱码-->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

SpringMVC static resource processing

1. Configure the path of static resources

<mvc:resources mapping="/static/**" location="/static/"/>

2. Configure the servlet processor using tomcat

<mvc:default-servlet-handler/>

SpringMVC operates session and cookie

@Controller
@SessionAttributes({"model1","model2"})
public class SessionController {

    @RequestMapping("/s1")
    public void test01(HttpSession session){
        session.setAttribute("msg", "session attribute");
    }

    @RequestMapping("/s2")
    public void test02(HttpSession session){
        System.out.println(session.getAttribute("msg"));
    }

    /**
     * 将model放入session作用域
     * @param model
     */
    @RequestMapping("/s3")
    public void test03(Model model){
        model.addAttribute("model1", "model1 attribute");
    }

    /**
     * 获取通过注解设置的session域中的值
     * @param session
     */
    @RequestMapping("/s5")
    public void test05(HttpSession session){
        System.out.println("msg: "+session.getAttribute("msg"));
        System.out.println("model1 :"+session.getAttribute("model1"));
        System.out.println("model2 :"+session.getAttribute("model2"));
    }

    /**
     * 通过注解获取session域中的值
     * @param
     */
    @RequestMapping("/s6")
    public void test05(@SessionAttribute(name = "msg") String session){
        System.out.println(session);
    }
   
操作cookie

public class CookieController {

    @RequestMapping("/c1")
    public void test01(HttpServletResponse response){
        Cookie ck = new Cookie("cookie","cookieValue");
        ck.setPath("/");
        ck.setMaxAge(60*60*24*7);
        response.addCookie(ck);
    }

    /**
     * 获取cookie中值的方式1
     * @param request
     */
    @RequestMapping("/c2")
    public void test02(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(cookies[i].getName()+":"+cookies[i].getValue());
        }
    }

    /**
     * 获取cookie中值的方式2  注解方式
     * @param cookie
     */
    @RequestMapping("/c3")
    public void test03(@CookieValue("cookie") String cookie){
        System.out.println(cookie);
    }
}

SpringMVC interceptor

The Interceptor interceptor in SpringMVC is also very important and useful. Its main function is to intercept user requests and process them accordingly. For example, use it to verify permissions, or to determine whether a user is logged in or not. There are two ways to define SpringMVC interceptors

  • Implement interface: org.springframework.web.servlet.HandlerInterceptor

  • Inheritance adapter: org.springframework.web.servethandler.HandlerInterceptorAdapter

1. Implement the HandlerInterceptor interface

public class MyIntercepter01 implements HandlerInterceptor {

    /**
     * 目标方法执行前执行  返回false拦截   否则放行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyIntercepter01 ->目标方法前->执行preHandle01 ");
        return true;
    }

    /**
     *
     * 目标方法执行后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyIntercepter01 ->目标方法执行后->执行postHandle01 ");
    }

    /**
     * 视图响应完成后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyIntercepter01 ->视图渲染完成后->执行afterCompletion01 ");
    }
2.继承HandlerInterceptorAdapter(不建议使用)

public class MyInterceptor2  extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }
}
使用拦截器拦截非法请求

/**
 *用户操作模拟实现
 * 用户的登录(无需登录)
 * 用户的添加(登录)
 * 用户修改(登录)
 * 用户删除(登录)
 *
 * @author mosin
 * date 2021/8/22
 * @version 1.0
 */
@Controller
@RequestMapping("/user")
@SessionAttributes("action")
public class UserInfoController {
    /**
     * 用户登录
     */
    @RequestMapping("/login")
    public ModelAndView login(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("success");

        User user = User.builder().password("123456").username("lisi").build();
        session.setAttribute("user", user);
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    /**
     * 用户添加
     */
    @RequestMapping("/add")
    public String add(Model model){
        model.addAttribute("action", "用户添加成功");
        System.out.println("用户的添加方法");

        return "success";
    }

    /**
     * 用户修改
     */
    @RequestMapping("/update")
    public String update(Model model){
        System.out.println("用户的更新方法");
        model.addAttribute("action", "用户更新成功");
        return "success";
    }

    /**
     * 用户修改
     */
    @RequestMapping("/delete")
    public String delete(Model model){
        System.out.println("用户的删除方法");
        model.addAttribute("action", "用户删除成功");
        return "success";
    }

}

SpringMVC file upload

添加坐标依赖

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
 </dependency>
配置解析器

<!--    文件上传配置文件解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--       允许上传的最大文件  单位字节-->
        <property name="maxUploadSize" >
            <value>104857600</value>
        </property>
<!--        内存中的最大缓存超出写出临时文件到硬盘-->
        <property name="maxInMemorySize" >
            <value>4096</value>
        </property>
        <property name="defaultEncoding">
            <value>utf-8</value>
        </property>
    </bean>
后台代码

@Controller
@RequestMapping("/upload")
public class UPloadController {

    @RequestMapping("/file")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){

        //获取项目的真实路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        System.out.println(realPath);
        //创建文件上传的目录
        File dir = new File(realPath, "/upload");
        System.out.println(dir);
        //判定文件夹是否存在 不存在创建
        if(!dir.exists()){
            dir.mkdir();
        }

        if(!file.isEmpty()){
            //获取文件的名字
            String fileName = file.getOriginalFilename();
            //截取文件的后缀 生成新的文件名 避免文件名字重复
            String suffix= fileName.substring(fileName.lastIndexOf("."));
            //获取当前系统时间
            String fileLastName = System.currentTimeMillis()+suffix;
            System.out.println(fileLastName);
            //将文件写入目标文件夹
            try {
                file.transferTo(new File(dir,fileLastName));
                request.setAttribute("msg", "文件上传成功");
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("msg", "文件上传失败");
            }
        }else{
            request.setAttribute("msg", "未选择文件");
        }

        return "success";
    }

    @RequestMapping("/files")
    public String uploads(@RequestParam("files") List<MultipartFile> files, HttpServletRequest request){

        //遍历集合
       files.forEach(multipartFile -> {
           FileUploadUtil.upload(multipartFile, request);
       });
        return "success";
    }
}

SpringMVC global exception unified processing

1. Processing method 1 Use @ExceptionHandler(Exception.class) to define an exception method in the class to handle the specified exception in this class

@RestController
@RequestMapping("/exception")
public class ExceptionController01 {

    @ExceptionHandler(Exception.class)
    public Object handlerException(Exception e){
        return JsonResult.builder().msg("出现"+"异常").code(1).data(e.getMessage()).build();
    }

    @RequestMapping("/e1")
    public Object ex1(){
        int a  = 1/0;
        return null;
    }

    @RequestMapping("/e2")
    public Object ex2() throws FileNotFoundException {
        new FileInputStream("ab");
        return null;
    }
}
2.处理的方式2 全局处理模式 定义ExceptionAdvice类

@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(value ={Exception.class})
    public Object handlerException(Exception e){
        return JsonResult.builder().msg("出现"+"异常").code(1).data(e.getMessage()).build();
    }
}

SSM framework integration

1. Introduce pom dependencies

1. Introduce mybatis dependency

<!--    mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
    </dependency>
<!--    分页pagehelper-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.2.1</version>
    </dependency>
<!--    mybatis-spring-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.5</version>
    </dependency>
2.引入spring依赖

<!--    spring-context-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.9</version>
    </dependency>
<!--    spring-aspects-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.3.9</version>
    </dependency>
<!--      spring-jdbc-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.3.9</version>
      </dependency>
3.springmvc依赖

<!--    spring-webmvc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.9</version>
    </dependency>
<!--    jackson-core-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.11.3</version>
    </dependency>
<!--    jackson-databind-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.3</version>
    </dependency>
<!--    jackson-annotations-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.11.3</version>
    </dependency>

<!--    文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
4.log4j依赖

<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
 <dependency>
       <groupId>org.apache.logging.log4j</groupId>
       <artifactId>log4j-api</artifactId>
       <version>2.13.3</version>
 </dependency>
  <dependency>
       <groupId>org.apache.logging.log4j</groupId>
       <artifactId>log4j-core</artifactId>
       <version>2.13.1</version>
  </dependency>
5.数据库驱动和连接池

<!--    mysql-connector-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.44</version>
    </dependency>
   
<!--    druid连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>
6.servlet+jsp依赖

<!--servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
<!--    jsp-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
7.jstl依赖

<!--jstl-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
8.其它依赖

<!--    lombok-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.16</version>
    </dependency>
<!--    junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

2. Set the configuration file

1.db.properties

jdbc.driver=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql:///mybatis?useSSL=true&serverTimezone=GMT%2B8 
jdbc.username=root 
jdbc.password=root 

#The number of connections established in the pool during initialization . 
jdbc.initialSize=2 
#The maximum number of active connection pools 
jdbc.maxActive=300 
#Maximum waiting time 
jdbc.maxWait=60000

2.log4j.properties

log4j.rootLogger=DEBUG,Console

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.org.apache=ERROR
log4j.logger.org.mybatis=ERROR
log4j.logger.org.springframework=ERROR

#这个需要
log4j.logger.log4jdbc.debug=ERROR
log4j.logger.com.gk.mapper=ERROR
log4j.logger.jdbc.audit=ERROR
log4j.logger.jdbc.resultset=ERROR
#这个打印SQL语句非常重要
log4j.logger.jdbc.sqlonly=DEBUG
log4j.logger.jdbc.sqltiming=ERROR
log4j.logger.jdbc.connection=FATAL

3.spring core configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 读取db.properties -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="${jdbc.initialSize}" />
        <property name="maxActive" value="${jdbc.maxActive}" />
        <property name="maxWait" value="${jdbc.maxWait}" />
    </bean>

    <!-- 事务管理器,依赖于数据源 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"  />

    <!-- 配置MyBatis工厂 SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 指定Mybatis核心配置文件位置 -->
        <property name="configLocation" value="classpath:config/mybatis-config.xml" />
        <!-- 扫描模块配置文件:mapper需要的xml文件(如果mapper.xml和接口在一个包下,可以不配置) -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 配置mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.kgc.ssm.dao" />
    </bean>

    <!-- 扫描包-->
    <context:component-scan base-package="cn.kgc.ssm" />
    <!--    开启spring注解支持-->
    <context:annotation-config/>
</beans>

4. spring-mvc configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 加载注解驱动 -->
    <mvc:annotation-driven />
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!--释放静态资源-->
    <mvc:default-servlet-handler/>
    <!--    文件上传配置文件解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--       允许上传的最大文件-->
        <property name="maxUploadSize" >
            <value>104857600</value>
        </property>
        <!--        内存中的最大缓存超出写出临时文件到硬盘-->
        <property name="maxInMemorySize" >
            <value>4096</value>
        </property>
        <property name="defaultEncoding">
            <value>utf-8</value>
        </property>
    </bean>
</beans>

5. mybatis configuration file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- mybatis运行时设置 -->
    <settings>
        <!-- 启用log4j日志 -->
        <setting name="logImpl" value="LOG4J"></setting>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 别名定义 -->
    <typeAliases>
        <package name="cn.kgc.ssm.entity" />
    </typeAliases>

    <!-- mybatis插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 配置mysql方言 -->
            <property name="helperDialect" value="mysql" />
            <!-- 设置为true时,如果pageSize=0就会查询出全部的结果 -->
            <property name="pageSizeZero" value="true" />
            <!-- 3.3.0版本可用,分页参数合理化,默认false禁用 -->
            <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
            <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>

6.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    前端控制器-->
    <servlet>
        <servlet-name>ssm</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ssm</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

<!--    过滤器解决中文乱码-->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
         </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>
</web-app>

3. Project directory structure

 

Guess you like

Origin blog.csdn.net/m0_67979925/article/details/129747743