A dot eyeball.

Spring MVC provides a DispatcherServlet to develop Web applications. With Servlet2.5 and below, you simply configure the element under web.xml. But here we use Servlet3.0 + no web. XML configuration mode, in the Spring MVC implementation WebApplicationInitializer interface can be equivalent to web. XML configuration.

The following will build a zero-configuration Spring MVC prototype project based on Maven.

Example 2.

1. Build Maven projects quickly

Note: The contents of this series of articles depend on each other. The contents of the later chapters depend on the configuration of the previous chapters. Maven is a multi-module project. The common dependency configuration is in the parent project’s POm. XML file. If you can’t find dependencies in the current project’s POM file, you can check the parent project’s configuration.

The contents of pom.xml are as follows:

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > springMvc4. X - learning < / groupId > < artifactId > springMvc4. X - learning < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < packaging > pom < / packaging > <name>springMvc4.x-learning</name> <url>http://blog.longjiazuo.com</url> <modules> <module>springMvc4.x-quickStart</module> </modules> <properties> <! -- Generic properties --> <java.version>1.7</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <! -- Web --> <jsp.version>2.2</jsp.version> <jstl.version>1.2</jstl.version> <servlet.version>3.1.0</servlet.version> <! -- Spring --> <spring-framework.version>4.1.5.RELEASE</spring-framework.version> <! Logging --> <logback.version>1.0.13</logback.version> <slf4j.version>1.7.5</slf4j.version> </properties> <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <! -- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-framework.version}</version> </dependency> <! Servlet </groupId> <artifactId> JSTL </artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> <! -- Spring and Transactions --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-framework.version}</version> </dependency> <! SLF4J </groupId> <artifactId> slf4J-api </artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> < version > 1.2.16 < / version > < / dependency > < the dependency > < groupId > org. Slf4j < / groupId > <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-access</artifactId> <version>${logback.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> < version > < / version 2.3.2 > < configuration > < source > ${Java version} < / source > < target > ${Java version} < / target > </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> The < artifactId > maven - war - the plugin < / artifactId > < version > 2.3 < / version > < configuration > <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>Copy the code

2. Log configuration

In the SRC /main/resources directory, create logback. XML to configure the log as follows:

<? The XML version = "1.0" encoding = "utf-8"? > <configuration scan="true" scanPeriod="1 seconds"> <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"> <resetJUL>true</resetJUL> </contextListener> <jmxConfigurator/> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>logbak: %d{HH:mm:ss.SSS} %logger{36} - %msg%n</pattern> </encoder> </appender> <logger name="org.springframework.web" level="DEBUG"/> <! <root level="info"> <appender-ref ref="console"/> </root> </configuration>Copy the code

Code explanation:

Set the logging level of classes in org.SpringFramework. web package to DEBUG. We often have 4XX errors related to parameter types when developing Spring MVC. Setting this will give you more detailed error messages.

3. Demo page

SRC /main/resources directory and create index.jsp under this directory.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <pre> Welcome to Spring MVC world </pre> </body> </html>Copy the code

Code explanation:

You may be wondering why the page is not placed under Maven’s standard SRC /main/ webApp /WEB-INF. The main purpose of this is to get used to the way Spring Boot pages are placed. Spring Boot pages are placed under SRC /main/ Resources.

4. Spring MVC configuration

package org.light4j.springMvc4; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @configuration @enableWebMVC // ① @ComponentScan(" org.light4j.springmvc4 ") public class MyMvcConfig extends WebMvcConfigurerAdapter {/ / (2) @ Bean public InternalResourceViewResolver viewResolver () {InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/classes/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return viewResolver; }}Copy the code

Code explanation:

There’s nothing special here, just a normal Spring configuration class. Here I’ve configured the ViewResolver of the JSP to map the path to the actual page location, where the @enableWebMVC annotation will enable some default configurations, such as some ViewResolver or MessageConverter.

In particular, I want to explain the Spring MVC ViewResolver, which is the core mechanism for rendering Spring MVC views (JSP or HTML). Spring MVC has an interface called ViewResolver(all viewResolvers implement this interface), which is implemented by overriding the method resolveViewName(), whose return value is interface View, The View’s job is to take model, Request, and Response objects and return the rendered View (not necessarily HTML, but JSON, XML, or PDF) to the browser. I’ll talk more about ViewResolver in a future article.

You might set the current path prefix to/WEB-INF/classes/views/Some strange, how and I developed the directory is inconsistent? Because the page we see is run-time code, not development-time code, the run-time code will automatically compile our page to/WEB-INF/classes/views/The following image shows the directory structure at runtime so that we can understand why the prefix is written this waySpring BootIn the useThymeleafAs a template, this setup will not be required.

5. Web configuration

package org.light4j.springMvc4; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration.Dynamic; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; Public class WebInitializer implements WebApplicationInitializer {/ / 1. @ Override public void onStartup (ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(MyMvcConfig.class); ctx.setServletContext(servletContext); / / (2) the Dynamic servlet = servletContext. AddServlet (" the dispatcher, "new DispatcherServlet (CTX)); / / (3) the servlet. AddMapping ("/"); servlet.setLoadOnStartup(1); }}Copy the code

Code explanation:

1) WebApplicationInitializer is to provide used to configure Spring Servlet3.0 + configuration interface, so as to realize alternative web. The location of the XML. Implement this interface will automatically be SpringServletContainerInitializer (to start Servlet3.0 container) is available. Create a WebApplicationContext, register the configuration class, and associate it with the current servletContext. ③ Register Spring MVC’s DispatcherServlet.

6. Simple controller

package org.light4j.springMvc4.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @controller // ① public class HelloController {@requestMapping ("/index") // ② public String hello() {return "index"; }}Copy the code

Code explanation:

① Declare a Controller with the @Controller annotation. ② Use @requestMapping to configure the mapping between urls and methods. / web-INF /classes/views/

7. To run

Deploy the program toTomcatIn, I set itTomcatThe port is80, now startTomcatAnd accesshttp://localhost/springMvc4.x-quickStart/index.

The running results are as follows:

Three. Source code examples:

Github Address: Click to view code cloud address: click to view

exceptional
Welcome to follow the life designer’s wechat public account



longjiazuoA