search
HomeJavajavaTutorialDetailed 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 id="Spring-nbsp-MVC-nbsp-Custom-nbsp-view">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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools