Spring 4 MVC HelloWorld-Annotated/javaconfig instance

Source: Internet
Author: User

In the previous Spring 4 MVC HelloWorld-instance, there are two XML files Spring-mvc.xml and Web. Now with the Java configuration, this two XML file will be deleted.

1. pom.xml file
<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>com.demo.springmvc</groupId> <artifactId> Spring4mvchelloworlddemo</artifactid> <version>0.0.1-SNAPSHOT</version> <packaging>war </packaging> <properties> &LT;SPRINGFRAMEWORK.VERSION&GT;4.0.6.RELEASE&LT;/SPRINGFRAMEWORK.VERSION&G    T </properties> <dependencies> <dependency> <groupid>org.springframework</g Roupid> <artifactId>spring-webmvc</artifactId> <version>${springframework.versi On}</version> </dependency> <!--Below declared dependencies is included for the servers WH      O may complain about Servlet/jstl missing dependency--  <dependency> <groupId>javax.servlet</groupId> <artifactid>javax.servlet-ap            i</artifactid> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> &LT;ARTIFACTID&GT;JAVAX.SERVLET.JSP-API&LT;/ARTIFAC tid> <version>2.3.1</version> </dependency> <dependency> &L T;groupid>javax.servlet</groupid> <artifactId>jstl</artifactId> <version>            1.2</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupid>org.apache.maven.plugins</gr Oupid> <artifactId>maven-compiler-plugin</artifactId> <version>     3.2</version>               <configuration> <source>1.8</source> <ta  Rget>1.8</target> </configuration> </plugin> <!-- The goal is to delete Web. XML (no matter what, to be resolved.)                    )-<plugin> <groupId>org.apache.maven.plugins</groupId>                    <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warsourcedirectory>src/main/webapp</warsourcedirect Ory> <warName>Spring4MVCHelloWorldDemo</warName> <failonmi            Ssingwebxml>false</failonmissingwebxml> </configuration> </plugin> </plugins> </pluginManagement> <finalname>spring4mvchelloworlddemo</finalnam E> </build></project> 

  

Step 2: Add a 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";    } }

  

Step 4: Add a View
<%@ 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" >

  

Step 5: Add the Configuration Class
Package 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.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  @EnableWebMvc
Equivalent to <mvc:annotation-driven/>xml, which is designed to support classes of @controller annotations that @RequestMapping map incoming requests to specific methods.
@ComponentScan (basepackages = "Com.springmvc")
Equivalent to <context:component-scan base-package= "Com.springmvc"/>

Step 6: Add the Initialization class
Package 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{@Overridepublic 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 above content is similar to the content of Web. XML in the previous tutorial because we use the front-end controller DispatherServler , assigning a map (Url-pattern in XML) instead of providing a path for the spring configuration file (spring-mvc.xml), where we are registering the configuration class. in General, we are doing the same thing, but the method is different.

Update: Note that you can now write the above class more succinctly [ This is the preferred way ] by extending AbstractAnnotationConfigDispatcherServletInitializer base class, as follows:

Package Configuration;import Org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer;public class Initializer extends abstractannotationconfigdispatcherservletinitializer{@Overrideprotected class<?>[] Getrootconfigclasses () {return new class[]{helloworldconfiguration.class};} @Overrideprotected class<?>[] Getservletconfigclasses () {return null;} @Overrideprotected string[] Getservletmappings () {return new string[]{"/"};}}

Deployment runs.

Spring 4 MVC HelloWorld-Annotated/javaconfig instance

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.