Spring MVC starts
1. The request process for Spring MVC
2. Build Spring MVC
2.1 Using Java to build Spring MVC (requires servlet 3.0 environment)
Configuring Dispatcherservlet and Contextloaderlistener
Package spittr.config;
Import Org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class Spittrwebappinitializer extends abstractannotationconfigdispatcherservletinitializer{
// corresponding Contextloaderlistener
@Override
protected class<?>[] getrootconfigclasses () {
return new Class <?>[] {rootconfig.class};
}
For Dispatcherservlet
@Override
protected class<?>[] getservletconfigclasses () {
return new Class<?>[] {webconfig.class};//specify configuration Class
}
@Override
protected string[] Getservletmappings () {
return new string[] {"/"};//map Dispatcherservlet to "/"
}
}
Abstractannotationconfigdispatcherservletinitializer anatomy
In the Servlet3.0 environment, the container looks for the class that implements the Javax.servlet.ServletContainerInitializer interface in the Classpath and, if found, configures the servlet container. Spring provides the implementation of this interface, called Springservletcontainerinitializer, which in turn finds classes that implement Webapplicationinitializer and gives them the configured tasks to complete. Spring3.2 introduced a convenient Webapplicationinitializer basic implementation, namely Abstractannotationconfigdispatcherservletinitializer. Because our Spittrwebappinitializer expands the Abstractannotationconfigdispatcherservletinitializer (and also implements the Webapplicationinitializer) , so when deployed to the Servlet3.0 container, the container automatically discovers it and uses it to configure the servlet context.
Abstractannotationconfigdispatcherservletinitializer will create both Dispatcherservlet and Contextloaderlistener. The class with @configuration annotations returned by the Getrootconfigclasses method will be used to define the bean for the Contextloaderlistener application context. The class with @configuration annotations returned by the Getservletconfigclasses method will be used to define the bean for the Dispatcherservlet application context. We want Dispatcherservlet to load the beans that contain the Web components, such as the controller, view resolver, and processor mappings, and Contextloaderlistener to load the other beans in the app. These beans are typically the middle-tier and data-tier components that drive the application backend.
Configure Spring MVC
Package spittr.config;
Import Org.springframework.context.annotation.Bean;
Import Org.springframework.context.annotation.ComponentScan;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.web.servlet.ViewResolver;
Import Org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
Import ORG.SPRINGFRAMEWORK.WEB.SERVLET.CONFIG.ANNOTATION.ENABLEWEBMVC;
Import Org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
Import Org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc//Enable spring MVC @ComponentScan ("Spittr.web")//Enable component Scan public class Webconfig extends webmvcconfigureradapter{/** * Configure JSP View resolver * @return */@Bean public viewresolver Viewresolver
() {Internalresourceviewresolver resolver = new Internalresourceviewresolver ();
Resolver.setprefix ("/web-inf/view/");
Resolver.setsuffix (". jsp"); Resolver.Setexposecontextbeansasattributes (TRUE);
return resolver;
/** * Configuring the processing of static resources requires Dispatcherservlet to forward requests for static resources to the Servlet container's default servlet instead of using Dispatcherservlet itself to handle such requests
*/@Override public void configuredefaultservlethandling (Defaultservlethandlerconfigurer configurer) {
Configurer.enable ();
}
}
Customizing the Dispatcherservlet Configuration
In Spittrwebappinitializer we rewrote three methods to configure Dispatcherservlet, and there are actually more ways to overload the Dispatcherservlet for additional configuration.
One way is to customizeregistration (), After Abstractannotationconfigdispatcherservletinitializer registers the Dispatcherservlet with the servlet container, The Customizeregistration () is called, and Registration.dynamic is passed in after the servlet has been registered. By overloading the Customizeregistration () method, we can make additional configuration for the Dispatcherservlet. For example, set Multipartconfigelement:
@Override
protected void Customizeregistration (Dynamic registration) {
Registration.setmultipartconfig (
new Multipartconfigelement ("/tmp/spittr/uploads"));
}
As to whether this setting is very busy, we will introduce it in the spring upload.
Add additional servlets and filter
If we want to register other servlets, filter, or listener in the Web container, we can implement spring's Webapplicationinitializer ( As we said before, the Servlet3.0 container automatically looks for its implementation class and is used to configure the servlet container. For example, inject a servlet and a filter:
Import Javax.servlet.ServletContext;
Import javax.servlet.ServletException;
Import Org.springframework.web.WebApplicationInitializer;
public class Myservletinitializer implements webapplicationinitializer{public
void Onstartup (ServletContext ServletContext) throws Servletexception {
//register servlet
javax.servlet.ServletRegistration.Dynamic myservlet =
Servletcontext.addservlet ("Myservlet", myservlet.class);
Myservlet.addmapping ("/custom/**");//Map servlet
javax.servlet.FilterRegistration.Dynamic myfilter =
Servletcontext.addfilter ("Myfilter", myfilter.class);
Myfilter.addmappingforurlpatterns (null, FALSE, "/custom/**");//Add filter's mapping Path
}
}
If you just register the filter and map it to Dispatcherservlet, there's a handy way to do it in Abstractannotationconfigdispatcherservletinitializer- Overloaded Getservletfilters () method:
@Override
protected filter[] Getservletfilters () {
return new filter[] {new Myfilter ()};
}
2.2 Configuring Spring MVC in Web. xml:
Xml:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance http://www.springmodules.org/schema/cache/ Springmodules-cache.xsd http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd "xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" > <!--Specify a spring frame to be Location of files, Contextloaderlistener-<context-param> <param-name>contextconfiglocation</ param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> < ;listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class > </listener> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-c Lass>org.springframework.web.servlet.dispatcherservlet</servlEt-class> <init-param> <!--Specify the location of the Spring MVC application Context profile, and if not specified here, the configuration file will be found based on the servlet name-context- <param-name>contextConfigLocation</param-name> <param-value>classpath:dispatcherservlet-co ntext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </SERVLET&G
T <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</ Url-pattern> </servlet-mapping> </web-app>
Applicationcontext.xml:
<?xml version= "1.0" encoding= "UTF-8"?> <beans
xmlns= "Http://www.springframework.org/schema/beans"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "
xmlns:tx=" Http://www.springframework.org/schema/tx "xmlns:context=" http://www.springframework.org/schema/ Context "
xsi:schemalocation="
Http://www.springframework.org/schema/beans/http Www.springframework.org/schema/beans/spring-beans-3.0.xsd
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/http Www.springframework.org/schema/tx/spring-tx-3.0.xsd
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/http Www.springframework.org/schema/aop/spring-aop-3.0.xsd
Http://www.springframework.org/schema/context/http Www.springframework.org/schema/context/spring-context-3.0.xsd ">
<bean id=" test "class=" spittr.web.Test "/>
<context:component-scan base-package=" spittr "/>
</beans>
Dispatcherservlet-context.xml:
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.0.xsd "> <bean id=" viewresolver "class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix ">/web-inf/& lt;/property> <property name= "SuffIX ">.jsp</property> </bean> </beans>
2.3 Let Web. XML use a Java configuration instead of a configuration
also means that spring MVC loads the configuration from a class with @configuration annotations when it is started, We need to tell Dispatcherservlet and Contextloaderlistener to use Annotationconfigwebapplicationcontext, This is a Webapplicationcontext implementation class that loads the Java configuration class instead of using XML. To implement this configuration, we only need to set the Contextclass context parameters and the initialization parameters of the Dispatcherservlet.
<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance http://www.springmodules.org/schema/cache/ Springmodules-cache.xsd http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd "xsi:schemalocation=
"Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" > <!--using Java configuration-- <context-param> <param-name>contextClass</param-name> <param-value>org.springfra Mework.web.context.support.annotationconfigwebapplicationcontext</param-value> </context-param> < Context-param> <param-name>contextConfigLocation</param-name> <!--Specify configuration class--<param-va lue>spittr.config.rootconfig</param-value> </context-param> <listener> <listener-class> ; org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcherservlet</ Servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> & lt;! --Using Java configuration-<init-param> <param-name>contextClass</param-name> <param-valu E>org.springframework.web.context.support.annotationconfigwebapplicationcontext</param-value> </ Init-param> <init-param> <param-name>contextConfigLocation</param-name> <!--means Configuration Class-<param-value>spittr.config.WebConfig</param-value> </init-param> <load-on -startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name> dispatcherservlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </ Web-app>
Controller
Placeholder
Spring MVC allows us to add placeholders in the @requestmapping path. The names of the placeholders are enclosed in curly braces ("{" and "}"). The other parts of the path exactly match the request being processed, but the placeholder part is any value.
Package spittr.web;
Import org.springframework.web.bind.annotation.PathVariable;
Import org.springframework.web.bind.annotation.RequestMapping;
public class Spittler {
@RequestMapping ("/{spittleid}") Public
String spittle (
@PathVariable ("Spittleid ") long Spittleid) {
System.out.println (Spittleid);
Return "page";
}
}
Thus, in the request path, whatever the value of the placeholder part will be passed to the Spittleid parameter of the processor method.
If the value attribute is not in @pathvariable, it assumes that the name of the placeholder is the same as the parameter name of the method.
Redirect and go to the specified URL path
return "redirect:/spitter/";//redirect
return "Forward:/spitter";//go to the specified URL path
Form Inspection
Starting with Spring3.0, support for the Java Validation API is provided in Spring MVC.
public class User {
@NotNull
@Size (min=5,max=16)
private String userName;//non-null, 5-16 characters
@NotNull
@Size (min=6, max=10)
private String password;//non-empty, 6-10 characters
}
Package spittr.web;
Import org.springframework.validation.Errors;
Import org.springframework.validation.annotation.Validated;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Spittr.entity.User;
public class Spittler {
@RequestMapping ("/login") public
String spittle (
@Validated User user,//Checksum input
Errors Errors) {
if (errors.haserrors ()) {
return "registerform";//If the checksum has an error, return the form again.
}
return "redirect:/spitter/";
}
}
The errors parameter is immediately following the parameter with the checksum annotation.