Spring4 MVC HelloWorld Annotations and Javaconfig instances

Source: Internet
Author: User


In this section, we take the Spring4 mvc HelloWorld annotation/javaconfig as an example, step-by-step to learn Spring4 MVC annotations, project settings, code, deployment, and run in a simple way.

In the previous Spring MVC 4 Hello World XML Tutorial example, we have developed a Hello World Web application using the XML configuration. However, XML is not the only way to configure a spring application. Alternatively, we can use the Java configuration to configure the application.

If you look back at the previous tutorials, you will find that we have used XML configuration in two places. The first one is spring-servlet.xml here we define the view resolver to identify real views, location searches, and scan beans through components. The second is Web. XML, we define the front controller configuration and the URL pattern will be looked for matching.

In this tutorial, we'll create an example of Hello world again, but this time we'll use the Java configuration. We will delete the XML files mentioned above and replace these XML configurations with their corresponding java.

The following technology stacks need to be used:
    • Spring 4.0.6.RELEASE
    • Maven 3
    • JDK 1.6
    • Tomcat 8.0.21
    • Eclipse JUNO Service Release 2

Now let's get started!

1th Step: Create the required directory structure project

Article use Eclipse to create a MAVEN Web project that includes a step-by-step wizard using Eclipse to create a MAVEN project.

The following will be the final project structure.

Now, let's Add/update the above to discuss the contents of each of the details mentioned in the project structure. 2nd step: Update Pom.xml using spring and servlet dependencies

We want to discuss the Spring Java-based configuration depending on the API of Servlet 3.0, so we need to include dependencies in Pom.xml.

<?xml version= "1.0"? ><project xsi:schemalocation= "http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "xmlns=" http://maven.apache.org/POM/4.0.0 "xmlns:xsi=" http://www.w3.org/ 2001/xmlschema-instance "><modelversion>4.0.0</modelversion><groupid>com.yiibai.springmvc </groupid><artifactid>spring4mvchelloworldnoxmldemo</artifactid><packaging>war</ packaging><version>1.0.0</version><name>spring4mvchelloworldnoxmldemo</name>< Properties><springframework.version>4.0.6.release</springframework.version></properties> <dependencies><dependency><groupId>org.springframework</groupId><artifactId> Spring-webmvc</artifactid><version>${springframework.version}</version></dependency> <dependency><groupid>javax.servlet</groupid><artifactid>javax.servlet-api</ Artifactid><version>3.1.0</versiOn></dependency><dependency><groupid>javax.servlet.jsp</groupid><artifactid> Javax.servlet.jsp-api</artifactid><version>2.3.1</version></dependency><dependency ><groupid>javax.servlet</groupid><artifactid>jstl</artifactid><version>1.2 </version></dependency></dependencies><build><pluginManagement><plugins> <plugin><groupid>org.apache.maven.plugins</groupid><artifactid>maven-war-plugin</ Artifactid><version>2.4</version><configuration><warsourcedirectory>src/main/webapp </warsourcedirectory><warname>spring4mvchelloworldnoxmldemo</warname><failonmissingwebxml >false</failonmissingwebxml></configuration></plugin></plugins></ Pluginmanagement><finalname>spring4mvchelloworldnoxmldemo</finalname></build></project > 

The first thing to note here is the Maven-war-plugin plugin declaration. As we will completely remove Web. XML, we need to configure this plugin to avoid the MAVEN build war package failure. The second change is to join the Jsp/servlet/jstl dependency, which we may need because we are going to use the Servlet API and the Jstl view in our code. In general, containers already contain these libraries, which are provided for them in pom.xml, and we can set the scope of the action.

3rd Step: Add the controller to add a controller class under Src/main/java, as follows:

Com.yiibai.springmvc.controller.HelloWorldController

Package Com.yiibai.springmvc.controller;import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.RequestMethod; @Controller @requestmapping ("/") public class Helloworldcontroller {@RequestMapping (method = requestmethod.get) public String SayHello (Modelmap model) { Model.addattribute ("Greeting", "Hello World from Spring 4 MVC"); return "Welcome";} @RequestMapping (value = "/helloagain", method = requestmethod.get) public String Sayhelloagain (Modelmap model) { Model.addattribute ("Greeting", "Hello World Again, from Spring 4 MVC"); return "Welcome";}}

In the class name @controller note declares the spring bean of this class and the @RequestMapping annotation declares that this class is the default handler for all requests that type "/". The first method does not declare any mappings, it will inherit the mapping declaration of the mappings at the class level, and the GET request is processed by default. Method Two (because additional mapping declarations use the Value property) Form/hello will be requested again. The property method says what kind of HTTP request this method can serve.

method to say what kind of HTTP request this method can serve. Modelmap is a map implementation, here as an alternative to the [Request.getattribute ()/request.setattribute ()] SetPoint as a request attribute. Notice that we return the "Welcome" string from this method. This string will be the suffix and prefix suffix, defined in the View parser prefix (see spring-servlet.xml above), to form a true view file name.

4th step: Add a View

Create a new folder named views in the Web-inf directory, and add a simple JSP page welcome.jsp (web-inf/views/welcome.jsp) from the controller to the simple access mode value.

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" Utf-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
5th step: Add a Configuration Class

Under Src/main/java, add the following class for the specified package, as shown in. This construction class can be seen as an alternative to Spring-servlet.xml because it contains all the necessary components for the scan and view resolver information.

Com.yiibai.springmvc.configuration.HelloWorldConfiguration

Package Com.yiibai.springmvc.configuration;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.enablewebmvc;import Org.springframework.web.servlet.view.internalresourceviewresolver;import Org.springframework.web.servlet.view.JstlView; @Configuration @enablewebmvc@componentscan (basepackages = " COM.YIIBAI.SPRINGMVC ") public class Helloworldconfiguration {@Beanpublic viewresolver viewresolver () { Internalresourceviewresolver viewresolver = new Internalresourceviewresolver (); Viewresolver.setviewclass ( Jstlview.class); Viewresolver.setprefix ("/web-inf/views/"); Viewresolver.setsuffix (". jsp"); return viewresolver;}}

@Configuration indicates that the class contains annotations for @bean production bean management is one or more bean methods by the spring container. The above configuration class corresponds to the following XML:

 <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:context= "http://www.springframework.org /schema/context "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xmlns:xsi=" http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans/http Www.springframework.org/schema/beans/spring-beans-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC/HTTP Www.springframework.org/schema/mvc/spring-mvc-4.0.xsd Http://www.springframework.org/schema/context/HTTP Www.springframework.org/schema/context/spring-context-4.0.xsd "><context:component-scan base-package=" Com.yiibai.springmvc "/><mvc:annotation-driven/><beanclass=" Org.springframework.web.servlet.view.InternalResourceViewResolver "><property name=" prefix "><value >/web-inf/views/</value></property><property name= "suffix" ><value>.jsp</value> </property></bean></beans> 

@EnableWebMvc is equivalent to Mvc:annotation-driven in XML. It can map the @controller-annotated class for requests that use @requestmapping to a specific method.

@ComponentScan equivalent to Context:component-scan base-package= "..." Provides spring where to look for management beans/classes.

6th step: Adding initialization classes

Add an initialization class implementation webapplicationinitializer in Src/main/java using the specified package as shown (in this case, as an alternative to any Spring configuration defined in Web. xml). When a Servlet 3.0 container is started, the class is loaded and initialized, and the method is called by the servlet container at startup.

Com.yiibai.springmvc.configuration.HelloWorldInitializer

 Package Com.yiibai.springmvc.configuration;import Javax.servlet.servletcontext;import Javax.servlet.servletexception;import Javax.servlet.servletregistration;import Org.springframework.web.webapplicationinitializer;import Org.springframework.web.context.support.annotationconfigwebapplicationcontext;import Org.springframework.web.servlet.dispatcherservlet;public class Helloworldinitializer Implements Webapplicationinitializer {public void Onstartup (ServletContext container) throws Servletexception { Annotationconfigwebapplicationcontext CTX = new Annotationconfigwebapplicationcontext (); Ctx.register ( Helloworldconfiguration.class); Ctx.setservletcontext (container); Servletregistration.dynamic servlet = Container.addservlet ("Dispatcher", New Dispatcherservlet (CTX)); Servlet.setloadonstartup (1); Servlet.addmapping ("/");}}   

The content above resembles the content of Web. XML in the previous tutorial because we are using the front-end controller dispatcherservlet, assigning mappings (URL schema XML) and not providing the path to the Spring configuration file (spring-servlet.xml) , here we are registering the configuration class. In general, we are doing the same thing, just in a different way.

Update: Note that now you can more succinctly write the above class [and its best method] to extend the Abstractannotationconfigdispatcherservletinitializer class as follows:

Package Com.yiibai.springmvc.configuration;import Org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer;public class Helloworldinitializer extends Abstractannotationconfigdispatcherservletinitializer {@Overrideprotected class<? >[] Getrootconfigclasses () {return new class[] {helloworldconfiguration.class};} @Overrideprotected class<?> [] getservletconfigclasses () {return null;} @Overrideprotected string[] Getservletmappings () {return new string[] {"/"}; }}
7th step: Build and deploy your application

One thing to keep in mind is that the Java-based configuration API, like Webapplicationinitializer,spring, relies on the Servlet3.0 container. Make sure that you are not using the servlet to declare any less than 3.0. For our case, we will remove the Web. xml file from the application.

Now build the war (either as the last tutorial mentioned in Eclipse) or through MAVEN's command line (mvn clean install). Deploy the war to the Servlet3.0 container. Since I am using tomcat here, I simply put the war file into the Tomcat WebApps folder and then click Start.bat to run it in the Tomcat bin directory.

or right-click Project =>run as + maven install, once again right-click Project =>run as + maven build, pop-up selection:

To run the application, let's now access Url:http://localhost:8080/spring4mvchelloworldnoxmldemo, which shows the results as shown below:


That's it, finish!

Code Download: Http://pan.baidu.com/s/1nugPMcT

Spring4 MVC HelloWorld Annotations and Javaconfig instances

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.