Detailed analysis of SpringMVC views and REST style (with code)
This article brings you a detailed analysis of SpringMVC views and REST style (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
What is a view resolver?
The two most important interfaces used by springMVC to handle views are ViewResolver and View.
The main function of ViewResolver is to resolve a logical view name into a real view. In SpringMVC, the View object is used to present the View object to the client, and the ViewResolver only converts the logical view name into a real view. A View object that resolves to an object.
The main function of the View interface is to process views and return them to the client.
Execution process of the view parser:
After the request method is executed, a ModelAndView object is finally returned. For those that return String , View, ModelMap and other types SpingMVC will eventually assemble them into a ModelAndView object internally, which contains the logical name and view of the model object. StringMVC uses the view parser to obtain the final view object. The final view can be a JSP or other file-form view. The rendering processor does not care about which method is ultimately adopted. The processor focuses on the work of producing model data, and has always achieved full decoupling of MVC.
View:
The role of the view is to render model data and present the data in the model to the user in some form. In order to achieve the decoupling of the view model and specific implementation technology, Sping defines a View interface. View objects are instantiated by the view resolver, and since views are stateless, they do not have thread safety issues.
Commonly used view implementation classes:
InternalResourceView: Encapsulates JSP resources into a view and is the view parser used by springmvc by default.
JstlView: Introducing the jstl package springmvc into the JSP project will automatically use this parser
MapingJackJsonView: Output the model in Json mode through the ObjectMapper of the Jackson open source framework.
AbstractExcelView: The abstract class of Excel document view, which constructs Excel document based on POI
AbstractPdfVIew: The abstract class of PDF document view, which constructs Pdf document based on iText
BeanNameViewResolver: Resolve the logical view name into a Bean, and the id of the Bean is equal to the logical view name.
The role of the view resolver is relatively simple, parsing the logical view into a specific view object. All view resolvers must implement the ViewResolver interface.
JSP is the most commonly used view technology, you can use InternalResourceView as the view parser
As long as the JSTL tag is introduced in the project, springmvc will automatically convert the view InternalResourceView into JstlView, which is its subclass.
Each view parser implements the Ordered interface and develops an order attribute, through which the priority of the parser can be set. The smaller the order, the higher the priority. Spring MVC will parse the logical view name according to the priority of the view parser order until the parsing is successful and the view object is returned, otherwise a ServletException will be thrown
Custom view:
@Component public class MyView implements View { @Override public String getContentType() { return "text/html"; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.getWriter().println("<h1>Spring MVC Custom view</h1>"); } }
We need Implement this custom view into the View interface and override the two methods in the interface. Then we declare this class as a Bean and hand it over to spring for management. Here we configure a beanName resolver.
<!-- 配置BeanName解析器 --> <bean id="beanNameViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"> <property name="order" value="1"/> </bean>
Then write a request. This request returns the name of the Bean. By default, the first letter is lowercase and displayed in camel case.
@RequestMapping("myView") public String myView(){ System.out.println("myView load ..."); return "myView"; }
This way we can complete our custom view.
Off and redirect:
If the return string contains "redirect :" or "forward:", SpringMvc will do special processing.
If we need to access the view directly, we can configure it like this
<!– 直接配置对应的视图访问路径 --> <mvc:view-controller path="/hello" view-name="hello.jsp" /> <!-- 如果配置了mvc-controller会导致其它页面没法正常访问,还需要添加一个标签 --> <mvc:annotation-driven />
REST Chapter
REST (Representational State Transfer): That is (resource) presentation layer state transfer.
Resources: An entity on the network, or a piece of information on the network. It can be a piece of text, a song, a picture, etc. You can use a URL to point to it. Each resource has a specific, unique URL. To access this resource, just access the URI directly.
Representation layer: The form in which resources are presented.
State Transfer: Each time a request is issued, it represents an interaction between the client and the server. The HTTP protocol is a stateless protocol, that is, all states are stored on the server side. If the client wants to operate the server, it must use some means to cause the server to undergo state transformation. This transformation is based on the presentation layer, so it is the presentation layer state transformation.
在我们的SpringMVC之中支持HTTP四种请求状态,REST规定的HTTP协议中四种表示操作方式的动词
GET请求:获取资源
POST请求:新建资源
PUT:更新资源
DELETE:删除资源
我们需要在WEB.xml中配置实现PUT,DELETE请求方式,大家都知道在我们传统的HTML中只有GET,POST两种请求方式。
<!-- 配置HiddenHttpMethodFilter过滤器实现PUT,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>
GET请求
GET请求: <a href="rest/testRest/10">test RestGet请求</a><br><br> @RequestMapping(value="/testRest/{id}",method=RequestMethod.GET) public String testRestGet(@PathVariable Integer id){ System.out.println("GET请求,获取id为:" + id + "的对象!"); return SUCCESS; }
Post请求
POST请求: <form action="rest/testRest" method="post"> <input type="submit" value="post请求" /> </form> @RequestMapping(value="/testRest",method=RequestMethod.POST) public String testRestPost(){ System.out.println("POST请求,添加新的对象!"); return SUCCESS; }
PUT和DELETE请求想要使用必须添加上面的过滤器,并且在Post请求中加上隐藏域name="_method",value="PUT/DELETE"。
PUT,请求其实是由POST请求转换而来的。
PUT请求: <form action="rest/testRest" method="post"> <!-- 添加隐藏域,名称为_method,value为请求方式 --> <input type="hidden" name="_method" value="PUT" /> <input type="submit" value="put请求" /> </form> @RequestMapping(value="/testRest",method=RequestMethod.PUT) public String testRestPut(){ System.out.println("PUT请求,更新操作!"); return SUCCESS; }
DELETE请求
DELETE请求: <form action="rest/testRest/10000" method="post"> <!-- 添加隐藏域,名称为_method,value为请求方式 --> <input type="hidden" name="_method" value="DELETE" /> <input type="submit" value="delete请求" /> </form> @RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE) public String testRestDelete(@PathVariable Integer id){ System.out.println("DELETE请求,删除操作!" + id); return SUCCESS; }
重复一次第一章的内容在我们springmvc拦截所有请求会导致css,js,图片等不能引入我们可以这样解决:
<!--将非mapping配置下的请求交给默认的Servlet来处理--> <mvc:default-servlet-handler/> <!--如果添加了默认servlet,mvc请求将无效,需要添加annotation-driven--> <mvc:annotation-driven></mvc:annotation-driven>
The above is the detailed content of Detailed analysis of SpringMVC views and REST style (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

What is the difference between SpringBoot and SpringMVC? SpringBoot and SpringMVC are two very popular Java development frameworks for building web applications. Although they are often used separately, the differences between them are obvious. First of all, SpringBoot can be regarded as an extension or enhanced version of the Spring framework. It is designed to simplify the initialization and configuration process of Spring applications to help developers

The difference between spring and springmvc: 1. Positioning and functions; 2. Core functions; 3. Application areas; 4. Extensibility. Detailed introduction: 1. Positioning and functions. Spring is a comprehensive application development framework that provides dependency injection, aspect-oriented programming, transaction management and other functions. It is designed to simplify the development of enterprise-level applications, and Spring MVC is the Spring framework. A module in it is used for the development of Web applications and implements the MVC pattern; 2. Core functions and so on.

SpringBoot and SpringMVC are two frameworks commonly used in Java development. They are both provided by the Spring framework, but they have some differences in functions and usage methods. This article will introduce the characteristics and differences of SpringBoot and SpringMVC respectively. 1. Features of SpringBoot: Simplified configuration: SpringBoot greatly simplifies the project configuration process through the principle of convention over configuration. It can automatically configure the parameters required by the project, and developers

The differences between springboot and springmvc are: 1. Different meanings; 2. Different configurations; 3. Different dependencies; 4. Different development times; 5. Different productivity; 6. Different ways to implement JAR packaging function; 7. Whether batch processing is provided Function; 8. Different functions; 9. Different community and documentation support; 10. Whether deployment descriptors are required.

The role of interceptor SpringMVC's interceptor is similar to the filter in Servlet development, which is used to pre-process and post-process the processor. Interceptors are connected into a chain in a certain order, and this chain is called an interceptor chain (InterceptorChain). When an intercepted method or field is accessed, the interceptors in the interceptor chain will be called in the order they were previously defined. Interceptors are also the specific implementation of AOP ideas. The difference between interceptors and filters: Filter (Filter) The scope of use of interceptor (Intercepter) is part of the servlet specification and can be used by any JavaWeb project. Spri

With the development of the Internet, Web services are becoming more and more common. As an application programming interface, JavaAPI is constantly launching new versions to adapt to different application scenarios. As a popular open source framework, SpringMVC can help us easily build web applications. This article will explain in detail how to use SpringMVC for Web service processing in JavaAPI development, including configuring SpringMVC, writing controllers, and using

Analyzing the similarities and differences between SpringBoot and SpringMVC SpringBoot and SpringMVC are very important development frameworks in the Java field. Although they are both part of the Spring framework, there are some obvious differences in usage and functionality. This article will compare SpringBoot and SpringMVC and analyze the similarities and differences between them. First, let's learn about SpringBoot. SpringBo
