Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does the springMVC framework look like

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces what the springMVC framework is like, the content is very detailed, interested friends can refer to, hope to be helpful to you.

SpringMVC

Concept: SpringMVC is a lightweight web framework based on java to achieve the request-driven type of MVC design model. It belongs to the follow-up products of springFramework and has been integrated into Spring Web Flow. Spring framework provides a fully functional MVC module for building web applications, using Spring pluggable MVC framework, so that when using Spring for WEB development, you can choose to use Spring's SpringMVC framework or integrate other MVC frameworks.

It uses a set of annotations to make a simple Java class a controller for handling requests without implementing any interface sequentially, and it also supports RESTful programming-style requests.

Starter Code:

Step 1: configure the front-end controller, in web.xml

DispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc.xml 1 dispatcherServlet /

2. Create a control class

@ Controllerpublic class HelloController {@ RequestMapping (path = "/ hello") / / is used to establish the correspondence between the request URL and the request processing method / * * attribute Path/value, mapping path * method, what kind of request method can the current method accept * params, the condition for request parameters * handers, the request sent must contain the request header * * / public String sayHello () {System.out.println ("hello StringMvc"); return "success";}}

3. Create a configuration file under the resource folder

Program parsing:

1. Start the server and load some configuration files

2. Send the request and process the request in the background

Component introduction: the springmvc framework executes the process based on the component approach

Front-end controller: DispatcherServlet, which is equivalent to c in mvc, which calls other components to process user requests and reduces the coupling between components.

Processor mapper: HandlerMapping, which is responsible for finding handler (processor) according to user's request

Processor adapter: HandlerAdapter, executes on the processor

Processor: Handler, which is the specific business controller to be written in our development.

View parser: ViewResolver, responsible for processing the results to generate view views

Request parameter binding

Starter Code:

1. Send request parameters

User name:

2. Request parameter binding, and automatically bind parameters with the same name

@ Controller@RequestMapping ("/ param") public class ParamController {@ RequestMapping ("/ testParam") public String testParam (String username) {System.out.println ("executed." + username); return "success";}}

Request parameters bind entity class:

1. Create an entity class

Public class DemoClass implements Serializable {private String username; private String password; private Double money;//- omits the get,set method and adds it yourself.

2. Send a request

User name:

Password:

Amount:

3. Bind entity types automatically

@ Controller@RequestMapping ("/ param") public class ParamController {@ RequestMapping ("/ save") public String save (DemoClass demoClass) {System.out.println (demoClass); return "success";}}

Note: solve the garbled code in POST request: add filter, add it in web.xml

CharacterEncodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 characterEncodingFilter / *

Request parameter binding collection type:

1. Send a request

User id:

User age:

2. Create the corresponding entity class

3. Automatically bind parameters

Custom content converter: resolve data content conversion exception problem

Step 1: define a class that implements the Convrter interface, which has two generics that represent the accepted type and the target type, respectively

/ / Custom type converter public class StringToDateConverter implements Converter {@ Override public Date convert (String s) {if (s = = null) {throw new RuntimeException ("Please pass in data");} DateFormat df = new SimpleDateFormat ("yyyy-MM-dd"); try {Date date = df.parse (s); return date } catch (ParseException e) {e.printStackTrace (); throw new RuntimeException ("data type conversion exception");}

Step 2: register the type converter

Get servlet native API

/ / get native APIpublic String testServlet (HttpServletRequest request, HttpServletResponse response) {return "success";}

Common notes:

@ RequsetParams

Function: assign the parameter with the specified name in the request to the parameter in the controller.

Attribute: value, the name in the request parameter

Required, whether this parameter is required for request parameters. Default value: true, which means it must be provided. If not, an error will be reported.

/ @ RequestParampublic String testRequestParam (@ RequestParam (name = "name") String username) {return "success";}

@ RequsetBody

Function: used to obtain the content of the request body, directly use to get the data of key=value&key= value structure, get request is not applicable

Attribute: whether required; must have a request body. The default value is true. If the value is true, the get request method will report an error. If the value is false,get, the request will get null.

/ / @ RequestBodypublic String testRequestBody (@ RequestBody String body) {System.out.println (body); return "success";}

@ PathVariable

Purpose: used to bind placeholders in url

Attribute: value: specifies the placeholder name in url

Restful style URL:

1. The request path is the same, and different backend methods can be executed according to different request methods.

2. The advantages of restful style URL: 1, clear structure, 2, in line with the standard, 3, easy to understand, 4, easy to expand

/ / @ PathVariable@RequestMapping ("/ testPathVariable/ {uid}") public String testPathVariable (@ PathVariable (name = "uid") String id) {System.out.println (id); return "success";}

@ HiddentHttpMethodFilter

Function; because the browser's form form only supports GET and POST requests, but DELETE, PUT and other method do not, spring3.0 adds a filter that can change the browser request to the specified request method and send it to our controller method to support GET,POST,PUT and DELETE

How to use it:

Step 2: request method must use POST request

Step 3: provide the _ method request parameter as required. The value of this parameter is the request method we need.

@ RequestHeader

Function: used to get the request header

Required: whether this header is required

/ / @ RequestHeaderpublic String testRequestHeader (@ RequestHeader (value = "Accept") String header) {System.out.println (header); return "success";}

@ CookieValue

Function: used to pass the value of the specified cookie name to the controller method parameter

Attribute: value: specify the name of the cookie

Required: whether this cookie is required

/ / @ CookieValuepublic String testCookieValue (@ CookieValue (value = "JSESSIONID") String cookie) {System.out.println (cookie); return "success";}

@ ModelAttribute

Function: used to modify methods and parameters that appear on the method, indicating that the current method will be executed before the controller's method is executed. It can modify a method that does not return a value, or it can modify a method that has a specific return value. Appears on the parameter and gets the specified data to assign a value to the parameter

Attribute: value. The key,key used to obtain data can be on the attribute name of POJO or the key of map structure.

Application scenario: when the table submits data that is not complete entity class data, ensure that the fields that do not submit data use the original data of the database object.

/ / @ ModelAttribute@ModelAttributepublic void MyShow () {System.out.println ("MyShow executed");}

@ SessionAttribute

Function: used to perform parameter sharing between controller methods multiple times

Attribute: value: used to specify the name of the attribute to be stored

Type: used to specify the type of data to be stored

Act on the class.

Response data and result view of Springmvc

The response return value is of type String:

/ / return value is String@RequestMapping ("/ testString") public String testString (Model model) {System.out.println ("testString executed"); return "success";}

The response return value is of type void:

/ the return value is voidpublic void testvoid (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println ("testvoid method execution"); request.getRequestDispatcher ("/ WEB-INF/Pages/success.jsp") .forward (request,response); / / request forwarding response.sendRedirect (request.getContextPath () + "/ success.jsp"); / / redirect / / direct response response.setCharacterEncoding ("UTF-8"); response.setContentType ("text/html") Charset=UTF-8 "); response.getWriter () .print (" hello ");}

File upload

Traditional code:

File upload: traditionally choose a file: @ RequestMapping ("/ fileupload1") public String fileUpLoad (HttpServletRequest request) throws Exception {System.out.println ("File upload"); / / use the fileupload component String realPath = request.getSession (). GetServletContext (). GetRealPath ("/ uploads"); File file = new File (realPath); if (! (file.exists () {file.mkdirs () } / / parse the request object and get the uploaded file like DiskFileItemFactory factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (factory); List fileItems = upload.parseRequest (request) For (FileItem item: fileItems) {/ / to determine whether the current item object is an uploaded file if (item.isFormField ()) {/ / normal form item} else {/ / upload file item String filename = item.getName (); String uuid = UUID.randomUUID (). ToString (). Replace ("-", ") Filename=uuid+ "_" + filename; item.write (new File (realPath,filename)); item.delete ();} return "success";}

SpringMVC mode code:

File upload: springmvc Select File: @ RequestMapping ("/ fileupload2") public String fileUpLoad2 (HttpServletRequest request,MultipartFile upload) throws IOException {System.out.println ("springmvc File upload"); String path = request.getSession (). GetServletContext (). GetRealPath ("/ uploads/"); File file = new File (path); if (! file.exists ()) {file.mkdirs ();} String filename = upload.getOriginalFilename () String uuid = UUID.randomUUID (). ToString (). Replace ("-", "); filename = uuid+" _ "+ filename; upload.transferTo (new File (path,filename)); return" success ";}

Cross-service mode code:

File upload: select a file across servers: @ RequestMapping ("/ fileupload3") public String fileUpLoad3 (MultipartFile upload) throws IOException {System.out.println ("Cross-server file upload"); / / define the server path for uploading files String path = "http://localhost:9090/uploads/"; String filename = upload.getOriginalFilename (); String uuid = UUID.randomUUID () .toString () .replace ("-",") Filename = uuid+ "_" + filename; / / create client object Client client = Client.create (); / / connect to the picture server WebResource resource = client.resource (path + filename); / / upload file resource.put (upload.getBytes ()); return "success";}

In actual development, we will have many servers that handle different functions, such as:

Application server: responsible for deploying our applications

Database server: running our database

Caching and message servers: responsible for handling caches and messages with large concurrent access

File server: the server responsible for storing files uploaded by users

Interceptor for SpringMVC: Filter similar to servlet

1. Write interceptor classes

/ * Custom interceptor * / public class MyInterceptor implements HandlerInterceptor {/ * preprocess, before controller method execution * if return true is released, execute the next interceptor, if not Execute the method in controller * if return false does not release * @ param request * @ param response * @ param handler * @ return * @ throws Exception * / @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println ("MyInterceptor executed") Return true } / * Post-processing method * @ param request * @ param response * @ param handler * @ param modelAndView * @ throws Exception * / @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler ModelAndView modelAndView) throws Exception {} / * jump to the page and execute * * @ param request * @ param response * @ param handler * @ param ex * @ throws Exception * / @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}}

2. Configure the interceptor

Exception handling of SpringMVC:

1. Write custom exception classes

Public class SysException extends Exception {private String message; @ Override public String getMessage () {return message;} public void setMessage (String message) {this.message = message;} public SysException (String message) {this.message = message;}}

2. Write exception handlers

Public class SysExceptionResolver implements HandlerExceptionResolver {/ * business handling exceptions * @ param httpServletRequest * @ param httpServletResponse * @ param o * @ param e * @ return * / @ Override public ModelAndView resolveException (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {/ / get exception object SysException exception= null; if (e instanceof SysException) {exception= (SysException) e } else {exception= new SysException (system maintenance);} ModelAndView mv = new ModelAndView (); mv.addObject ("errorMsg", exception.getMessage ()); mv.setViewName ("error"); return mv;}}

3. Configure exception handlers

On what the springMVC framework is to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report