Springboot Spring Web MVC Framework

Source: Internet
Author: User
Tags jboss

1, SPRINGMVC automatic configuration

Spring Boot provides automatic configuration for SPRINGMVC.

Automatic configuration contains the following characteristics of spring:

(1) View parser contentnegotiatingviewresolver or Beannameviewresolver.

(2) Support for static files, including support for Webjar.

(3) Auto-register Converter Converter, Genericconverter, Formatter.

(4) Support Httpmessageconverters (convert request, response data format)

(5) Register messagecodesresolver (conversion error code)

(6) Support static index.html

(7) Support Favicon

(8) Support automatic use of data binder Configurablewebbindinginitializer

If you want to maintain the above characteristics and add other configurations of SPRINGMVC (such as interceptors, formatters, view controllers, etc.), You want to join your own webmvcconfigureradapter with @configuration annotations, and have annotations @enablewebmvc. If you want to provide commonly used handles such as requestmappinghandlermapping, Requestmappinghandleradapter, Exceptionhandlerexceptionresolver, You can define a webmvcregistrationsadapter to provide such a component (component).

2, Httpmessageconverters

The SPRINGMVC uses the Httpmessageconverter interface to convert HTTP request and response. objects are automatically converted to JSON (using Jackson), or XML (with Jackson XML or JAXB). Strings are usually UTF-8 encoded by default.

Importorg.springframework.boot.autoconfigure.web.HttpMessageConverters;Importorg.springframework.context.annotation.*;ImportOrg.springframework.http.converter.*; @Configuration Public classmyconfiguration {@Bean Publichttpmessageconverters customconverters () {Httpmessageconverter<?> additional = ... Httpmessageconverter<?> another = ...        return NewHttpmessageconverters (additional, another); }}

Any httpmessageconverter defined in the context will be added to the converters list.

3. JSON serialization and deserialization

If you use Jackson for data serialization and deserialization, you might want to build your own tools. In fact, Spring provides @jsoncomponent to enable the beans for the corresponding class (implementing the Serializers/deserializers interface) to be converted directly to JSON. You can also annotate classes in which the inner class is serializers/deserializers.

ImportJava.io.*;ImportCom.fasterxml.jackson.core.*;Importcom.fasterxml.jackson.databind.*;Importorg.springframework.boot.jackson.*; @JsonComponent Public classExample { Public Static classSerializerextendsJsonserializer<someobject> {        // ...    }     Public Static classDeserializerextendsJsondeserializer<someobject> {        // ...    }}

All @jsoncomponent annotated beans will be automatically registered by Jackson.

4, Messagecodesresolver

Messagecodesresolver can convert the error code to an error message. As long as you set the value of Spring.mvc.message-codes-resolver.format to Prefix_error_code or postfix_error_ COD (enumeration in Defaultmessagecodesresolver.format), Spring Boot will help you create one.

5. static file Area

Spring Boot treats the default classpath or/static (or/public,/resources,/meta-inf/resources) under the root of the application as a static file area. He defaults to using Spring MVC's resourcehttprequesthandler, and you can modify the default by adding one in your own webmvcconfigureradapter and overriding the Addresourcehandlers implementation.

By default, the resource file will match/**, and you can set it through Spring.mvc.static-path-pattern, for example, setting all the files under resource to be static can be set to:

Spring.mvc. static-path-pattern=/resources/**

You can also customize the static resource area by setting the value of the spring.resources.static-locations.

Spring Boot also supports the Webjar directory, and any files packaged in Webjar form under/webjars/** are fetched in the form of a jar.

Spring boot supports versioning of static files, such as when we join Webjars-locator dependency, the "/webjars/jquery/dist/jquery.min.js" file will address "/webjars/jquery/ X.y.z/dist/jquery.min.js "for access," x.y.z "is the Webjar version.

If you use JBoss, you need to use WEBJARS-LOCATOR-JBOSS-VFS dependencies instead of webjars-locator dependencies. Some of your/wenjars/** will always report 404.

You can configure cache fragmentation with the following configuration, effectively adding a file area hash code to the URL, such as <link href= "/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>

Spring.resources.chain.strategy.content.enabled=truespring.resources.chain.strategy.content.paths =/**

The fixed policy will only add a version to the URL but does not change its name.

Spring.resources.chain.strategy.content.enabled=truespring.resources.chain.strategy.content.paths =/**spring.resources.chain.strategy.fixed.enabled= TRUESPRING.RESOURCES.CHAIN.STRATEGY.FIXED.PATHS=/JS/LIB/SPRING.RESOURCES.CHAIN.STRATEGY.FIXED.VERSION=V12

In the above configuration,/js/lib/mymodule.js will become/v12/js/lib/mymodule.js.

6, Favicon.ico

Spring Boot automatically looks for the Favicon.ico file in the static file area root directory and the classpath root directory, and once it is found, it is used as an icon.

7, Configurablewebbindinginitializer

SPRINGMVC processes a specific request by initializing a webdatabinder with Webbindinginitializer. You can build your own Configurablewebbindinginitializer bean,spring boot will automatically configure SPRINGMVC to use it.

8. Template engine

Springboot will automatically use the following template engine

Freemaker

Groovy

Thymeleaf

Mustache

Template files are usually placed under the Classpath*:templates directory.

9. Error handling

Spring Boot provides/error to match all error messages so that they are visualized. For the machine client, the page returns a JSON string containing the status and exception information, and for the browser client, the page returns an error page with error data rendering (you can override it by defining your own/error controller). If you want to completely override all of its behavior, you can implement Errorcontroller and register the bean corresponding to the implementation class, and you can also save the original mechanism by defining the bean of the Errorattributes class, replacing the content (error message).

You can use @controlleradvice to give the specified controller or exception type.

@ControllerAdvice (basepackageclasses = Foocontroller.class) Public classFoocontrolleradviceextendsResponseentityexceptionhandler {@ExceptionHandler (yourexception.class) @ResponseBody responseentity<?>handlecontrollerexception (httpservletrequest request, Throwable Ex) {httpstatus status=GetStatus (Request); return NewResponseentity<> (NewCustomerrortype (Status.value (), Ex.getmessage ()), status); }    Privatehttpstatus GetStatus (httpservletrequest request) {Integer StatusCode= (Integer) request.getattribute ("Javax.servlet.error.status_code"); if(StatusCode = =NULL) {            returnHttpstatus.internal_server_error; }        returnhttpstatus.valueof (StatusCode); }}

In the example above, if a controller throws a yourexception under the Foocontroller package, The returned results will be represented by Errorattributes-based results as JSON strings based on Customererrortype.

Custom error page

You can define the error page under/error. The error page cannot be a static HTML (that is, under any static resource directory) or a template. The file name should be the error code value or the error code match value.

For example, a 404 error

src/+-main/     +-java/     |   + <source code> +-     resources/public         /             +-error/             |   +-404.             htmlpublic assets>

5xx Error

src/+-main/     +-java/     |   + <source code> +-resources/+-         templates/+             error/             |   + -             5xx.ftl+-<other templates>

You can also configure your error message by implementing Errorviewresolver

 Public class Implements errorviewresolver {    @Override    public  Modelandview Resolveerrorview ( HttpServletRequest request,            httpstatus status, Map<string, object> model) {        // Use the request or status to optionally return a Modelandview        return ...    } 

Match SPRINGMVC External error

For errors that are not inside the SPRINGMVC, you can register the error page directly with the Errorpageregistrar interface. The interface acts directly on the embedded container, so it works even if you do not create dispatcherservlet.

  @Bean  public   Errorpageregistrar Errorpageregistrar () { return  new   Myerrorpageregistrar ();}  //  ...  private  static  class  Myerrorpageregistrar implements   Errorpageregistrar {@Override  public  void   Registererrorpages (Errorpageregistry registry) {Registry.adderrorpages (new  errorpage (httpstatus.bad_request, "/400" 

Note: Your registered error page will eventually be processed by the filter, and the filter will be registered as an error distributor (dispatcher)

@Bean  Public Filterregistrationbean Myfilter () {    new  Filterregistrationbean ();    Registration.setfilter (new  myfilter ());    ...    Registration.setdispatchertypes (Enumset.allof (dispatchertype. class ));     return registration;}

10. Spring HATEOAS

If you're editing a restful api,spring using hypermedia, it provides automatic configuration for Spring Hateoas and works well with most applications.

Use @enablehypermediasupport annotations to enable your app to support spring HATEOAS.

11. Support Cors (cross-domain)

Spring provides support for cross-domain.

can be implemented by adding annotations to the controller

  @RestController @requestmapping ( "/account" )  public   Class   AccountController {@CrossOrigin @RequestMapping ( "/{id}" )  public   account Retrieve (@PathVariable Long ID) { //  ... } @RequestMapping (method  = requestmethod.delete, Path = "/{id}" )  public  void  " Span style= "COLOR: #000000" > remove (@PathVariable Long ID) { //  ...  }}  

You can also set the global

@Configuration  Public class myconfiguration {    @Bean    public  webmvcconfigurer corsconfigurer () {          Returnnew  webmvcconfigureradapter () {            @Override            publicvoid  addcorsmappings (Corsregistry registry) {                registry.addmapping ("/api/**");            }        };    }}

Springboot Spring Web MVC Framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.