01_Springmvc learning notes

1. SSM integration

Ideas: MVC three layer architecture, 1. dao:mybatis 1.1. mybatis core configuration file: sqlMapConfig.xml - configure the package name of the Mapper mapping file as an alias. 1.2. applicationContext_dao.xml configuration data source, sqlSessionFactory (mybatis session, Mapper plant) configuration interface basepackage (SQL configuration to dynamic agent development, according to the mybatis mybatis interface, we only need to provide the interface of mapper and 1.3.) above 1.2 is equivalent to the completion of the integration of service 2. spring and mybatis: spring 2.1. applicationContext_service.xml: service layer configuration note: < context:component-scan base-package= scanning; com.itdream.ssm.service /> 2.2. applicationContext_tx.xml: spring administration 3. Web: springmvc 3.1. springmvc.xml: 1. controller < 2. scanning configuration notes;! -- configuration mapping and annotation driven, HttpMappingHandlerMapping and HttpMappingHandlerAdapter instead of the default selection Adapter --> < mvc:annotation-driven/> 3. configuration view parser, simplified controller layer, returning the page write view < bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver" > < property; name= "prefix" value= "/WEB-INF/jsp/" /> < property; name= "suffix" value= ".Jsp" /> < /bean> web.xml 4. servlet the container (Tomcat) and < spring boot loader, front controller configuration of springmvc; the core of --spring! --> < context-param> monitor; < param-name> contextConfigLocation< /param-name> < param-value> classpath:resources/spring/applicationContext-*.xml< /param-value> < /context-param> < Li Stener> < listener-class> org.springframework.web.context.ContextLoaderListener< /listener-class> < /listener> < -->! --springmvc in the front controller; < servlet> < servlet-name> springmvc< < servlet-class> servlet-name> org.springframework.web.servlet.DispatcherServlet< /servlet-class> < init-param> < param-name> contextConfigLocation< /param-name> < param-value> classpath:resources/ spring/springmvc.xml< /param-value> < /init-param> < /servlet> < servlet-mapping> < servlet-name> springmvc< /servlet-name> < url-pattern> *.action< /url-pattern> & Lt; /servlet-mapping>

Here, SpringMVC has three ways of intercepting URL requests:

1. / 2. / JSP to intercept all, including intercept all does not include JSP 3., *.action only to intercept the.Action at the end of the request, not intercept static resources and other resources if using second interception, but also the release of static resources such as js/jquery/css, can be configured in springmvc.xml: <! -- static resource mapping so, static resource is not intercepted location: physical path mapping resource file: virtual path --> mapping; < mvc:resources mapping= "/js/**" location= "/js/" />

2. springmvc usage

2.1 @RequestMapping

Different processor mapping rules can be defined through the @RequestMapping annotation.

1.URL path mapping (written URL mapped to the corresponding method based on the method, value), is the value of the array can be multiple URL mapping to the same method, comma separated @RequestMapping (value= item) or @RequestMapping ("/item") @RequestMapping ("/item/itemList.action" public ModelAndView (findItemList) {/ / commodity data query) List< Item> list = this.itemService.queryItemList (ModelAndView); / / create a logical view of ModelAndView, set MV = new ModelAndView ("itemList"); / / commodity data into the model of mv.addObject (itemList, list); return MV;} 2. written in class, narrow path such as @RequestMapping ("/item") public class itemController is equivalent to all the RequestMapping method before the addition of /item prefix, it can be used to smoke Take or unify the path prefix 3., and the method is qualified to qualify the GET method @RequestMapping (method = RequestMethod.GET) to qualify the POST method @RequestMapping (method = RequestMethod.POST)

The return value of the 2.2 Controller method

1. returns the ModelAndView controller method, defines the ModelAndView object, and returns the object where the model data can be added, specifying the view. 2. returns the String (official recommendation) controller method returns a string that specifies the logical view name and resolves it to the physical view address through the view parser. Model.addAttribbute data using Model model (k, V) stored in the request domain in addition: the return of String also supports and redirect requests, for example: return "redirect:/itemList.action"; "return forward: /itemEdit.action? Id=" +id; 3. return to void in the Controller method parameter can be defined on the request and response, use request or response to specify the response results: suitable for Ajax access request

2.3 springmvc solves the post request garbled question

Add the interceptor in web.xml, intercept all requests, will carry the parameter into UTF-8 format < to solve the garbage problem! Post --> < filter> < filter-name> encoding< /filter-name> < filter-class> org.springframework.web.filter.CharacterEncodingFilter< /filter-class> <! -- set the encoding parameter is UTF-8--> < init-param> < param-name> encoding< /param-name> < param-value> UTF-8< /param-value> < /init-param> < /filter> < filter-mapping> < filter-name> encoding< /filter-name> < url-pattern> /*< /url-pattern> < /filter-mapping> if you want to solve the garbage problem of GET requests:
01_Springmvc learning notes

Custom parameter converter in 2.4 springmvc

Since date data comes in many formats, springmvc cannot convert strings into date types. So need a custom parameter binding front controller after receiving the request, find the processor adapter note form, method of RequestMapping markers of adaptation, and the method of the parameter in the parameter binding. You can customize the converter Converter on the springmvc processor adapter for parameter binding. < is generally used; mvc:annotation-driven/> annotation driver loads the processor adapter and can be configured on this tag. 1. write custom converter Converter Converter< S, T> //S:source, the need to convert the type of source //T:target, need to change the target type public class DateConverter implements Converter< String, Date> public Date convert {@Override (String s) {if (StringUtils.isEmpty (s)) {return null} try {DF = DateFormat; new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); return df.parse (s);} catch (ParseException E) {e.printStackTrace (return null);};}} 2. configured in the springmvc.xml custom Converter < --> <! --conversion-service: custom converter; mvc:annotation-driven conversion-service=; /> < "conversionService" - turn! Exchanger configuration of --> < bean id= "conversionService" class= "org.springframework.format.support.FormattingConversionServiceFactoryBean" > < property; name= "converters" > < set> < bean class= "com.itdream.ssm.converter.DateConverter" /> < /set> < /property> < /bean>

Second ways: (understand)

<! -- --> < bean annotation adapter; class=; org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter > < property; name= "webBindingInitializer" ref= "customBinder" > < /property> < bean> <! -- custom webBinder --> < bean; id= "customBinder" class= "org.springframework.web.bind.support.ConfigurableWebBindingInitializer" > < property name= "conversionService" ref= "conversionService" /> < /bean> <! -- --> < bean converter configuration;; id= "conversionService" class= "org.springframework.format.support.FormattingConversionServiceFactoryBean" > < property; name= "converters" > < set> < bean class = "cn.itcast.springmvc.convert.DateConverter" /> < < /property> /set> < /bean> note: this method requires the independent configuration of processor mapper and adapter; no longer uses < mvc:annotation-driven/>

3. springmvc advanced knowledge points

3.1 custom exception handler

The Dao, service, and controller of the system are thrown up through the throws Exception, and finally the exception handler is handled by the springmvc front-end controller, as follows:

01_Springmvc learning notes

To distinguish between different exceptions, we usually differentiate between the exception types, where we create a custom system exception.
if controller, service, and Dao throw such exceptions, the exception information is expected to be processed by the system.

Public class CustomerException extends / / custom exception {Exception public CustomerException (String message) {super}} (message);

Next, you define the custom exception handler:

* / * * * Created by Administrator custom exception handler on 2017/8/29. / public class MyEceptionResolver implements HandlerExceptionResolver public ModelAndView resolveException {@Override (HttpServletRequest request, HttpServletResponse response, Object o, Exception E) {ModelAndView MAV = new (ModelAndView); / / according to the definition of friendly message abnormal different if (e instanceof CustomerException) {mav.addObject ("errorMsg" (e.getMessage));} else {mav.addObject ("errorMsg", "unknown exception");} e.printStackTrace (WEB-INF/jsp/error.jsp mav.setViewName); / / page Jump exception ("error"); return MAV;}}

Finally, configure the custom exception handler in springmvc.xml, and then hit the exception, and the front-end controller is handed over to the exception handler:

< - - configure the global custom exception handler --> < bean id=, myEceptionResolver, class=, com.itdream.ssm.exception.MyEceptionResolver, />

3.2 springmvc upload pictures

Picture upload need to be stored on the local disk, the virtual path configuration of the tomcat, the Tomcat changes in config/server.xml: DocBase: Path: the true path of the virtual path < Context docBase= "D:/upload/img" path= "/img" reloadable= "false" /> I use idea can also be directly in the configuration of IDE tools: source + extra. Select the real path to map, right ApplicationContext fill in the virtual path
01_Springmvc learning notes
After the configuration, but also need to tick in server: check here, idea can also directly access the home page of tomcat, or else not
01_Springmvc learning notes

Join the jar package:

01_Springmvc learning notes

Configuring the file upload parser in springmvc.xml:

<! -- configuration file upload parser, ID must be set to multipartResolver--> < bean; id= "multipartResolver" class= "org.springframework.web.multipart.commons.CommonsMultipartResolver" > <! -- maximum size configuration upload file: 50M: 1*1024*1024*50--> < property; name= "maxUploadSize" value= "52428800" /> < /bean>

Also, the front page needs to be met: enctype=, “multipart/form-data.”

Also, the input tag type is file, and the name is consistent with the parameter names received by the controller

Controller to achieve file upload, upload the picture file to the local server, and save the path to the database:

Provide / parameters MultipartFile, name @RequestMapping and the front of the parameter name ("/updateItem.action") public String updateItem (Items item, MultipartFile pictureFile throws IOException) {/ / get the file name String originalFilename = pictureFile.getOriginalFilename (original); / / get the suffix String ext = FilenameUtils.getExtension (originalFilename); / / get the random file name String name = UUID UUID.randomUUID (.ToString) (.ReplaceAll) ("-", "") (.ToUpperCase); String filename = "/img/" + name + "." //save to + ext; disk upload saved to the local server (pictureFile.transferTo new File ("D:/upload/img/" + name + "" + ext)); //save to database save the path to the item.setPic database (filename); itemsService.up DateItems (item); return "redirect:/item/list.action";}

3.3 JSON data interaction

Join the jar package:

01_Springmvc learning notes
The @RequestBody:@RequestBody annotation is used to read the HTTP content of the request (string), HttpMessageConverter interface provided by springmvc will read (JSON) conversion parameters for Java objects and bind to the Controller method. @ResponseBody @ResponseBody notes for object returns Controller method, the HttpMessageConverter interface provided by springmvc is converted to the data in the specified format such as JSON, XML, @RequestMapping response to the client through the Response ("/testAjaxJson") public @ResponseBody Items testAjaxJson (@RequestBody Items item, ModelMap model) {System.out.println (item); return item;}

3.4 Restful development

Restful is a resource orientation and resource manipulation style. Not a standard, not an agreement. It’s just a style. Software based on this style can be more concise, more hierarchical, and easier to implement caching mechanisms.

1. note @RequestMapping ("item/{id}") statement requested URL {xxx} is called the placeholder request URL can be "item /1" or "item/2" (@PathVariable) Integer (2. ID) to obtain data on the URL if the @RequestMapping is represented by "item/{id}", ID and the parameter name, @PathVariable name is not specified. If inconsistent, such as "item/{ItemId}", you need to specify the name @PathVariable ("itemId"). The use of restful1.action URL / * * * Restful access path style developed here, using the PathVariable (URL) can be received in the ID / @RequestMapping ("restful{id}.action") public String restful (@PathVariable) (Integer ID, ModelMap model) {Items item = itemsService.findItemsById (ID); model.addAttribute ("item" item, return "); editItem";}

3.5 springmvc custom interceptors

Custom interceptor implements the HandlerIntercepter interface: three ways to implement it

Public class MyInterceptor1 implements HandlerInterceptor public Boolean preHandle {@Override (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o Exception System.out.println (throws) {"execution method 1"); return true; public void postHandle} @Override (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView Exception System.out.println (throws) {"execution method after 1 @Override public void");} afterCompletion (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e Exception System.out.println (throws) {"rendering page 1");}}

Configuring custom interceptors in springmvc.xml:

<! -- --> < custom interceptor; mvc:interceptors> < mvc:interceptor> < mvc:mapping path= /> < / * * "bean class=" com.itdream.ssm.interceptor.MyInterceptor1 "/> < /mvc:interceptor> < mvc: interceptor> < mvc:mapping; path= /> < / * *" bean class= "com.itdream.ssm.interceptor.MyInterceptor2" /> < /mvc:interceptor> < /mvc:interceptors> preHandle; Summary: according to the definition of sequence called postHandler interceptor to intercept is defined according to the reverse call afterCompletion call postHandler in reverse order according to the definition of the interceptor interceptor interceptor chain all return a successful call to afterCompletion only preHandle return true call