Java EE development SpringMVC project managed by Maven, mavenspringmvc

Source: Internet
Author: User

Java EE development SpringMVC project managed by Maven, mavenspringmvc

The previous blogs have already talked about Spring. Today we will talk about Spring MVC. SpringMVC currently has a place in JavaEE development and is easy to use. Low coupling and high cohesion. Some annotations and Java configuration classes can be used to achieve good decoupling. Today, let's take a look at how to use Maven to configure SpringMVC and use it in our Web project.

This blog is the continuation of the previous blog. In the previous blog, we talked in detail about the configuration of the Java environment, the installation of Eclipse in the Java EE version, and the installation and configuration of Maven, install and configure Tomcat. We have installed M2Eclipse and STS plug-ins for our Eclipse. And a Maven-managed Web App is created. This blog is based on the Web App project created in the previous blog. For details about the previous blog, go to Java EE development Eclipse-based environment building and Maven Web App creation.

 

I. Preparations before SpringMVC is introduced

In the previous blog, we created a Maven-managed Web App. The content below isSpringMVC. A directory is missing in the project we created. In SpringMVC, anotherSrc/test/resourcesDirectory, but the project we just created does not exist, so we have to create this directory, right-clickJava Resources-> New-> Source Folder. The details are as follows:

  

 

Select our project and enter our Folder name, as shown below.

  

 

After adding the directory, We need to edit the Output folder of the directory created above. Let's take a look at the Output folder in the src/test/java Directory, which is taget/test-classes. The newly added src/test/resouces must also be set to target/test-classes. Select the entry and edit it, as shown in the following figure.

  

 

Select test-classes when editing, and click OK to complete the settings, as shown below:

  

 

2. Configure SpringMVC through Maven

The above preparations are ready. Next we should use Maven to configure SpringMVC. This part will be in pom. add spring MVC and its dependent libraries in xml, introduce our SpringMVC-related items through Java configuration, and finally give a simple example.

 

1. Configure the dependency library in pom. xml

The configuration of Maven pom. xml is not described too much here, Maven official website (http://maven.apache.org/) has a detailed instance. The POM Reference provides specific Pom configuration solutions. So I won't go into details about the configuration of pom. xml in this blog. For more details, visit the official website.

  

 

Third-party libraries supported by Maven can be found at http://mvnrepository.com/. you can search for the desired database in the search box and obtain the desired database. As follows:

  

 

 

First, add some attributes to pom. xml. These attributes will be used when configuring the dependency library, most of which are the versions of some dependent libraries. These attributes are similar to macro-defined attributes for later version changes. Below is all the properties of the project involved in this blog, as shown below:

  

Then add the unit test dependency and the spring-webmvc dependency, as shown below. Below spring-webmvc is configured with the spring-version defined above.

  

Then add the jstl template library, servlet, and jsp dependency library, as shown below. Of course, different databases correspond to different version attribute values, as shown below:

  

 

Then add SLF4J and LogBack to output logs, as shown below:

  

Finally, we added our Maven plug-in. The version of this plug-in is the version of the M2Eclipse plug-in we installed earlier, as shown below:

  

Below is the complete content of pom. xml in the project involved in this blog:

<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/maven-v4_0_0.xsd"> <modelVersion> 4.0.0 </modelVersion> <groupId> com. zeluli </groupId> <artifactId> SpringMVCWithMaven </artifactId> <packaging> war </packaging> <version> 0.0.1-SNAPSHOT </version> <name> springmvcwithmavmave N Webapp </name> <url> http://maven.apache.org </url> <properties> <! -- Generic properties --> <java. version> 1.8 </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. version> 4.3.6.RELEASE </spring. version> <! -- Logging --> <logback. version> 1.2.1 </logback. version> <slf4j. version> 1.7.21 </slf4j. version> </properties> <dependencies> <! -- Unit test dependency --> <dependency> <groupId> junit </groupId> <artifactId> junit </artifactId> <version> 3.8.1 </version> <scope> test </ scope> </dependency> <! -- Spring MVC --> <dependency> <groupId> org. springframework </groupId> <artifactId> spring-webmvc </artifactId> <version >$ {spring. version }</version> </dependency> <! -- Web dependency --> <dependency> <groupId> javax. servlet </groupId> <artifactId> jstl </artifactId> <version >$ {jstl. version }</version> </dependency> <groupId> javax. servlet </groupId> <artifactId> javax. servlet-api </artifactId> <version >$ {servlet. version }</version> <scope> provided </scope> </dependency> <groupId> javax. servlet. jsp </groupId> <artifactId> jsp-api </artifactId> <version >$ {jsp. Version }</version> <scope> provided </scope> </dependency> <! -- Added support for object conversion to json or xml --> <! -- Https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml --> <dependency> <groupId> com. fasterxml. jackson. dataformat </groupId> <artifactId> jackson-dataformat-xml </artifactId> <version> 2.8.6 </version> </dependency> <! -- Added support for json Data Binding --> <! -- Https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId> com. fasterxml. jackson. core </groupId> <artifactId> jackson-databind </artifactId> <version> 2.8.6 </version> </dependency> <! -- Use SLF4J and LogBack as logs --> <dependency> <groupId> org. slf4j </groupId> <artifactId> slf4j-api </artifactId> <version >$ {slf4j. version }</version> </dependency> <groupId> ch. qos. logback </groupId> <artifactId> logback-classic </artifactId> <version >$ {logback. version }</version> </dependency> <groupId> ch. qos. logback </groupId> <artifactId> logback-core </artifactId> <version >$ {logback. version }</version> </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-complier-plugin </artifactId> <version> 3.3.9 </version> <configuration> <source >$ {java. version} </source> <target >$ {java. version }</target> </configuration> </plugin> </plugins> <finalName> SpringMVCWithMaven </finalName> </build> </project>
Pom. xml

 

After the configuration is complete, we will see the packages in our project in the directory, as shown below:

  

 

2. configure our SpringMVC

First, create a package in the src/main/java directory to store SpringMVC-related items. Create a Java class in the package and name it SpringMVCConfig. Then use Spring's@ ConfigurationDeclare the annotation as a configuration class, and then use@ EnableWebMvcEnable WebMvc. Then configure in the Java configuration fileInternalResourceViewResolverClass Bean. Simply put, we have configured a View Resolver for JSP. As shown below.

  

The corresponding code in this class is as follows:

package com.zeluli.springmvc;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;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("com.zeluli.springmvc")public class SpringMVCConfig  extends WebMvcConfigurerAdapter {        @Bean    public InternalResourceViewResolver viewResolver(){        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();        viewResolver.setPrefix("/WEB-INF/classes/views/");        viewResolver.setSuffix(".jsp");        viewResolver.setViewClass(JstlView.class);        return viewResolver;    }        }

 

3. Web Initialization

After configuring Spring, we also need to create a class for Web initialization. That is, WebInitalier. Below is the creation process of this class. When we create this class, we need to implement the WebApplicationInitializer interface in Spring framework, as shown below:

  

What is done in this class is also relatively simple. assign values to load the context of Spring configuration and associate it with ServletContext. Then create the DispatcherServlet of SpringMVC.

  

The complete code of the above class is as follows:

package com.zeluli.springmvc;import javax.servlet.ServletRegistration.Dynamic;import javax.servlet.ServletContext;import javax.servlet.ServletException;import org.springframework.web.WebApplicationInitializer;import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.servlet.DispatcherServlet;public class WebInitializer implements WebApplicationInitializer {    public void onStartup(ServletContext servletContext) throws ServletException {                AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();        context.register(SpringMVCConfig.class);        context.setServletContext(servletContext);                Dynamic servlet = (Dynamic) servletContext.addServlet("dispatcher", new DispatcherServlet(context));        servlet.addMapping("/");        servlet.setLoadOnStartup(1);    }}

 

 

4. Create a Controller

After the configuration is complete, create our Controller. Create a web package under the springmvc package and then create a Controller class. Here we declare it as FirstController, as shown below. Then, the @ Controller annotation is used to tell the Spring framework that this is a Controller class.

In this Controller class, there is a success () value assignment ing, Which is mapped to the index. jsp page when you access/index routing. As shown below.

  

 

5. Create index. jsp

Finally, we created our jsp page. Our jsp page is placed in the src/main/resources directory. Create a view to accommodate the front-end page, and create an index. jsp page. Of course, when creating this page, you need to delete the index. jps page under the webapp, and then add some divs and styles to the index. jsp page.

  

 

6. Run

After all the above steps, the next step is the moment when we finally win in tears. Select our Tomcat server to run the project. If you see the page below, your previous configuration is correct. SpringMVC's introduction and configuration have come to an end. Below is the long-awaited page.

I will not repeat the log configuration here. The Demo involved in this blog will still be shared on github.

Github-Demo source code share address: https://github.com/lizelu/SpringMVCWithMaven

Related Article

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.