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
SpringBoot与SpringMVC的比较及差别分析SpringBoot与SpringMVC的比较及差别分析Dec 29, 2023 am 11:02 AM

SpringBoot和SpringMVC都是Java开发中常用的框架,但它们之间有一些明显的差异。本文将探究这两个框架的特点和用途,并对它们的差异进行比较。首先,我们来了解一下SpringBoot。SpringBoot是由Pivotal团队开发的,它旨在简化基于Spring框架的应用程序的创建和部署。它提供了一种快速、轻量级的方式来构建独立的、可执行

比较SpringBoot与SpringMVC的差异是什么?比较SpringBoot与SpringMVC的差异是什么?Dec 29, 2023 am 10:46 AM

SpringBoot与SpringMVC的不同之处在哪里?SpringBoot和SpringMVC是两个非常流行的Java开发框架,用于构建Web应用程序。尽管它们经常分别被使用,但它们之间的不同之处也是很明显的。首先,SpringBoot可以被看作是一个Spring框架的扩展或者增强版。它旨在简化Spring应用程序的初始化和配置过程,以帮助开发人

SpringBoot与SpringMVC的区别是什么?SpringBoot与SpringMVC的区别是什么?Dec 29, 2023 pm 05:19 PM

SpringBoot和SpringMVC是Java开发中常用的两个框架,它们都是由Spring框架所提供的,但在功能和使用方式上有着一些区别。本文将分别介绍SpringBoot和SpringMVC的特点和区别。一、SpringBoot的特点:简化配置:SpringBoot通过约定优于配置的原则,大大简化了项目的配置过程。它可以自动配置项目所需要的参数,开发人

Java的SpringMVC拦截器怎么用Java的SpringMVC拦截器怎么用May 13, 2023 pm 02:55 PM

拦截器(interceptor)的作用SpringMVC的拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。将拦截器按一定的顺序联结成一条链,这条链称为拦截器链(InterceptorChain)。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。拦截器也是AOP思想的具体实现。拦截器和过滤器区别区别过滤器(Filter)拦截器(Intercepter)使用范围是servlet规范中的一部分,任何JavaWeb工程都可以使用是Spri

springboot和springmvc有哪些区别springboot和springmvc有哪些区别Jun 07, 2023 am 10:10 AM

springboot和springmvc区别是:​1、含义不同;2、配置不同;3、依赖项不同;4、开发时间不同;5、生产力不同;6、实现JAR打包功能的方式不同;7、是否提供批处理功能;8、作用不同;9、社区和文档支持不同;10、是否需要部署描述符。

Java API 开发中使用 SpringMVC 进行 Web 服务处理Java API 开发中使用 SpringMVC 进行 Web 服务处理Jun 17, 2023 pm 11:38 PM

随着互联网的发展,Web服务越来越普遍。JavaAPI作为一种应用编程接口,也在不断地推出新的版本来适应不同的应用场景。而SpringMVC作为一种流行的开源框架,能够帮助我们轻松地构建Web应用程序。本文将详细讲解在JavaAPI开发中,如何使用SpringMVC进行Web服务处理,包括配置SpringMVC、编写控制器、使用

spring和springmvc有哪些区别spring和springmvc有哪些区别Dec 29, 2023 pm 05:02 PM

spring和springmvc的区别:1、定位和功能;2、核心功能;3、应用领域;4、扩展性。详细介绍:1、定位和功能,Spring是一个综合性的应用程序开发框架,提供了依赖注入、面向切面编程、事务管理等功能,旨在简化企业级应用程序的开发,而Spring MVC是Spring框架中的一个模块,用于Web应用程序的开发,实现了MVC模式;2、核心功能等等。

面试官:你说的SpringMVC的请求处理流程是网上抄的吧?面试官:你说的SpringMVC的请求处理流程是网上抄的吧?Jul 26, 2023 pm 04:34 PM

本文主要从源码的阅读和调试的角度,整体的讲解了SpringMVC处理请求的整个流程,并且讲解了参数的绑定以及返回值的处理。相信大家看完后,结合自己的调试信息,会对SpringMVC的请求处理过程有一个更深入的理解。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)