SpringMVC
1. What is spring MVC
Is a lightweight, MVC based web application layer framework that encapsulates servlets
MVC:
M: Model, the Model layer, refers to javaBean, which is used to = = process data==
javaBean:
Entity class, business processing, i.e. Service, Dao
V: View, the View layer, refers to html or jsp pages in the project, which is used to interact with users and = = display data==
C: Controller, the control layer, refers to the servlet in the project, which is used to = = receive requests = = and = = respond to browsers==
2. Spring MVC process
Related components:
Front end controller (dispatcher servlet): receives requests and responds to results, reducing the coupling between components
2. Processor mapper( HandlerMapping): according to URL Find the processor
Handler adapter: executes the handler according to specific rules (rules required by the handler adapter)
4. Processor( Handler): Each Controller(Need programmers to write code (processing logic)
- View resolver: parses the view, processes the returned string, and parses it into the corresponding page
Detailed explanation of processing flow
1. The user initiates a request to the front-end controller (dispatcher servlet)
2. The front-end controller requests the handler mapping to find the handler: search through xml configuration or annotation
3. After finding the Handle, the handler mapping returns the handler execution chain (including generation processing) to the front controller
Interceptor object and processor (interceptor, etc.)
4. The front-end Controller (DispatcherServlet) calls the processor adapter (HandlerAdapter) to execute the processor (= = Handler, i.e. Controller, i.e. Servlet layer = =)
5. The Handler adapter executes the methods in the Handler
6. After the Handler is executed, return ModelAndView to the processor adapter
7. The processor adapter returns ModelAndView to the front controller
8. The front-end controller requests the view resolver to parse the view into a view
9. The View resolver returns the View to the front controller
10. The front controller renders the view
11. The front-end controller responds to the user
3. Spring MVC: specific implementation process
1. Import jar package
- commons-logging-1.1.1.jar
- spring-aop-5.2.16.RELEASE.jar
- spring-beans-5.2.16.RELEASE.jar
- spring-aspects-5.2.16.RELEASE.jar
- spring-context-5.2.16.RELEASE.jar
- spring-core-5.2.16.RELEASE.jar
- spring-expression-5.2.16.RELEASE.jar
- spring-web-5.2.16.RELEASE.jar
- spring-webmvc-5.2.16.RELEASE.jar
2. A request was initiated
<a href="test">request</a>
3. The core controller (front-end controller) is configured in web.xml
<servlet> <!--register DispatcherServlet--> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- Specify the location of the core configuration file --> <init-param> <!--name Value is fixed content--> <param-name>contextConfigLocation</param-name> <!--stay src Configured under xml--> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- start-up tomcat Create it now DispatcherServlet The smaller the number of instances, the earlier the execution--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <!-- url-pattern:Two ways of writing 1) *.do, *.action, *.mvc 2)Slash / --> <url-pattern>/</url-pattern> </servlet-mapping>
4. Create spring mvc.xml core configuration file
①: head
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--Various configurations--> </beans>
②: configure scanning
<!--open mvc Annotation scan --> <mvc:annotation-driven/> <!--scanning controller All classes in the package are created for controller object --> <context:component-scan base-package="com.bdqn.controller"></context:component-scan>
③: configure view parser
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--prefix--> <!--jsp To put in WEB-INF Files under: used to store pages--> <property name="prefix" value="/WEB-INF/jsp/"></property> <!--suffix--> <property name="suffix" value=".jsp"></property> </bean>
5. Create Controller class
@Controller //Create the Controller object and put it into the spring MVC container public class UserController{ @RequestMapping("/test") //Configure request mapping path public String test(){ return "success";//Returned page } }
4. @ RequestMapping() annotation
@RequestMapping() annotation
1. Location
1,On class: represents the module path 2. In terms of method: it represents the specific path (processor method, mapper method)
2. Properties
value = "/ path": mapping path, slash can be omitted, but it is not recommended
Method: request method
Value: RequestMethod.GET handles get requests
RequestMethod.POST handle post requests
= = note = =: if there is no method, all requests are supported
5. Spring MVC input parameter
1. Single parameter: the method parameter name must be consistent with the request parameter name
<a href="user/del?id=1">delete</a> public String del(Integer id){ }
2. Multiple parameters:
1. The method parameter name is consistent with the request parameter name = =:
<a href="user/del?id=1&name=zs">delete</a> public String del(Integer id,String name){}
2. If the method parameter name and the request parameter name = = are inconsistent, you need to use = = @ RequestParam = = annotation
public String showPage(@RequestParam(value="number",required=false,defaultValue="1")Integer curPage ){
@ RequestParam annotation: bind request parameters to method parameters
value: received parameter name
required: whether the parameter must be included and whether the parameter content can be empty. The default is true (the parameter must be passed); false is the opposite
defaultValue: default value. If no parameter is passed, there is a default value
3. Enter parameters as objects: the request parameters must be consistent with the attribute names in the object = = entity class==
public String add(User user) {}
6. Spring MVC output parameters
1. ModelAndView class: store data + view
public ModelAndView findAll(){ ModelAndView mv = new ModelAndView(); mv.addObject("user", user); //Store data: mv.setViewName("student/list")// Store view return mv; }
2. Model class: storing data
public String findAll(Model model){ model.addAttribute("user", user); //Store data} return "student/list"// Return to view}
3. Using servlet native interfaces
1,request:
public String Method name(HttpServletRequest request){}
2,session:
public String Method name(HttpSession session){}
3,response:
public void del(HttpServletResponse response) throws IOException{ response.setContentType("text/html;charset=utf-8"); //Process the response in Chinese. / / after the deletion succeeds, jump back to the findAll method under the controller and query the response. Getwriter(). Print ("< script > alert ('deletion succeeded! '); location. Href ='findAll'; < / script >"); }
4. Using the Map interface
public String findAll(Map<String,Object> map){ map.put("key",value); }
5. Redirection: = = springmvc default forwarding jump==
Keyword: = = redirect:==
public String Method name(){ return "redirect:/stu/findAll"; }
7. Handle the Chinese garbled code of the request
1: post request garbled
Configure in web.xml
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <!--Sets the character encoding in the project--> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <!-- /*:Indicates that all requests are processed through the filter first--> <url-pattern>/*</url-pattern> </filter-mapping>
2: get request garbled
① : Method 1
Modify the tomcat configuration file and add the code consistent with the project code, as follows:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
② : Method 2
String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
8. How spring MVC handles static resources
Such as js, css, image, html, etc
Cause: the URL pattern of DispatcherServlet is configured as "/" in web.xml, resulting in all static resources being handed over to DispatcherServlet for processing, and
DispatcherServlet cannot handle access to static resources. Therefore, the access to static resources is 404.
1. The first treatment method:
= = need to rely on tomcat==
Configure: MVC: default servlet handler in springmvc.xml/
2. The second processing method: = = recommended==
Configure in springmvc.xml:
<mvc:resources location="/static/" mapping="/static/**"/><!--mvc:resoutces After joining, the frame will be created ResourceHttpRequestHandler Object that handles access to static resources without dependency tomcat The server mapping: Access to static resources url Address, using wildcards **location: Directory location of static resources in the project-->
Implementation steps:
1) create a static folder under webapp and put images, js, css, etc. into the file
2) configure in spring MVC:
<mvc:resources location="/static/" mapping="/static/**"/>
3) page usage:
<script type="text/javascript" src="static/js/jquery-1.12.4.js"></script> Relative path <img src="<%=basePath%>/static/images/read.jpg"/> Absolute path <img src="${pageContext.request.contextPath}/static/images/user/dongtu.gif"/> Absolute path
9. Get absolute path
Method 1:
<%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
Method 2:
${pageContext.request.contextPath}
10. Spring MVC: ajax request
1: Based on fastjson dependency
Import package: fastjson-1.2.6.jar
1. Use out output stream object to handle + fastjson dependency
public void Method name(HttpServletResponse response) throws IOException{ response.setContentType("text/html;charset=utf-8"); response.getWriter().print(Returned data); (If the return type is json,You need to convert the object to json (type) }
2. Use @ ResponseBody annotation + fastjson dependency
@RequestMapping(value="/route",produces="text/html;charset=utf-8") @ResponseBody //Respond to the user through the response, instead of using the view parser, but directly write the data into the output stream; (public String method name () {return returned data; (if the return type is json, you still need to convert the object to json type)}
2: Based on the default jackson dependency of spring MVC
1. Import package: jackson-core-2.9.8.jar
jackson-annotations-2.9.8.jar
2. controller processing:
1. Processing return text type
@RequestMapping("/ajax") @ResponseBody//File upload annotation public String method name () {return str;}
2. Handle the returned json type
public List<type> Method name(){ return list; } public Type method name(){ return object; } public Map<type,type> Method name(){ return map; }
3. Processing returned html type
public String Method name(){ String str = "have html Label data"; return str; }
11. File upload
1. Single file upload
1. Form:
① the form submission format must be post submission
②. Add attribute to the form: enctype = "multipart / form data"
③. Add the name attribute to the text box
④. File domain provided:
<form action="<%=basePath%>standardController/addON" method="post" enctype="multipart/form-data"> </form><input type="file" name="photo"/>
2. jar package:
①: support file upload: commons-fileupload-1.4.jar
②: io flow: commons-io-2.7.jar
3. Controlling file upload type with js
$("[name=photo]").change(function(){ var val = $(this).val(); //Get the suffix of the current file / / substring: extract the characters between the two specified subscripts in the string, set a value, that is, start from there / / lastIndexOf(): the last position of the specified string value, and find var Zhui = val.substring (val.lastindexof ("...)) from back to front; If (Zhui! = ". JPG" & & Zhui! = ". GIF" & & Zhui! = ". PNG" & & Zhui! = ". BMP") {alert ("please select the correct picture format"); $(this).val(""); / / empty the selected file}});
4. Configure the file parser object in springmvc.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
Note:
1) CommonsMultipartResolver: judge whether the file is included in the request. If so, parse the requested file into MultipartFile and pass it to
controller
2) the id must be multipartResolver
5. File upload Controller processing method:
@RequestMapping("/fileOn") public void fileOn(user u,MultipartFile photo,HttpSession session,HttpServletResponse response) throws IllegalStateException, IOException{ if(!photo.isEmpty()){//Judge whether it is empty. / / create a file String path=session.getServletContext().getRealPath("/static/updateFile /)// Obtain the storage path of the current file system.out.println (path); File file=new File(path); // Judge whether the current folder exists if(!file.exists()) {/ / does not exist. Create file.mkdirs();} / / file name processing / / get the file name String filePD=FilenameUtils.getExtension(photo.getOriginalFilename())// Take a random name for the file; Prevent overwriting string filename = UUID. Randomuuid(). Tostring(). Replace ("-", "" "). Touppercase() +". + filepd// Put the file name in the updateFile created above. file=new File(path,fileName)// File upload photo.transferTo(file)// Save the file into the corresponding column u.setfilename (filename) of the entity class;} int row=us.insertON(u); If (row! = 0) {response. Getwriter(). Print ("< script > alert ('Insert succeeded '); location. Href ='findall' < / script >");} else {response. Getwriter(). Print ("< script > alert ('Insert failed '); history. Back() < / script >");}
2. Multi file upload
1. It is required that the name s of all file fields on the page must be the same
Photo 1:<input type="file" name="photos"><br/>Photo 2:<input type="file" name="photos"><br/>Photo 3:<input type="file" name="photos"><br/>
2. MultipartFile [] reception in controller
Create via line file outside of loop
public void fileOn(user u,MultipartFile[] photos,HttpSession session,HttpServletResponse response){ //Create a file string path = session. Getservletcontext(). Getrealpath ("/ static / updateFile /"); System.out.println(path); File file=new File(path); // Judge whether the current folder exists if(!file.exists()) {/ / does not exist create file. Mkdirs();} for (int i = 0; I < photos. Length; I + +) {multipartfile photo = photos [i]; if (! Photo. Isempty()) {/ / judge whether it is empty / / file name processing / / obtain the file name String filePD=FilenameUtils.getExtension(photo.getOriginalFilename()); / / take a random name for the file; prevent overwriting string filename = UUID. Randomuuid(). Tostring(). Replace ("-", "" "). Touppercase() +" +Filepd; / / put the file name in the updateFile created above. file=new File(path,fileName); / / upload photo.transferto (file); if (I = = 0) {u.setfilename1 (filename);} else if (I = = 1) {u.setfilename2 (filename) ;} else {u.setfilename3 (filename);}}} int row = us. Inserton (U); if (row! = 0) {response. Getwriter(). Print ("< script > alert ('Insert succeeded '); location.href =' query all methods' < / script >");} else {response. Getwriter(). Print( "< script > alert ('Insert failed '); history. Back() < / script >");}}
12. File download
1. Method 1: use html Tags:
Download files other than pictures:
<a href="static/download/a.docx">download doc</a>
Download pictures:
<a href="static/download/read.jpg" download="read.jpg"> <img src="static/download/read.jpg" width="50" height="50"/> </a>
2. Method 2: use flow to realize:
Page:
<a href="user/download?fileName=file name">Download with file stream doc</a>
controller:
public void download(String fileName,HttpSession session,HttpServletResponse response) throws FileNotFoundException, IOException{ //The file path is the image storage location in Tomcat. It is customized. The file created according to file upload String path = session.getServletContext().getRealPath("/static/updateFile/")+fileName; / / get the file path file f = new file (path); if (f.exists()) {/ / if the file exists, download / / set the response header to download as an attachment (activate the download box, and the file name will be automatically filled in the download box) response.addheader ("content disposition", "attachment; filename =" + filename ") ; / / output as a stream, and output the file ioutils.copy (New FileInputStream (path), response. Getoutputstream()) specified on the server;}}
13. spring supports Rest style URLs
1. Page:
<a href="login/1/Zhang San">request</a>
2. controller connection parameters:
//When receiving here, define the parameter name @ requestmapping ("login / {ID} / {name}") / / @ pathvariable annotation: you can bind the placeholder parameter in the URL to the input parameter of the controller processing method. public String login(@PathVariable int id,@PathVariable String name) {/ / the parameter name ID must be exactly the same as that in {ID}. System.out.println (ID + "\ T" + name); return "success";} / / if the parameter names are inconsistent, you need to specify that the keyword in @ PathVariable("name") is exactly the same as that in {name}@ RequestMapping("login/{id}/{name}") public String login(@PathVariable(value="id") int id,@PathVariable(value="name") String userName){ }
3. File name upload in Rest style:
@RequestMapping("/download/{fileName:.+}")
14. Other annotations in spring MVC
Spring 4.3 introduces @ GetMapping and @ PostMapping to help simplify the mapping of common HTTP methods and better express the semantics of annotated methods.
① : @ GetMapping is a combined annotation, which is the abbreviation of @ RequestMapping(method = RequestMethod.GET). This annotation maps the get request to a specific processing method.
② : @ PostMapping is a combined annotation, which is the abbreviation of @ RequestMapping(method = RequestMethod.POST). This annotation maps post requests to specific processing methods.