SpringMVC study notes----

SpringMVC study notes----

1. Getting started with SpringMVC basics, creating a HelloWorld program

Original address: www.cnblogs.com/sunniest/p/...

1. 1. import the jar package required by SpringMVC.

2. Add the configuration of SpringMVC 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 > < The servlet-Mapping > < the servlet-name > SpringMVC </the servlet-name > < URL-pattern >/</URL-pattern > </the servlet-Mapping > copy the code

3. Add springmvc-servlet.xml configuration file under src

<?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-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 = "/the WEB-INF/JSP/"/> <-! suffix -> < Property name = "suffix" value = ".jsp"/> </the bean > </Beans > copy the code

4. Create a folder named jsp under the WEB-INF folder to store jsp views. Create a hello.jsp and add "Hello World" to the body.

5. Create a package and Controller, as shown below

6. Write Controller code

@Controller @RequestMapping("/mvc") public class mvcController { @RequestMapping("/hello") public String hello(){ return "hello"; } } Copy code

7. Start the server, type http://localhost:8080/project name/mvc/hello

2. configuration analysis

1. Dispatcherservlet

DispatcherServlet is the front controller, which is configured in the web.xml file. To intercept matching requests, the Servlet interception matching rules must be defined by yourself. The intercepted requests are distributed to the target Controller for processing according to the corresponding rules. This is the first step in configuring Spring MVC.

2.InternalResourceViewResolver

View name resolver

3. Notes appearing above

@Controller is responsible for registering a bean to the spring context

The @RequestMapping annotation specifies which URL requests can be processed by the controller

3. SpringMVC commonly used annotations

@Controller

Responsible for registering a bean to the spring context
@RequestMapping

The annotation specifies which URL requests can be processed by the controller
@RequestBody

This annotation is used to read the body part data of the Request request, use the default configuration of the HttpMessageConverter to parse, and then bind the corresponding data to the object to be returned, and then bind the object data returned by the HttpMessageConverter to the method in the controller Parameter

@ResponseBody

 This annotation is used to convert the object returned by the Controller method into a specified format through an appropriate HttpMessageConverter, and then write it to the body data area of the Response object

@ModelAttribute 

Use the @ModelAttribute annotation on the method definition: Spring MVC will call the methods marked with @ModelAttribute at the method level one by one before calling the target processing method

Use the @ModelAttribute annotation before entering the method parameters: you can get the object from the hidden model data from the hidden object, and then bind the request parameter-to the object, and then pass in the input parameter to add the method input parameter object to In the model 

@RequestParam

Use @RequestParam at the input parameter of the processing method to pass the request parameters to the request method

@PathVariable

Bind URL placeholder to
input parameter @ExceptionHandler

Annotate to the method, the method will be executed when an exception occurs
@ControllerAdvice

Make a Contoller a global exception handling class. The method annotated with the @ExceptionHandler method in the class can handle all exceptions in the Controller

4. automatic matching parameters

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

5. 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 code

2. Write a method in the Controller

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

6. use InitBinder to process Date type 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 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 code

The front desk can get "p" in the Request field

8. use Ajax to call

//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 code

The front desk is called with the following Jquery code

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

9. use the redirect method to process the request in the Controller

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

10. File upload

1. Need to import two jar packages

2. Join in the SpringMVC configuration file

<!-- upload settings --> < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > < property name = "maxUploadSize" value = "102400000" > </property > </bean > copy 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 code

4. Form from the front desk

< Form Action = "MVC/Upload" Method = "POST" the enctype = "multipart/form-Data" > < INPUT type = "File" name = "File" > < br > < INPUT type = "Submit" value = " submit" > </form > Copy code

11. Use the @RequestParam annotation to specify the name of the parameter

@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 code

Twelve, RESTFul style 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 code

2. The form form sends put and delete requests

Configure 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 code

In the foreground, you can use the following code to generate a request

< 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 code

Thirteen, return a string in json format

1. Import the following jar package

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 code

14. Exception handling

1. Handling 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 code

2. Handling 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 code

3. Another way to handle global exceptions

Configure 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 > </The props > </Property > </the bean > copy the code

error is the error page

15. 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 code

2. Configure in the SpringMVC configuration file

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

3. Interceptor execution order

16. Form validation (using Hibernate-validate) and internationalization

1. Import the jar package required by Hibernate-validate

(Unchecked, do not import)

2. Write the entity class User and add verification 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 code

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

3. Use SpringMVC's form form in jsp

< Form: form Action = "form/the 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 code

ps:path corresponds to name

4. Code in 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 code

ps:

1. Because the modelAttribute attribute is used in jsp, there must be a "user" in the request field.

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

3. Return to the original page and the error message will be echoed, and the form will also be echoed

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 code

Configure 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 code

6. International display

Add locale_zh_CN.properties under src

username=Account password=password Copy code

add in locale.properties

username=user name password=password Copy 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

<-! The JSP the make CAN BE Page visited -> < MVC: View-Controller path = "/the locale" View-name = "the locale"/> copy the code

Let locale.jsp be directly accessible under WEB-INF

Finally, visit locale.jsp, switch the browser language, you can see the language of the account and password is also switched

Seventeen, the finale-integrating SpringIOC and SpringMVC

1. Create a test.SpringMVC.integrate package to demonstrate integration and create various types

2.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 code

3.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 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 code

5. Spring configuration file

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

<?xml version="1.0" encoding="UTF-8"?> < 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 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 </name-param > < param-value > CLASSPATH: the applicationContext.xml </param-value > </context-param > copy the code

6. Carry out some configuration in SpringMVC to prevent SpringMVC and SpringIOC from overlapping the management of the same object

<!-- 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: the include filter- type = " Annotation " expression The = " org.springframework.web.bind.annotation.ControllerAdvice "/> </context: Component-Scan > copy the code

 

Eighteen, SpringMVC detailed operation flowchart

Nineteen, SpringMVC operating principle

 

1. The client request is submitted to DispatcherServlet
2. The DispatcherServlet controller queries one or more HandlerMappings to find the Controller that processes the request
3. DispatcherServlet submits the request to the Controller
4. After the Controller calls the business logic for processing, it returns to ModelAndView
5. DispatcherServlet queries one Or multiple ViewResoler view resolvers, find the view specified by ModelAndView
6. The view is responsible for displaying the results to the client

 

Twenty, the difference between SpringMVC and struts2

1. Springmvc is developed based on methods, and struts2 is developed based on classes. springmvc maps the URL and the method in the controller. After the mapping is successful, springmvc generates a Handler object, which contains only one method. The method execution ends, and the formal parameter data is destroyed. Controller development of springmvc is similar to web service development.
2. Springmvc can be used for singleton development, and singleton development is recommended. Struts2 receives parameters through class member variables. Singletons cannot be used, but multiple instances can only be used.
3. After actual testing, struts2 is slow because of the use of struts tags. If you use struts, it is recommended to use jstl.