Start with SpringMVC basics. Create a HelloWorld program

The original address: www.cnblogs.com/sunniest/p/…

1. First, import the JAR packages required by SpringMVC.

2. Add the SpringMVC configuration in the web. XML configuration file

  <! --configure the setting of springmvcDispatcherServlet and configure the mapping-->
  <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-servlet.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>
Copy the code

3. Add the springmVC-servlet. XML configuration file under SRC


      
<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-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">                    

    <! -- scan the package and the sub package -->
    <context:component-scan base-package="test.SpringMVC"/>

    <! -- don't handle the static resource -->
    <mvc:default-servlet-handler />

    <! -- if you use annotation you must configure following setting -->
    <mvc:annotation-driven />
    
    <! -- configure the InternalResourceViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            id="internalResourceViewResolver">
        <! -- prefix -- -- >
        <property name="prefix" value="/WEB-INF/jsp/" />
        <! - the suffix - >
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
Copy the code

4. Create a folder named JSP in the WEB-INF folder to hold the JSP view. Create a hello.jsp and add “Hello World” to the body.

5. Create the package and Controller, as shown below

6. Write Controller code

@Controller
@RequestMapping("/mvc")
public class mvcController {

    @RequestMapping("/hello")
    public String hello(){        
        return "hello";
    }
}
Copy the code

7. Start the server and type http://localhost:8080/ project name/MVC /hello

2. Configuration parsing

1.Dispatcherservlet

The DispatcherServlet is the front controller configured in the web.xml file. The Servlet intercepts matched requests. The Servlet intercepts matched requests by defining its own rules. The intercepted requests are distributed to the target Controller for processing according to the corresponding rules, which is the first step in configuring Spring MVC.

2.InternalResourceViewResolver

View name resolver

3. Notes that appear above

The @Controller is responsible for registering a bean into the Spring context

The @requestMapping annotation specifies which URL requests the controller can handle

Common annotations for SpringMVC

@Controller

Is responsible for registering a bean in the Spring context @requestMapping

The annotation specifies which URL requests the controller can handle @requestBody

This annotation is used to read the body part of the Request and is parsed using the default HttpMessageConverter configuration. The corresponding data is then bound to the object to be returned, and the object data returned by HttpMessageConverter is bound to the parameters of the controller method

@ResponseBody

This annotation is used to write the object returned by the Controller’s methods to the body data section of the Response object after converting it to the specified format via the appropriate HttpMessageConverter

@ModelAttribute

Use the @ModelAttribute annotation on method definitions: Spring MVC calls the methods labeled @ModelAttribute at the method level one by one before calling the target processing methods

Use the @modelAttribute annotation before the method input parameter: you can get the object from the implied object from the implied model data, bind the request parameters-to the object, and pass in the input parameter to add the method input object to the model

@RequestParam

Using @requestParam in the handler method entry can pass the request parameters to the request method

@PathVariable

Bind the URL placeholder to the @ExceptionHandler input argument

Annotation to a method to execute @controllerAdvice when an exception occurs

Make a Contoller a global ExceptionHandler class annotated with the @exceptionhandler method to handle all Controller exceptions

Four, automatic matching parameters

    //match automatically
    @RequestMapping("/person")
    public String toPerson(String name,double age){
        System.out.println(name+" "+age);
        return "hello";
    }
Copy the code

Five, automatic packing

1. Write a Person entity class

package test.SpringMVC.model;

public class Person {
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    private String name;
    private int age;
    
}
Copy the code

2. Write methods in Controller

    //boxing automatically
    @RequestMapping("/person1")
    public String toPerson(Person p){
        System.out.println(p.getName()+" "+p.getAge());
        return "hello";
    }
Copy the code

Use InitBinder to handle Date parameters

    //the parameter was converted in initBinder
    @RequestMapping("/date")
    public String date(Date date){
        System.out.println(date);
        return "hello";
    }
    
    //At the time of initialization,convert the type "String" to type "date"
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
                true));
    }
Copy the code

7. Pass parameters to the front desk

    //pass the parameters to front-end
    @RequestMapping("/show")
    public String showPerson(Map<String,Object> map){
        Person p =new Person();
        map.put("p", p);
        p.setAge(20);
        p.setName("jayjay");
        return "show";
    }
Copy the code

The foreground can get “P” in the Request field

Use Ajax calls

    //pass the parameters to front-end using ajax
    @RequestMapping("/getPerson")
    public void getPerson(String name,PrintWriter pw){
        pw.write("hello,"+name);        
    }
    @RequestMapping("/name")
    public String sayHello(){
        return "name";
    }
Copy the code

The foreground is called with the following Jquery code

          $(function(){
              $("#btn").click(function(){
                  $.post("mvc/getPerson",{name:$("#name").val()},function(data){
                      alert(data);
                  });
              });
          });
Copy the code

Redirect requests in Controller

    //redirect 
    @RequestMapping("/redirect")
    public String redirect(){
        return "redirect:hello";
    }
Copy the code

X. File upload

1. Two JAR packages need to be imported

2. Add it to the SpringMVC configuration file

    <! -- upload settings -->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="102400000"></property>
    </bean>
Copy the code

3. Method code

    @RequestMapping(value="/upload",method=RequestMethod.POST)
    public String upload(HttpServletRequest req) throws Exception{
        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
        MultipartFile file = mreq.getFile("file");
        String fileName = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");        
        FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/")+
                "upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.')));
        fos.write(file.getBytes());
        fos.flush();
        fos.close();
        
        return "hello";
    }
Copy the code

4. Foreground form

      <form action="mvc/upload" method="post" enctype="multipart/form-data">
          <input type="file" name="file"><br>
          <input type="submit" value="submit">
      </form>
Copy the code

Specify the name of the parameter using the @requestParam annotation

@Controller @RequestMapping("/test") public class mvcController1 { @RequestMapping(value="/param") public String testRequestParam(@RequestParam(value="id") Integer id, @RequestParam(value="name")String name){ System.out.println(id+" "+name); return "/hello"; }}Copy the code

RESTFul SringMVC

1.RestController

@Controller @RequestMapping("/rest") public class RestController { @RequestMapping(value="/user/{id}",method=RequestMethod.GET) public String get(@PathVariable("id") Integer id){ System.out.println("get"+id); return "/hello"; } @RequestMapping(value="/user/{id}",method=RequestMethod.POST) public String post(@PathVariable("id") Integer id){ System.out.println("post"+id); return "/hello"; } @RequestMapping(value="/user/{id}",method=RequestMethod.PUT) public String put(@PathVariable("id") Integer id){ System.out.println("put"+id); return "/hello"; } @RequestMapping(value="/user/{id}",method=RequestMethod.DELETE) public String delete(@PathVariable("id") Integer id){ System.out.println("delete"+id); return "/hello"; }}Copy the code

2. The form sends put and DELETE requests

Configure it in web.xml

  <! -- configure the HiddenHttpMethodFilter,convert the post method to put or delete -->
  <filter>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <url-pattern>/ *</url-pattern>
  </filter-mapping>
Copy the code

The request can be generated in the foreground with the following code

    <form action="rest/user/1" method="post">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="put">
    </form>
    
    <form action="rest/user/1" method="post">
        <input type="submit" value="post">
    </form>
    
    <form action="rest/user/1" method="get">
        <input type="submit" value="get">
    </form>
    
    <form action="rest/user/1" method="post">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="delete">
    </form>
Copy the code

Return a string in json format

1. Import the following JAR packages

2. Method code

@Controller @RequestMapping("/json") public class jsonController { @ResponseBody @RequestMapping("/user") public User get(){ User u = new User(); u.setId(1); u.setName("jayjay"); u.setBirth(new Date()); return u; }}Copy the code

14. Exception handling

1. Handle local exceptions (in Controller)

    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception ex){
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("exception", ex);
        System.out.println("in testExceptionHandler");
        return mv;
    }
    
    @RequestMapping("/error")
    public String error(){
        int i = 5/0;
        return "hello";
    }
Copy the code

2. Handle global exceptions (all Controllers)

@ControllerAdvice public class testControllerAdvice { @ExceptionHandler public ModelAndView exceptionHandler(Exception ex){ ModelAndView mv = new ModelAndView("error"); mv.addObject("exception", ex); System.out.println("in testControllerAdvice"); return mv; }}Copy the code

3. Another way to handle global exceptions

Configured in the SpringMVC configuration file

    <! -- configure SimpleMappingExceptionResolver -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.ArithmeticException">error</prop>
            </props>
        </property>
    </bean>
Copy the code

Error is the error page

Set up a custom interceptor

1. Create a MyInterceptor class and implement the HandlerInterceptor interface

public class MyInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { System.out.println("afterCompletion"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { System.out.println("postHandle"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { System.out.println("preHandle"); return true; }}Copy the code

2. Configure it in the SpringMVC configuration file

    <! -- interceptor setting -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/mvc/**"/>
            <bean class="test.SpringMVC.Interceptor.MyInterceptor"></bean>
        </mvc:interceptor>        
    </mvc:interceptors>
Copy the code

3. Execution sequence of interceptors

Form validation (using hibernate-validate) and internationalization

1. Import the JAR package required by hibernate-validate

(Import is not selected)

2. Write the entity class User with validation annotations

public class User {
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
    }    
    private int id;
    @NotEmpty
    private String name;

    @Past
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;
}
Copy the code

Ps: @past indicates that the time must be a Past value

3. Use the SpringMVC form form in JSP

    <form:form action="form/add" method="post" modelAttribute="user">
        id:<form:input path="id"/><form:errors path="id"/><br>
        name:<form:input path="name"/><form:errors path="name"/><br>
        birth:<form:input path="birth"/><form:errors path="birth"/>
        <input type="submit" value="submit">
    </form:form> 
Copy the code

Ps: the path corresponding to the name

4. The code in the Controller

@Controller @RequestMapping("/form") public class formController { @RequestMapping(value="/add",method=RequestMethod.POST) public String add(@Valid User u,BindingResult br){ if(br.getErrorCount()>0){ return "addUser"; } return "showUser"; } @RequestMapping(value="/add",method=RequestMethod.GET) public String add(Map<String,Object> map){ map.put("user",new User()); return "addUser"; }}Copy the code

ps:

1. Because the JSP uses the modelAttribute attribute, there must be a “user” in the request field.

2.@Valid means to validate parameters against annotations marked on the entity

3. If the error message is displayed, the form is also displayed

5. Error message customization

Add locale.properties in the SRC directory

NotEmpty.user.name=name can't not be empty
Past.user.birth=birth should be a past value
DateTimeFormat.user.birth=the format of input is wrong
typeMismatch.user.birth=the format of input is wrong
typeMismatch.user.id=the format of input is wrong
Copy the code

Configured in the SpringMVC configuration file

    <! -- configure the locale resource -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="locale"></property>
    </bean>
Copy the code

6. Internationalized display

Add locale_zh_cn.properties under SRC

Username = account password= passwordCopy the code

Add a locale. The properties

username=user name
password=password
Copy the code

Create a locale.jsp

  <body>
    <fmt:message key="username"></fmt:message>
    <fmt:message key="password"></fmt:message>
  </body>
Copy the code

Configure in SpringMVC

    <! -- make the jsp page can be visited -->
    <mvc:view-controller path="/locale" view-name="locale"/>
Copy the code

Make locale.jsp directly accessible in WEB-INF

Finally, go to locale.jsp and switch the browser language. You can see that the language for your account and password has also been changed

The grand finale — integrating SpringIOC and SpringMVC

1. Create a test.SpringMVC. Integrate package to demonstrate integration and create various categories

2. The User entity class

public class User {
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
    }    
    private int id;
    @NotEmpty
    private String name;

    @Past
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;
}
Copy the code

3. The UserService class

@Component
public class UserService {
    public UserService(){
        System.out.println("UserService Constructor...\n\n\n\n\n\n");
    }
    
    public void save(){
        System.out.println("save");
    }
}
Copy the code

4.UserController

@Controller @RequestMapping("/integrate") public class UserController { @Autowired private UserService userService; @RequestMapping("/user") public String saveUser(@RequestBody @ModelAttribute User u){ System.out.println(u); userService.save(); return "hello"; }}Copy the code

5.Spring configuration file

Create the SpringIOC configuration file applicationContext.xml in the SRC directory


      
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "
        xmlns:util="http://www.springframework.org/schema/util"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"    
        >
    <context:component-scan base-package="test.SpringMVC.integrate">
        <context:exclude-filter type="annotation" 
            expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" 
            expression="org.springframework.web.bind.annotation.ControllerAdvice"/>        
    </context:component-scan>
    
</beans>
Copy the code

Add configuration in web.xml

  <! -- configure the springIOC -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
Copy the code

6. Do some configuration in SpringMVC to prevent SpringMVC and SpringIOC from managing the same object together

<! -- scan the package and the sub package -->
    <context:component-scan base-package="test.SpringMVC.integrate">
        <context:include-filter type="annotation" 
            expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" 
            expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
Copy the code

 

Detailed operation flow chart of SpringMVC

How SpringMVC works

 

1. The client requests to be sent to DispatcherServlet 2. Query one or more HandlerMapping by the DispatcherServlet controller, 3. The DispatcherServlet submits the request to the Controller. 4. DispatcherServlet queries one or more ViewResoler view parsers and finds the view specified by ModelAndView. The view is responsible for displaying the results to the client

 

Differences between SpringMVC and Struts2

1. Springmvc based method development, Struts2 based class development. Springmvc maps urls to methods in the Controller. After the mapping is successful, SpringMVC generates a Handler object that contains only one method. Method is finished, and the data is destroyed. Springmvc’s Controller development is similar to Web Service development. 2. Springmvc can do singleton development, and it is recommended to use singleton development. Struts2 receives parameters through the member variables of the class. 3, After the actual test, Struts2 is slow because of the use of Struts tags. If you use Struts, it is recommended to use JSTL.