Detailed description of spring mvc usage and integration of ssm

spring mvc

What is mvc

Model view controller (MVC) is a well-known design idea based on the design field response program. It mainly decouples the business logic from the boundary by separating the model, view and controller in the application. Generally, the model is responsible for encapsulating the application data to be displayed at the view level. The view only shows the data and does not contain any business logic. The controller is responsible for receiving the request from the incoming user and calling the background service (service or dao) to process the business logic. After processing, the background business layer may return some data to be displayed in the view layer. The controller collects these data and prepares the model for presentation at the view level. The core idea of MVC pattern is to separate the business logic from the boundary and allow them to change independently without affecting each other.

3 questions

What is spring mvc

Spring MVC is a "web member" in the spring family. It is a lightweight web framework based on Java that implements the design idea of Web MVC. Even if the idea of MVC architecture pattern is adopted, the web layer is decoupled into "responsibilities". Based on request driving, it means to make "request response model". The "purpose of the framework" is to help us simplify development. Spring MVC is also to simplify our common web development.

Spring MVC is an implementation of the idea of "service to author". The front-end controller is DispatcherServlet; The controller shall be disassembled into a handler mapping for processor management and a view resolver for view management; support support localization / internationalization (Locale ) analysis and uploading of text pieces; It provides flexible data validation, formatting and data binding mechanisms; It provides a contractual programming support with a strong convention over configuration (Convention first principle).

What spring mvc can do

  1. Let us easily design a clean Web layer;
  2. Develop a more concise Web layer;
  3. Integration with Spring framework (such as IOC container, AOP, etc.);
  4. Provide the contract programming support that is strong in the configuration;
  5. Can simply enter the unit test of the Web layer;
  6. Support flexible URL mapping to page controller;
  7. It is often easy to integrate with other view technologies, such as jsp, Velocity, FreeMarker, etc., because the Model data is not placed in a specific API, but in a Model (Map data structure is implemented, so it is easy to be used by other frameworks);
  8. Flexible data validation, formatting and data binding mechanisms enable any object to enter data binding without implementing the API of a specific framework;
  9. flexible localization and other analysis;
  10. Simpler exception handling;
  11. Holding static resources;
  12. hold Restful.

How spring mvc works

The process of spring mvc returning views is equivalent to request forwarding

The Spring MVC framework is also a request driven Web framework, and enables the front-end controller mode (yes) to provide a centralized request processing mechanism. All requests will be designed to be processed by a single handler, and then distributed to the corresponding controller (action / processor) for processing according to the request mapping rules. let's take a look at the process of Spring MVC processing requests as a whole:

  1. first, the user sends a request, which is captured by the SpringMvc front-end controller (DispatherServlet);
  2. . The front-end controller (DispatherServlet) parses the request URL to obtain the request URI, and calls "HandlerMapping" according to the URI;
  3. The front-end controller (DispatherServlet) obtains the returned HandlerExecutionChain (including the Handler object and the interceptor corresponding to the Handler object);
  4. DispatcherServlet selects appropriate handleradapters according to the obtained HandlerExecutionChain. (Note: if the HandlerAdapter is successfully obtained, the pre handler (...) method of the interceptor will be executed at this time);
  5. HandlerAdapter adapts and executes the corresponding Handler according to the requested Handler; HandlerAdapter (extract the model data in the Request, fill in the Handler parameter, and start to execute the Handler (Controller). During the process of filling in the input parameters of the Handler, according to the configuration, Spring will do some additional functions: httpmessageconverter: convert the Request message (such as Json, xml and other data) into an objects, and convert the objects into the specified response information. Data conversion: perform data conversion on the Request message. For example, converting String to Integer, Double and other data formatting: data formatting. For example, to convert a String into a formatted number or format data such as Date Period Verification: verify the validity of the data ( such as long degree, format, etc.), and store the verification results in BindingResult or Error)
  6. After the Handler finishes executing, it returns "modelandviews" (i.e. models and views) to the HandlerAdaptor
  7. The HandlerAdaptor adapter returns the execution result ModelAndView to the front-end controller.
  8. After receiving the ModelAndView, the front-end controller requests the corresponding view parser.
  9. The View parser parses ModelAndView and returns the corresponding View;
  10. Render the view and return the rendered view to the front controller.
  11. Finally, the front-end controller sends the rendered page response to the user or client

rely on

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.lwf</groupId>
  <artifactId>11_24springMVC</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>11_24springMVC Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.75</version>
    </dependency>
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.16</version>
      </dependency>
    <!-- spring web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.4.RELEASE</version>
    </dependency>
    <!-- spring mvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.4.RELEASE</version>
    </dependency>
    <!-- web servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>

  </dependencies>
  <build>
  <plugins>
  <!-- Compiling environment plug-ins -->
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
      <encoding>UTF-8</encoding>
    </configuration>
  </plugin>
  <!-- jetty plug-in unit -->
  <plugin>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-maven-plugin</artifactId>
  <version>9.4.27.v20200227</version>
  <configuration>
    <scanIntervalSeconds>10</scanIntervalSeconds>
    <!-- Setting end mouth -->
    <httpConnector>
      <port>8085</port>
    </httpConnector>
    <!-- Set item item path -->
    <webAppConfig>
      <contextPath>/springmvc01</contextPath>
    </webAppConfig>
  </configuration>
  </plugin>
  </plugins>
  </build>
</project>

Start configuration (load spring configuration file by web container)

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <!-- Code filtering utf-8 -->
  <filter>
    <description>char encoding filter</description>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- servlet Request distributor -->
  <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:spring.xml</param-value>
    </init-param>
    <!-- Indicates that the Servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>springMvc</servlet-name>
  <!-- This is an intercept request, "/"Delegate intercepts all requests,"*.do"Block all.do request -->
   <url-pattern>/</url-pattern>
<!--    <url-pattern>*.do</url-pattern>-->
  </servlet-mapping>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

Simple presentation

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Test {
    private String name;
    private String city;
}

@Service
public class TestService {
    private List<Test> user=new ArrayList<>();
    {
        Test test=new Test("lwf","jx");
        Test test1=new Test("lwf1","jx");
        user.add(test);
        user.add(test1);
    }
    public List<Test> tests(){return user;}
}

@RestController
public class TestController {
    @Autowired
    private TestService testService;
    /*
    Return to view plus data
    */
    @RequestMapping("/test")
    public ModelAndView test(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("one", testService.tests().get(0));
        modelAndView.setViewName("Test");
        return modelAndView;
    }
}

@RequestMapper

Parameters:

value: the path mapped by the processor can be a single url or multiple parameters

//Return object in json mode
@RestController
//Return view name
//@Controller
public class TestController {
    @Autowired
    private TestService testService;
    //The value attribute can be one or more URLs. The value attribute is default, so "value=" may not be written; URLs similar to servlet s are 1-to-many
    @RequestMapping({"/test","tes"})
   // @RequestMapping(value = {"/test","tes"})
    //@RequestMapping("/test")
    public ModelAndView test(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("one", testService.tests().get(0));
        modelAndView.setViewName("Test");
        return modelAndView;
    }
}

**params:** determine which controller to access according to the request url

/**
 * Access by parameter name
 * Access through parameters
 * Access address:
 * http://ip:port/springmvc/url?test06
 * @return
 */
@RequestMapping(params = "test06")
public ModelAndView test06(){
 ModelAndView modelAndView = new ModelAndView();
 modelAndView.addObject("hello","test06");
 modelAndView.setViewName("hello");
 return modelAndView;
}

Method: the corresponding request method (get, post, put...). The parameter is the RequestMethod enumeration object (delete,get,head,options,patch,post,put,trace)

There are multiple parameters, and the prefix (value, method) must be added (actually, idea added it for me).

@RequestMapping(value = {"/test","tes"},method = RequestMethod.POST)

RequestMapper is an all-round annotation. The following annotations are for various requests

//For delete requests, the two annotation methods have the same effect
@RequestMapping(value = "/test",method = RequestMethod.DELETE)
@DeleteMapping(value = "/test")

//Same reason
 @GetMapping("/test")
 @RequestMapping(value = "/test",method = RequestMethod.GET)
 
// post
@PostMapping("/test")
 @RequestMapping(value = "/test",method = RequestMethod.POST)
 
 //put
@RequestMapping(value = "/test",method = RequestMethod.PUT)
@PutMapping("/test")

8. The other requests are similar to the above. Here we only list the above four. The above four request methods correspond to the curd (add, delete, modify and query) of the persistence layer. The rational use of these four requests is also the cornerstone of RestFul style coding methods;

RestFul (spring mvc extension)

RESTful architecture should follow the principle of unified interface, which includes a set of restricted predefined operations. No matter what kind of resources are accessed through the same interface. The interface should use standard HTTP methods such as GET, PUT and POST, and follow the semantics of these methods.

If resources are exposed according to the semantics of HTTP methods, the interface will have the characteristics of security and idempotence. For example, GET and HEAD requests are secure, and the server state will not be changed no matter how many times the request is made. The GET, HEAD, PUT and DELETE requests are idempotent. No matter how many times the resource is operated, the result is always the same. The subsequent requests will not have more impact than the first time.

Typical usage of GET, DELETE, PUT and POST are listed below:

GET

  • Safe and idempotent

  • Get representation

  • Get representation on change (CACHE)

  • 200 (OK) - indicates that it has been issued in the response

  • 204 (no content) - empty resource representation

  • 301 (Moved Permanently) - the URI of the resource has been updated

  • 303 (See Other) - other (e.g., load balancing)

  • 304 (not modified) - resource not changed (cached)

  • 400 (bad request) - refers to a bad request (for example, parameter error)

  • 404 (not found) - resource does not exist

  • 406 (not acceptable) - the server does not support the required representation

  • 500 (internal server error) - general error response

  • 503 (Service Unavailable) - the server is currently unable to process the request

POST

  • Unsafe and not idempotent

  • Create resources using the (automatically generated) instance number managed by the server

  • Create sub resource

  • Some update resources

  • If it has not been modified, the resource will not be updated (Le Guan lock)

  • 200 (OK) - if an existing resource has been changed

  • 201 (created) - if a new resource is created

  • 202 (accepted) - processing request accepted but not completed (asynchronous processing)

  • 301 (Moved Permanently) - the URI of the resource is updated

  • 303 (See Other) - other (e.g., load balancing)

  • 400 (bad request) - bad request

  • 404 (not found) - resource does not exist

  • 406 (not acceptable) - the server does not support the required representation

  • 409 (conflict) - Generic conflict

  • 412 (Precondition Failed) - Precondition Failed (e.g. conflict during condition update)

  • 415 (unsupported media type) - the received representation is not supported

  • 500 (internal server error) - general error response

  • 503 (Service Unavailable) - the service is currently unable to process the request

PUT

  • Unsafe but idempotent

  • Create a resource with the instance number managed by the client

  • Update resources by substitution

  • If it is not modified, update the resource (Le Guan lock)

  • 200 (OK) - if the existing resource is changed

  • 201 (created) - if a new resource is created

  • 301 (Moved Permanently) - the URI of the resource has changed

  • 303 (See Other) - other (e.g., load balancing)

  • 400 (bad request) - bad request

  • 404 (not found) - resource does not exist

  • 406 (not acceptable) - the server does not support the required representation

  • 409 (conflict) - Generic conflict

  • 412 (Precondition Failed) - Precondition Failed (e.g. conflict during condition update)

  • 415 (unsupported media type) - the received representation is not supported

  • 500 (internal server error) - general error response

  • 503 (Service Unavailable) - the service is currently unable to process the request

DELETE

  • Unsafe but idempotent

  • Delete resource

  • 200 (OK) - resource deleted

  • 301 (Moved Permanently) - the URI of the resource has changed

  • 303 (See Other) - other, such as load balancing

  • 400 (bad request) - bad request

  • 404 (not found) - resource does not exist

  • 409 (conflict) - Generic conflict

  • 500 (internal server error) - general error response

  • 503 (Service Unavailable) - the server is currently unable to process the request

To sum up, RestFul is to use the same request url address to distinguish which operations to add, delete, modify, and query. In a huge project, this avoids api interface explosion.

Give me a chestnut

url: http://localhost:8080/springMVC/user

Add: url: http://localhost:8080/springMVC/user method:post User{name: "lwf", age:18,desc: "you are so handsome that you hide in the sun"}

Delete: url: http://localhost:8080/springMVC/user method:delete User{name: "lwf", age:18,desc: "you are so handsome that you hide in the sun"}

Change: url: http://localhost:8080/springMVC/user method:put User{name: "lwf", age:18,desc: "you are so handsome that you hide in the sun"}

Query: url: http://localhost:8080/springMVC/user/{name} method:get

position

1. Method (RestFul style)

2. On the controller, set the root path of mapping on the access method

Parameter binding

  1. The parameter name is equal to the value of the data name attribute passed from the front end

    Basic type plus string

    Request: http://localhost:8080/springmvc/test?name=lwf&age=18&desc= 'handsome'

    @RequestMapping("/test")
     public ModelAndView test(String name,Integer age,String desc){
         ModelAndView modelAndView=new ModelAndView();
         System.out.println("welcome:"+name+desc);
         modelAndView.addObject("one", testService.tests().get(0));
         modelAndView.setViewName("Test");
         return modelAndView;
     }
    

    Complex type

    For a single object, the key value pair passed is the same as the java class attribute name, and is automatically bound:

    Request: http://localhost:8080/springmvc/test?name=lwf&age=18&desc= 'handsome'

    @RequestMapping("/test")
     public ModelAndView test(User user){
         ModelAndView modelAndView=new ModelAndView();
         System.out.println("welcome:"+user.toString());
         modelAndView.addObject("one", testService.tests().get(0));
         modelAndView.setViewName("Test");
         return modelAndView;
     }
    

    Array:

    /**
     * Array type data binding
     * Client parameter transfer form: ids=1&ids=2&ids=3
     * @param ids
     */
    @RequestMapping("/data06")
    public void data06(String[] ids){
     for(String id : ids){
     System.out.println(id + "---");
     }
    }
    

    **List:** at this time, the User entity needs to define the corresponding list attribute. (for the parameter binding of the collection, it is generally necessary to wrap the JavaBean object)

    //pojo class
    @lombok.Data
    public class User {
    
     private int id;
     private String userName;
     private String userPwd;
    
     private List<Phone> phones = new ArrayList<Phone>();
     }
     
     @lombok
     public class Phone {
    
     private String num;
     }
     
     //front end
    <form action="data08" method="post">
     <input name="phones[0].num" value="123456" />
     <input name="phones[1].num" value="4576" />
     <button type="submit"> Submit</button>
    </form>
    
    //controller
    @RequestMapping("/data08")
    public void data08(User user){
     System.out.println(user);
    }
    

    set type: similar to list

    //pojo class
    @lombok.Data
    public class User {
    
     private int id;
     private String userName;
     private String userPwd;
    
     private Set<Phone> phones = new HahSet<Phone>();
     }
     
     @lombok
     public class Phone {
    
     private String num;
     }
     
     //front end
    <form action="data08" method="post">
     <input name="phones[0].num" value="123456" />
     <input name="phones[1].num" value="4576" />
     <button type="submit"> Submit</button>
    </form>
    
    //controller
    @RequestMapping("/data08")
    public void data08(User user){
     System.out.println(user);
    }
    

    Map

    //pojo class
    @lombok.Data
    public class User {
    
     private int id;
     private String userName;
     private String userPwd;
    
     private Map<String,Phone> map = new HahMap<>();
     }
    <form action="data10" method="post">
     <input name="map['1'].num" value="123456" />
     <input name="map['2'].num" value="4576" />
     <input name="map['3'].num" value="4576" />
     <button type="submit"> Submit</button>
    </form>
     
    //controller
    @RequestMapping("/data08")
    public void data08(User user){
     System.out.println(user);
    }
    
  2. Different, use annotation binding

    Basic type plus string

    Request: http://localhost:8080/springmvc/test?name=lwf&age=18&desc= 'handsome'

    @RequestMapping("/test")
        public ModelAndView test(@RequestParam(name="name") String name1,@RequestParam(name="age") Integer age1,@RequestParam(name="desc") String desc1){
            ModelAndView modelAndView=new ModelAndView();
            System.out.println("welcome:"+name1+desc1);
            modelAndView.addObject("one", testService.tests().get(0));
            modelAndView.setViewName("Test");
            return modelAndView;
        }
    

    Complex type (idle boredom makes a difference)

  3. Receive using HttpServletRequest

    servlet like usage

    //Request: http://localhost:8080/springmvc/test?name=lwf&age=18&desc= 'handsome'
    @RequestMapping("/test")
     public ModelAndView test(HttpServletRequest req){
         ModelAndView modelAndView=new ModelAndView();
         System.out.println("welcome:"+req.getParemitet("name"));
         modelAndView.addObject("one", testService.tests().get(0));
         modelAndView.setViewName("Test");
         return modelAndView;
     }
    

Request forwarding

SpringMVC displays the page information in the form of use internal forwarding of the server by default. Also supports hold heavy orientation page.

redirect

Redirection is to send a 302 status code to the browser, and the browser requests a jump. The address bar will be changed.

Redirection starts with redirect:

/**
 * Redirect to JSP page
 * @return
 */
@RequestMapping(value="/view01")
public String view01(){
 return "redirect:view.jsp";
}
/**
 * Redirect to JSP page
 * Transfer parameters
 * @return
 */
@RequestMapping(value="/view02")
public String view02(){
 return "redirect:view.jsp?uname=zhangsan&upwd=123456";
}
/**
 * Redirect to JSP page
 * Pass the parameter (the Text parameter will be garbled during transmission)
 * @return
 */
@RequestMapping(value="/view03")
public String view03(){
 return "redirect:view.jsp?uname=Zhang San&upwd=123456";
}
/**
 * Redirect to JSP page
 * Pass the parameters (set the redirection parameters through the RedirectAttributes object to avoid the problem of medium text garbled code)
 * @param redirectAttributes
 * @return
 */
@RequestMapping(value="/view04")
public String view04(RedirectAttributes redirectAttributes){
 redirectAttributes.addAttribute("uname","Zhang San");
 redirectAttributes.addAttribute("upwd","123456");
 return "redirect:view.jsp";
}
/**
 * Redirect to JSP page
 * Return ModelAndView object
 * @param modelAndView
 * @return
 */
@RequestMapping(value="/view06")
public ModelAndView view06(ModelAndView modelAndView){
 modelAndView.addObject("uname","Lisi");
 modelAndView.addObject("upwd","123321");
 modelAndView.setViewName("redirect:view.jsp");
 return modelAndView;
}
/**
 * Redirect to Controller
 * Return ModelAndView object
 * @param modelAndView
 * @return
 */
@RequestMapping(value="/view07")
public ModelAndView view07(ModelAndView modelAndView){
 modelAndView.addObject("uname","admin");
 modelAndView.setViewName("redirect:test01");
 return modelAndView;
}

Get parameter values ​​from page

General data: ${Parameter name}
Complex data: ${Parameter name.attribute}

Request forwarding

Request forwarding, directly call the "jump" and let it return. For the browser, it can't tell whether the server has forward. The address bar will not be changed. Data in the request domain can be obtained.

Request forwarding begins with forward:

/**
 * Request forwarding to JSP page
 */
@RequestMapping("/view08")
public String view08(){
 return "forward:view.jsp";
}
/**
 * Request forwarding to JSP page
 * Setting parameters
 */
@RequestMapping("/view09")
public String view09(){
 return "forward:view.jsp?uname=Zhang San&upwd=123456";
}
/**
 * Request forwarding to JSP page
 * Set request domain
 */
@RequestMapping("/view10")
public String view10(Model model){
 model.addAttribute("uname","Zhang San");
 return "forward:view.jsp";
}
/**
 * Request forwarding to JSP page (default)
 * By default, it will specify that the JSP (set in the configuration file) will be found under the target record
 */
@RequestMapping("/view11")
public String view11(){
 return "/../../view";
}
/**
 * Request forwarding to Controller
 * @return
 */
@RequestMapping("/view12")
public ModelAndView view12(ModelAndView modelAndView){
 modelAndView.setViewName("forward:test01");
 return modelAndView;
}
/**
 * Request forwarding to Controller
 * Transfer parameters
 * @return
 */
@RequestMapping("/view13")
public ModelAndView view13(ModelAndView modelAndView){
 modelAndView.setViewName("forward:test01?uname=admin");
 return modelAndView;
}

Value

General data: ${Parameter name}
Complex data: ${Parameter name.attribute}

Interact with json data

In enterprise development, json has been used as the parameter type of the general interface, which is easy to resolve in the client. SpringMVC provides good support for json, which requires modifying relevant configurations and adding json data support functions

@ResponseBody

This annotation is used to convert the object returned by the "method" of the Controller to the specified format through the appropriate HttpMessageConverter, and then write it to the body data area of the Response object. The returned data is not the "html" tag. When it is data in some other format (such as json, xml, etc.), it will be "ajax" (usually "ajax request").

@RequestBody

This annotation is used to read the data of the body part of the Request, enable the HttpMessageConverter configured by default to be parsed, bind the corresponding data to the object to be returned, and then bind the object data returned by the HttpMessageConverter to the parameters of the method in the controller.

pom dependency

<!-- add to json rely on jar package -->
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.10.0</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.10.0</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-annotations</artifactId>
 <version>2.10.0</version>
</dependency>

spring profile add

<!-- mvc Request mapping processor and Adapter Configuration -->
<mvc:annotation-driven>
 <mvc:message-converters>
 <bean
class="org.springframework.http.converter.StringHttpMessageConverter" />
 <bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConve
rter" />
 </mvc:message-converters>
</mvc:annotation-driven>

code

@ResponseBody

@Controller
@RequestMapping("/user")
public class UserController {
 /**
 * @ResponseBody The returned data is in JOSN format, and the JavaBean object is returned
 * Annotation set on square body
 * @return
 */
 @RequestMapping("queryUser01")
 @ResponseBody
 public User queryUser01(){
 User user = new User();
 user.setId(1);
 user.setUserName("zhangsan");
 user.setUserPwd("123456");
 // user object returned
 return user;
 }
 /**
 * @ResponseBody The returned data is in JOSN format, and the JavaBean object is returned
 * The annotation is set before the method returns the object and after the modifier
 * @return
 */
 @RequestMapping("queryUser02")
 public @ResponseBody User queryUser02(){
 User user = new User();
 user.setId(2);
 user.setUserName("lisi");
 user.setUserPwd("123321");
 // user object returned
 return user;
 }

 /**
 * @ResponseBody The returned data is in JOSN format, and the returned set
 * @return
 */
 @RequestMapping("/queryUser03")
 @ResponseBody
 public List<User> queryUser03(){
 List<User> list = new ArrayList<>();
 User user01 = new User();
 user01.setId(1);
 user01.setUserName("zhangsan");
 user01.setUserPwd("123456");
 User user02 = new User();
 user02.setId(2);
 user02.setUserName("lisi");
 user02.setUserPwd("123321");
 list.add(user01);
 list.add(user02);
 // user collection returned
 return list;
 }
}

@RequestBody

@The RequestBody annotation is often used to handle content whose content type is not the default application/x-www-form-urlcode type, such as application/json or application/xml. Generally speaking, it is often used to handle application/json types@ The RequestBody accepts one JSON strings, one must be one strings. Through @RequestBody, you can bind the JSON strings in the request body to the corresponding bean s. Of course, you can also bind them to the corresponding strings respectively.

/**
 * @RequestBody Specifies that the requested parameter is a string in JOSN format
 * The annotation is set before the formal parameter
 * @param user
 * @return
 */
@RequestMapping("/getUser")
@ResponseBody
public User getUser(@RequestBody User user){
 System.out.println(user);
 return user;
}

//Front end ajax submission data
function test(){
 $.ajax({
 // Request get post
 type: "post",
 // Request path
 url: "user/getUser",
 // Expected amount data type returned by the server
 dataType: "json",
 // Set the data type of the server request type to JSON format
 contentType: "application/json;charset=utf-8",
 // Parameters passed to the server
 data:'{"userName":"admin","userPwd":"123456"}',
 // A callback function that receives the result of the response returned by the server (the formal parameter used in the function is used to receive the response returned by the server
 Data)
 success:function(data){
 console.log(data);
 }
 })
 }

Interceptor

The Interceptor interceptor in SpringMVC is also very important and useful. Its main function is to intercept the user's request and process it accordingly. for example, it can be used to perform permission verification, or to determine whether the user logs in. There are two definitions of SpringMVC interceptors:

Implementation link: org springframework. web. servlet. HandlerInterceptor

Inheritance adapter: org springframework. web. servlet. handler. HandlerInterceptorAdapter

: the interceptor performs steps 4, 7, and 9.

code

public class RootHanderIntercepter extends HandlerInterceptorAdapter {
    /*
    Execute before executing the controller, which is similar to the filter. Return the true table to allow passing, and false to intercept
    You can filter users who are not logged in and redirect the request to the login page:
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //No session, log in
    if(request.getSession().getAttribute("currUser")==null){
        response.sendRedirect("login.jsp");
        return false;
    }
    //With session, release
    return true;
    }
    
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String name=request.getParameter("name");
        if (name.equals("lwf")){
            System.out.println(name+"Pass to execute the controller");
            return true;
        }
        System.out.println("intercept"+name);
        return false;
    }
     /*
     After the controller is executed, it will be executed on the way back to the central controller
      */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("Execute controller");
    }
      /*
      After the execution, the view parser returns to the central controller for execution
       */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("View complete");
    }

}

spring configuration interceptor

<!--
 Interceptor chain (multiple interceptors)
 If multiple interceptors meet the requirements of interception processing, they shall be executed according to the sequence of configuration
 Of interceptors configured first preHandle Law first
 Of interceptors configured first postHandle,afterCompletion Law enforcement
 -->
<mvc:interceptors>
        <mvc:interceptor>
         <!-- Block all requests -->
            <mvc:mapping path="/*"/>
            <!-- adopt mvc:mapping Configure resources that do not need to be blocked. support wildcards. Multiple can be configured. -->
            <mvc:exclude-mapping path="/index.jsp"/>
            <!--Interceptor class fully qualified name-->
            <bean class="com.lwf.interceper.RootHanderIntercepter"/>
        </mvc:interceptor>
    </mvc:interceptors>

Upload file

Similar to servlet uploading and downloading files: servlet upload and download

Add pom dependency

<!-- add to commons-fileupload rely on -->
<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.3.2</version>
</dependency>

Add spring profile

<!-- Uploading of text pieces -->
<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!-- Maximum number of pieces allowed to be uploaded -->
 <property name="maxUploadSize">
 <value>104857600</value>
 </property>
 <!-- Set the maximum limit of the temporary part holder.
 This value is the threshold value. If it is lower than this value, it will be saved in memory. If it is lower than this value, it will be stored as a temporary file on the hard disk.
 -->
 <property name="maxInMemorySize">
 <value>4096</value>
 </property>
</bean>

code

Single file

/*
input type of is set to file
form The method of the form is set to post,
form The enctype of the form is set to multipart / form data, and data is transmitted in decimal form
*/
<form action="uploadFile" method="post" enctype="multipart/form-data">
 <input type="file" name="file" />
 <button type="submit"> Submit</button>
</form>


//controller
/**
* Uploading of text pieces
*/
@Controller
public class FileController {
 /**
 * Single piece upload
 * Use the Use MultipartFile object as a parameter to receive text pieces sent from the front end
 * @param file
 * @param request
 * @return
 */
 @RequestMapping("/uploadFile")
 public String uploadFile(@RequestParam("file") MultipartFile file,
 HttpServletRequest request){
 // Judge whether the piece is empty. If not, enter the piece upload operation corresponding to piece
 if (!file.isEmpty()) {
 try {
 // Get the path where the item is located (absolute path)
 String path = request.getServletContext().getRealPath("/");
  // Set the text record for storing uploaded text pieces
 File uploadFile = new File(path + "/upload");
 // Judge whether the document record exists. If it does not exist, create a new record
 if (!uploadFile.exists()) {
 // New record
 uploadFile.mkdir();
 }
 // Get the original name of the uploaded piece
 String originalName = file.getOriginalFilename();
 // Get the suffix of uploaded text pieces
 String suffix =
originalName.substring(originalName.lastIndexOf("."));
 // Through the milliseconds of the current time of the system, generate into random piece names (to avoid duplicate uploaded piece names)
 String fileName = System.currentTimeMillis() + suffix;
 // Upload text pieces (transfer text pieces to the specified item record)
 file.transferTo(new File(uploadFile, fileName));
 // Set successful domain object
 request.setAttribute("msg","text pieces uploaded successfully!");
 } catch (IOException e) {
 e.printStackTrace();
 // If an error is reported, set the domain object
 request.setAttribute("msg","Failed to upload text pieces!");
 }
 } else {
 // Uploaded file does not exist, set domain object
 request.setAttribute("msg","text piece does not exist, upload failed!");
 }
 return "result";
 }
}

Multiple files

<form action="uploadFiles" method="post" enctype="multipart/form-data">
 <input type="file" name="files" />
 <input type="file" name="files" />
 <input type="file" name="files" />
 <button type="submit"> Submit</button>
</form>

//controller
/**
 * Upload text pieces
 * @param file
 * @param request
 */
public void saveFile(MultipartFile file, HttpServletRequest request) {
 // Judge whether the piece is empty. If not, enter the piece upload operation corresponding to piece
 if (!file.isEmpty()) {
 try {
 // Get the path where the item is located (absolute path)
 String path = request.getServletContext().getRealPath("/");
 // Set the text record for storing uploaded text pieces
 File uploadFile = new File(path + "/upload");
 // Judge whether the document record exists. If it does not exist, create a new record
 if (!uploadFile.exists()) {
 // New record
 uploadFile.mkdir();
 }
 // Get the original name of the uploaded piece
 String originalName = file.getOriginalFilename();
 // Get the suffix of uploaded text pieces
 String suffix = originalName.substring(originalName.lastIndexOf("."));
 // Through the milliseconds of the current time of the system, generate into random piece names (to avoid duplicate uploaded piece names)
 String fileName = System.currentTimeMillis() + suffix;
 // Upload text pieces (transfer text pieces to the specified item record)
 file.transferTo(new File(uploadFile, fileName));
 // Set successful domain object
 request.setAttribute("msg","text pieces uploaded successfully!");
 } catch (IOException e) {
 e.printStackTrace();
 // If an error is reported, set the domain object
 request.setAttribute("msg","Failed to upload text pieces!");
 }
 } else {
 // Uploaded file does not exist, set domain object
 request.setAttribute("msg","text piece does not exist, upload failed!");
 }
}
/**
 * Multiple upload
 * @param files
 * @param request
 * @return
 */
@RequestMapping("/uploadFiles")
public String uploadFiles(@RequestParam("files") List<MultipartFile> files,
HttpServletRequest request) {
 // Judge whether the text piece set is empty
 if (files != null && files.size() > 0) {
 // Cyclic upload
 for (MultipartFile file:files) {
 // Upload text pieces
 saveFile(file, request);
 }
 }
 return "result";
}

SSM integration

Direct upper code

  1. Dependent on pom xml

    <dependencies>
     <!-- junit test -->
     <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
     <scope>test</scope>
     </dependency>
     <!-- spring Nuclear heart jar -->
     <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>5.2.4.RELEASE</version>
     </dependency>
     <!-- spring test jar -->
     <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-test</artifactId>
     <version>5.2.4.RELEASE</version>
     </dependency>
     <!-- spring jdbc -->
     <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-jdbc</artifactId>
     <version>5.2.4.RELEASE</version>
     </dependency>
     <!-- spring thing -->
     <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-tx</artifactId>
     <version>5.2.4.RELEASE</version>
     </dependency>
     <!-- aspectj Cut face programmed jar -->
     <dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjweaver</artifactId>
     <version>1.9.5</version>
     </dependency>
     <!-- c3p0 Connection pool -->
     <dependency>
     <groupId>com.mchange</groupId>
     <artifactId>c3p0</artifactId>
     <version>0.9.5.2</version>
     </dependency>
     <!-- mybatis -->
     <dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis</artifactId>
     <version>3.5.3</version>
     </dependency>
     <!-- add to mybatis And Spring Integrated core package -->
     <dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis-spring</artifactId>
     <version>2.0.3</version>
     </dependency>
     <!-- mysql Drive package -->
     <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>8.0.19</version>
     </dependency>
     <!-- day related to log printing jar -->
     <dependency>
     <groupId>org.slf4j</groupId>
     <artifactId>slf4j-log4j12</artifactId>
     <version>1.7.2</version>
     </dependency>
     <dependency>
     <groupId>org.slf4j</groupId>
     <artifactId>slf4j-api</artifactId>
     <version>1.7.2</version>
     </dependency>
     <!-- Sub plug-in -->
     <dependency>
     <groupId>com.github.pagehelper</groupId>
     <artifactId>pagehelper</artifactId>
     <version>5.1.10</version>
     </dependency>
     <!-- spring web -->
     <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-web</artifactId>
     <version>5.2.4.RELEASE</version>
     </dependency>
     <!-- spring mvc -->
     <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>5.2.4.RELEASE</version>
     </dependency>
     <!-- web servlet -->
     <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.0.1</version>
     </dependency>
     <!-- add to json rely on jar Package (pay attention to version) -->
     <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-core</artifactId>
     <version>2.10.0</version>
     </dependency>
     <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.10.0</version>
     </dependency>
     <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-annotations</artifactId>
     <version>2.10.0</version>
     </dependency>
     <!-- commons-fileupload -->
     <dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.2</version>
     </dependency>
    </dependencies>
    
    
     <build>
     <finalName>ssm</finalName>
     <!--
     Maven Xiang Yi:If the source code(src/main/java)existence xml,properties,tld Etc
     Maven By default, this file will not be automatically compiled to the output record,If you want to compile the xml properties tld Etc
     Explicit configuration required resources label
     -->
     <resources>
     <resource>
     <directory>src/main/resources</directory>
     </resource>
     <resource>
     <directory>src/main/java</directory>
     <includes>
     <include>**/*.xml</include>
     <include>**/*.properties</include>
     <include>**/*.tld</include>
     </includes>
     <filtering>false</filtering>
     </resource>
     </resources>
     <plugins>
     <!-- Compiling environment plug-ins -->
     <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-compiler-plugin</artifactId>
     <version>2.3.2</version>
     <configuration>
     <source>1.8</source>
     <target>1.8</target>
     <encoding>UTF-8</encoding>
     </configuration>
     </plugin>
     <!-- jetty plug-in unit -->
     <plugin>
     <groupId>org.eclipse.jetty</groupId>
     <artifactId>jetty-maven-plugin</artifactId>
     <version>9.4.27.v20200227</version>
     <configuration>
     <scanIntervalSeconds>10</scanIntervalSeconds>
     <!-- Setting end mouth -->
     <httpConnector>
     <port>8080</port>
     </httpConnector>
     <!-- Set item item path -->
     <webAppConfig>
     <contextPath>/ssm</contextPath>
     </webAppConfig>
     </configuration>
     </plugin>
     </plugins>
     </build>
    
  2. web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="3.0"
     xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
     <!-- start-up spring container-->
     <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:spring.xml</param-value>
     </context-param>
     <!-- Set up listeners -->
     <listener>
     <listenerclass>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
    
     <!-- Code filtering utf-8 -->
     <filter>
     <description>char encoding filter</description>
     <filter-name>encodingFilter</filter-name>
     <filterclass>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>encodingFilter</filter-name>
     <url-pattern>/*</url-pattern>
     </filter-mapping>
     <!-- servlet Request distributor -->
     <servlet>
     <servlet-name>springMvc</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servletclass>
     <init-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:servlet-context.xml</param-value>
     </init-param>
     <!-- Indicates that the Servlet -->
     <load-on-startup>1</load-on-startup>
     </servlet>
     <servlet-mapping>
     <servlet-name>springMvc</servlet-name>
     <!-- This is an intercept request, "/"Delegate intercepts all requests,"*.do"Block all.do request -->
     <url-pattern>/</url-pattern>
     <!--<url-pattern>*.do</url-pattern>-->
     </servlet-mapping>
    </web-app>
    
  3. servlet-context.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc.xsd
     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">
     <!-- Turn on the scanner -->
     <context:component-scan base-package="com.lwf.controller" />
     <!-- mvc Annotation driven and added json support holding -->
     <mvc:annotation-driven>
     <mvc:message-converters>
     <!-- Process when the returned information is a string -->
     <bean
    class="org.springframework.http.converter.StringHttpMessageConverter"/>
     <!-- Convert objects to json object -->
     <bean
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConve
    rter"/>
     </mvc:message-converters>
     </mvc:annotation-driven>
    
     <!-- Make use default Servlet To respond to static text parts -->
     <mvc:default-servlet-handler/>
    
     <!-- Configure view parser -->
     <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"
     id="internalResourceViewResolver">
     <!-- Prefix: in WEB-INF item recorded jsp item record -->
     <property name="prefix" value="/WEB-INF/jsp/"/>
     <!-- Suffix: in.jsp Resources at the end -->
     <property name="suffix" value=".jsp"/>
     </bean>
    
     <!-- Uploading of text pieces -->
     <bean id="multipartResolver"
    
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <!-- Maximum number of pieces allowed to be uploaded -->
     <property name="maxUploadSize">
     <value>104857600</value>
     </property>
     <!--
     Set the maximum limit of the temporary part holder.
     This value is the threshold value. If it is lower than this value, it will be saved in memory. If it is lower than this value, it will be stored as a temporary file on the hard disk.
     -->
     <property name="maxInMemorySize">
     <value>4096</value>
     </property>
     </bean>
    </beans>
    
  4. spring.xml

    <?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:aop="http://www.springframework.org/schema/aop"
    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/aop
     http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx.xsd">
     <!-- Scan basic package -->
     <context:component-scan base-package="com.lwf" >
     <!-- context:exclude-filter Tag: exclude scanning (filtering) of an annotation controller Layer)
    -->
     <context:exclude-filter type="annotation"
    
    expression="org.springframework.stereotype.Controller" />
     </context:component-scan>
     <!-- load properties Configuration text parts -->
     <context:property-placeholder location="classpath:db.properties" />
     <!-- aop -->
     <aop:aspectj-autoproxy />
     <!-- to configure c3p0 data source -->
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
     <property name="driverClass" value="${jdbc.driver}"></property>
     <property name="jdbcUrl" value="${jdbc.url}"></property>
     <property name="user" value="${jdbc.username}"></property>
     <property name="password" value="${jdbc.password}"></property>
     </bean>
     <!-- Configure transaction manager -->
     <bean id="txManager"
    
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="dataSource"></property>
     </bean>
     <!-- Set things up for enhancement -->
     <tx:advice id="txAdvice" transaction-manager="txManager">
     <tx:attributes>
     <tx:method name="add*" propagation="REQUIRED" />
     <tx:method name="insert*" propagation="REQUIRED" />
     <tx:method name="update*" propagation="REQUIRED" />
     <tx:method name="delete*" propagation="REQUIRED" />
     </tx:attributes>
     </tx:advice>
     <!-- aop Switch configuration -->
     <aop:config>
     <aop:pointcut id="servicePointcut"
     expression="execution(* com.lwf.service..*.*(..))"
    />
     <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut" />
     </aop:config>
     <!-- to configure sqlSessionFactory -->
     <bean id="sqlSessionFactory"
    class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="dataSource" ref="dataSource"></property>
     <property name="configLocation" value="classpath:mybatis.xml" />
     <property name="mapperLocations"
    value="classpath:mappers/*.xml" />
     </bean>
     <!-- Configure scanner -->
     <bean id="mapperScanner"
    class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <!-- scanning com.xxxx.ssm.dao This package and all mapped connection classes under its package -->
     <property name="basePackage" value="com.lwf.mapper" />
     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"
    />
     </bean>
    </beans>
    
  5. mybatis.xml

    <?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>
     <typeAliases>
     <package name="com.lwf.pojo"/>
     </typeAliases>
     <plugins>
     <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
     </plugins>
    </configuration>
    
  6. db.properties

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssm?
    useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    jdbc.username=root
    jdbc.password=root
    
  7. log4j.properties

    log4j.rootLogger=DEBUG, Console
    # Console
    log4j.appender.Console=org.apache.log4j.ConsoleAppender
    log4j.appender.Console.layout=org.apache.log4j.PatternLayout
    log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
    log4j.logger.java.sql.ResultSet=INFO
    log4j.logger.org.apache=INFO
    log4j.logger.java.sql.Connection=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    
  8. structure

    • main
      • java
        • com
          • lwf
            • controller
            • service
            • mapper
            • pojo
      • resources
        • spring.xml
        • servlet-context.xml
        • mybatis.xml
        • db.properties
        • log4j.properties
      • webapp
        • WEB-INF
          • web.xml
          • jsp

Tags: Java Spring RESTful

Posted by Crimpage on Sat, 30 Jul 2022 22:12:41 +0530