springmvc interview Review

First, what is springmvc?

  SpringMVC request is based on the realization of Java MVC design pattern driven type of lightweight Web framework that uses the MVC architectural pattern of thought, will decouple duty web layer, based on the request drive refers to the use of the request - response model, the purpose of the framework is to help us simplify development.

 

Two, springmvc request process

 

Specific processes across the architecture:

(1) The user sends a request -> DispatcherServlet, get the front end of the controller processing requests do not themselves, but to the other processors for processing, where only as a unified access point, for controlling the overall process.

(2) DispatcherServlet -> HandlerMapping, the processor will request mapper maps to HandlerExecutionChain object back to DispatcherServlet, the object which contains the object and a plurality of processors Handler HandlerInterceptor blocker object (if set is generated interceptor intercepting object, no is not generated).

(3) DispatcherServlet - Processor> HandlerAdapter, the transfer processor adapter into the adapter over the packaging, making it easy to support a variety of types of processors, which is the application adapters design patterns.

(4) HandlerAdapter -> processor perform the corresponding function call treatment method (Controller class and method is the need to write our own), and returns a ModelAndView object (including the model data, the logical view name), and then returns to the HandlerAdapter front controller.

        ModelAndView: Model business object model data portion is returned, View is a logical view of a part of the name.

(5) DispatcherServlet -> ViewResolver, the logical view view resolver name resolution concrete View (model data not included). The first resolves the name into a physical view of the logical view name is the particular page address, then generates a view object View.

(6) DispatcherServlet -> View, View case for rendering the view, i.e. model data rendering. At this time, actually a Model Map data structure.

(7) DispatcherServlet -> response to the user.

 

Three, springmvc comment

   @Controller: in the corresponding method, the parser may parse the view of the return jsp, html pages, and jump to the corresponding page;

   @RestController: the equivalent of @ Controller + @ ResponseBody

   @ResponseBody: return json string

   @RequestMapping: a path setting request

   @RequestMapping(value="/getName",method=RequestMethod.GET,params={"id=123","name","!age")

 //上述规则定义了,只能响应get请求,并且请求的参数必须包含id=123,必须包含name,不能包含age//根据上述规则此地址合法:http://localhost:8080/xx?id=123&name=abc

   Front-end parameter acquisition

  1, the same can be directly imply a property name. public String f (String name, String age) {}

  2, the front end of the transmission data is encapsulated as an object, the value of the same name and the field name to the object. public String f (Person person) {}

  3, the use of annotation @RequestParma (value = "name", defaultValue = "tc"): Get the name value, and set the default value. public String f (@RequestParma ( "name") String name) {}

  4, using PathVariable: This annotation data request in the request path Binding

    Request path: RequestMapping ( "../ {name} / {age}")

   public String f(@PathVariable("name")String name,@PathVariable("age")String age){return “redirect:”/  “forward:”}

   redirect: Redirect; forward: forward the request;

  5, @ RequestBody: json receiving data; public String f (@RequestBody Person person) {}

Fourth, file upload

/*
采用三种方式来接收上传文件,分别用三个方法试验
每个方法里,有程序执行时间记录
实际运用时,三者选其一
第一种最慢,第三种最快,一般选用第二种
*/
@Controller
public class FileController { /* * 通过流的方式上传文件 * * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象 */ @RequestMapping("fileUpload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException { // 用来检测程序运行时间 long startTime = System.currentTimeMillis(); try { // 获取输出流 OutputStream os = new FileOutputStream("E:/" + new Date().getTime() + file.getOriginalFilename()); // 获取输入流 CommonsMultipartFile 中可以直接得到文件的流 InputStream is = file.getInputStream(); int temp; // 一个一个字节的读取并写入 while ((temp = is.read()) != (-1)) { os.write(temp); } os.flush(); os.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("方法一的运行时间:" + String.valueOf(endTime - startTime) + "ms"); return "/success"; } /* * 采用file.Transto 来保存上传的文件 */ @RequestMapping("fileUpload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException { long startTime = System.currentTimeMillis(); String path = "E:/" + new Date().getTime() + file.getOriginalFilename(); File newFile = new File(path); // 通过CommonsMultipartFile的方法直接写文件(注意这个时候) file.transferTo(newFile); long endTime = System.currentTimeMillis(); System.out.println("方法二的运行时间:" + String.valueOf(endTime - startTime) + "ms"); return "/success"; } /* * 采用spring提供的上传文件的方法 */ @RequestMapping("springUpload") public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException { long startTime = System.currentTimeMillis(); // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); // 检查form中是否有enctype="multipart/form-data" if (multipartResolver.isMultipart(request)) { // 将request变成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // 获取multiRequest 中所有的文件名 Iterator iter = multiRequest.getFileNames(); while (iter.hasNext()) { // 一次遍历所有文件 MultipartFile file = multiRequest.getFile(iter.next().toString()); if (file != null) { String path = "E:/springUpload" + file.getOriginalFilename(); // 上传 file.transferTo(new File(path)); } } } long endTime = System.currentTimeMillis(); System.out.println("方法三的运行时间:" + String.valueOf(endTime - startTime) + "ms"); return "/success"; } }

 Front page:

<!-- 三个form分别对应controller里三个上传方法 -->
    <form name="Form1" action="fileUpload.v" method="post" enctype="multipart/form-data"> <h1>采用流的方式上传文件</h1> <input type="file" name="file"> <input type="submit" value="upload" /> </form> <form name="Form2" action="fileUpload2.v" method="post" enctype="multipart/form-data"> <h1>采用multipart提供的file.transfer方法上传文件</h1> <input type="file" name="file"> <input type="submit" value="upload" /> </form> <form name="Form3" action="springUpload.v" method="post" enctype="multipart/form-data"> <h1>使用spring mvc提供的类的方法上传文件</h1> <input type="file" name="file"> <input type="submit" value="upload" /> </form>

---------------------
reference links
https://blog.csdn.net/weixin_42621338/article/details/87204868

https://www.jianshu.com/p/fbc6953e5af4

 

 

Guess you like

Origin www.cnblogs.com/kobe24vs23/p/11316464.html
Recommended