Home  >  Article  >  Java  >  Detailed analysis of SpringMVC views and REST style (with code)

Detailed analysis of SpringMVC views and REST style (with code)

不言
不言Original
2018-09-26 15:26:512170browse

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!

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