Spring 4 MVC Hello World Tutorial-totally XML based (with Project source) "Awesome"

Source: Internet
Author: User
Tags http request xmlns


Original address: http://websystique.com/springmvc/spring-4-mvc-helloworld-tutorial-full-example/



"Click Category: Spring 4 mvc for viewing"






"Translation by clearly like the month QQ 605283073"



Previous post: Spring MVC 4 Series tutorials [General]



Next article: Spring 4 MVC HelloWorld Pure Annotated Way (with source)






#项目下载地址: http://websystique.com/?smd_process_download=1&download_id=1714#.



Special Note: This series of tutorials some children's shoes download down run often 404 or change to XML after the lack of org.springframework.web.context.ContextLoaderServlet, etc. see:/http blog.csdn.net/w605283073/article/details/52126347






This section describes spring MVC 4 contacts, using a typical Hello world but without ignoring any steps.



The next section describes the Hello World example, which is based entirely on Java annotations.



----------------------------



This example uses the following techniques:



Spring 4.0.6.RELEASE Maven 3 JDK 1.6 Eclipse JUNO Service RELEASE 2 m2eclipse plugin (Optional) If you're already familiar with how to create Mave in eclipse N Project, you can ignore the first step.






1th Step: Create a Maven WebApp project in Eclipse
File-> New, Maven Project,












If you want to create a project in another folder do not select "Use default Workspace location"



Click Next









Select Maven Web App Archetyp, then click Next






Fill in the Group ID, Artifact ID, and version. Then click Finish






The following structure will be obtained:












Note: If you do not see the Src/main/java and Src/test/java folders in the project structure, click Project>properties>java buildpath>libraries, Select or switch Java version, click OK, then you can see the structure of the project above.



Note: you no longer need to use MVN eclise:eclipse in the latest releases of Eclipse, this method is done for us by default in the M2E Eclipse plugin.



2nd Step: Add Spring Dependency in the Maven Pom.xml file because this is a MAVEN project and all dependencies (jars) are configured in Pom.xml, MAVEN will automatically help us download all the corresponding dependencies (jar packages).
Here is the contents of the Pom.xml file:


<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.websystique.springmvc</groupId>
    <artifactId>Spring4MVCHelloWorldDemo</artifactId>
    <packaging>war</packaging>
    <version>1.0.0</version>
    <name>Spring4MVCHelloWorldDemo Maven Webapp</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>
 
        <!-- Below declared dependencies are included for the servers who may complain about servlet/jstl missing 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-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <finalName>Spring4MVCHelloWorldDemo</finalName>
    </build>
</project>


The Maven Maven-compiler-plugin plugin is also added and indicates the Java version we are using. Note that this also forces eclipse to reference the version we configured when compiling this project. If not configured, eclipse will automatically use JDK version 1.5. So it's better to add it up.
3rd Step: Add controller and view (view)
Create a new package under Src/main/java [Src/main/java->new->package]. and add a new controller, as shown below. It just adds a string to the model and returns to the view. Com.websystique.springmvc.controller.HelloWorldController

Package Com.websystique.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";
    }
 
}


Let's take a closer look at:








@Controller annotation marks this class as spring bean which could handle different HTTP requests based on mapping specified On class or individual controller methods.



@RequestMapping annotations are used to map a Web request to a specified processor class or processing method. In this case, we also used it at the class level, which means that this class is the default processor for all HTTP "/" requests, @RequestMapping there are many properties [Value,method,params,..] Can be used to map in more detail.



The first method does not make any URL mapping declarations, so it inherits the mapping declaration above the class, and the default processing method for the HTTP GET request.



The second method, which adds a mapping declaration with value, is used to process the request with/helloagain. The method property is the type of HTTP request that is used to indicate the processing of this technique.



If no method is specified in the @requestmapping, it will process the request for all types of map URLs (GET post, etc.).



Modelmap is a map implementation class whose purpose is to replace the previous Request.getattribute/request.setattribute method,



It provides a way to set or get properties from the request or session.



Pay attention to the return values of these methods. These values will be the prefix or suffix of the view resolver (see spring-servlet.xml below) to produce a true name for the views file.



Create the Views folder in Web-inf and create JSP pages in it (web-inf/views/welcome.jsp).



In our example, simply access the model values sent by the controller.


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
< title > demo page < / Title >
</head>
<body>
Greeting : ${greeting}
</body>
</html>
</pre><pre>


Step 4: create the spring configuration file. Configure it in XML mode here. The next chapter will cover annotation mode. Create a configuration file called spring-servlet.xml under the WEB-INF folder. Note: you can use this name at will, but it should be consistent with the declaration in web.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.websystique.springmvc" />
 
    <mvc:annotation-driven />
     
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
 
</beans>







Spring configuration details:
< MVC: annotation driven / > means that we can not declare the bean in XML,
Or implement an excuse or inherit a bean class or other classes to define the bean dependency.
For example, just add a @ controller annotation to the class (that's what we used for the above controller class), so we don't need to add it to XML
Configure the bean, and spring will know that the class with this annotation contains the handler that responds to the HTTP request.
< context: component scan base package = "com. Websysteque. Springmvc" / > means
Spring automatically scans the component base package [com. Websysteque. Springmvc] under this package,
See if they have [@ controller, @ service, @ repository, @ component, etc.] annotations.
If there are these annotations, spring will automatically register them in the bean factory, which is the same as configuring beans in XML.
We declare a view resolver to help the controller agent respond to the correct view
Step 4: configure the (web. XML) file


<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.websystique.springmvc" />
 
    <mvc:annotation-driven />
     
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
 
</beans>


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.