Spring 4 MVC 入門

Spring 4 MVC Hello World Tutorial – Full Example Posted on February 9, 2014 in Hello World, Spring Framework Twitter 0 Tweet Facebook 32 Google+ 40 LinkedIn 4 Filament.io Made with Flare More Info 76 Flares Table of Contentshtml

Technologies Used
Project Setup using Maven
Spring Bean Configuration
Web App Configuration
Developing the Controller
Developing the View
Running using browser
Using Java Config instead of XML

In this tutorial you will learn how to develop a Spring 4 MVC Hello world example. Hope this tutorial will give you a quick start in Spring MVC development using the latest Spring 4 Release.java

Technologies used:web

Spring 4.0.1.RELEASE
JDK 1.6
Maven 3
Eclipse Java EE IDE ( Eclipse JUNO)

Updates (10 -Feb -2014): Updated the tutorial with JavaConfig. Now explains how to use WebApplicationInitializer and @Configuration 1: Maven Project Setup In Eclipsespring

Let us start with the creation of a Maven web project in Eclipse. A maven web project archetype will create all the necessary folder structures required for a web project. We assume that you have installed the maven plugins for Eclipse. If you haven’t configured it, refer our earlier Spring tutorial that has section explaining how to setup maven in eclipse.apache

File -> New -> Other -> Maven -> Maven Projectapi

Maven Project Eclipsemvc

Click Next and Click Next again ( If you wish to change default Workspace location , you may do so). In the next screen you should pick the maven web app archetype. Refer the screen belowapp

Maven Web App Archetypeeclipse

Click Next and provide the following valuesjsp

GroupId :com.javahash.web ( you can change this according to your package structure)
Artifact Id: Spring4MVCHelloWorld
Version: 1.0-SNAPSHOT

Click Finish to complete the Project Setup.

Project Structure-SpringMVC

This completes the project setup. Make sure the project is loaded in eclipse. 2: Spring Configuration

Activities in this section can be broadly defined as

Adding Spring libraries as dependencies in pom.xml
Defining an XML file that holds the configuration for spring beans
Configuring web.xml

Spring libraries are added as dependencies in maven (pom.xml).

Dependencies – pom.xml
<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.javahash.web</groupId>
 <artifactId>Spring4MVCHelloWorld</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>Spring4MVCHelloWorld Maven Webapp</name>
 <url>http://maven.apache.org</url>

 <properties>
    <spring.version>4.0.1.RELEASE</spring.version>
 </properties>

 <dependencies>

    <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
     <scope>test</scope>
    </dependency>

   <!-- Spring dependencies -->
   <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
  </dependency>

 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
 </dependency>

 <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
 </dependency>
</dependencies>

 <build>
 <finalName>Spring4MVCHelloWorld</finalName>
 </build>
</project>
<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.javahash.web</groupId>
 <artifactId>Spring4MVCHelloWorld</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>Spring4MVCHelloWorld Maven Webapp</name>
 <url>http://maven.apache.org</url>
 
 <properties>
    <spring.version>4.0.1.RELEASE</spring.version>
 </properties>
 
 <dependencies>
 
    <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
     <scope>test</scope>
    </dependency>
 
   <!-- Spring dependencies -->
   <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
  </dependency>
 
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
 </dependency>
 
 <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
 </dependency>
</dependencies>
 
 <build>
 <finalName>Spring4MVCHelloWorld</finalName>
 </build>
</project>

2.1 Configuring Spring Beans (dispatcher-servlet.xml)

Create an XML file and name it dispatcher-servlet.xml. This configuration file can be given any name. We are using the name dispatcher-servlet.xml for this project. Place this file inside the WEB-INF folder. This xml file holds the configuration info for the view resolver that spring uses to map view names to a concrete view files. <context:component-scan base-package="com.javahash.spring.controller" /> 1

<context:component-scan base-package="com.javahash.spring.controller" />

Above piece of code instructs spring to scan the package (com.javahash.spring.controller) and its children to detect and auto configure components. For instance, we can annotate a class with @Controller annotation and spring will automatically configure it as a controller class. Due to this auto scanning feature, there is no need to configure controller classes in xml files.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 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/context
 http://www.springframework.org/schema/context/spring-context-4.0.xsd">

 <context:component-scan base-package="com.javahash.spring.controller" />

 <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>

3: Configuring web.xml

The org.springframework.web.servlet.DispatcherServlet acts as the front controller for the application. All requests are intercepted by the spring servlet.

<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Archetype Created Web Application</display-name>

 <servlet>
   <servlet-name>dispatcher</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
   <servlet-name>dispatcher</servlet-name>
   <url-pattern>/</url-pattern>
 </servlet-mapping>

 <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
 </context-param>

 <listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
</web-app>

Note: Location of web.xml is inside the WEB-INF Folder

The default rule is spring looks for a file honoring the contract , servletname-servlet.xml to load the spring configuration beans. Because of this, spring will look for the file ( dispatcher-servlet.xml). If we had used a different name for the servlet, say frontcontroller, then the framework will look for a file with name frontcontroller-servlet.xml to load MVC configurations. We can override this behavior by explicitly specifying the mvc configuration file using the parameter contextConfigLocation. We have used that in the above web.xml 4: Developing the Controller

Starting with Spring 3, there is excellent support for annotations. We can use annotations to mark our class as a controller. The HelloWorldController is a very simple controller that just echoes a message. It takes a parameter and just echoes it.

package com.javahash.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

 @RequestMapping("/hello")
 public String hello(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
  
   model.addAttribute("name", name);
   //returns the view name
   return "helloworld";

 }

}

Please note the use of @Controller and @RequestMapping . The URL takes a parameter with name 「name」. 5: Developing the View

Create a file named helloword.jsp inside WEB-INF/views folder. In the dispatcher-servlet.xml, defined in section 2.1, we have specified that the jsp files will be put inside the WEB-INF/view folder.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//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=ISO-8859-1">
<title>Spring4 MVC -HelloWorld</title>
</head>
<body>
<h1>Hello : ${name}</h1>
</body>
</html>

At run-time, spring will choose the appropriate .jsp file based on the view-name returned by the controller method. 6: Build and Package

Right click the project , RunAs -> maven install

This will compile, package and install the executable as a WAR file. You can also perform maven package instead of maven install. Spring4MVCHelloWorld.war will be generated inside the target folder.

Deploy this WAR file to Tomcat web server or any web server you are using. http://localhost:8080/Spring4MVCHelloWorld/hello/?name=JavaHash 1

http://localhost:8080/Spring4MVCHelloWorld/hello/?name=JavaHash

Results

How to Avoid XML Files and use JavaConfig

Maintaining configuration using XML has its advantages and disadvantages. If you are not a fan of XML configuration and wish to enjoy the benefits of annotations based configuration, you can do so easily in Spring. It is your choice to go the XML path or the JavaConfig path. JavaConfig is a cool approach and helps in rapid application development and provides easy maintenance. When the number of artifacts in the project increases, JavaConfig is very handy. Also it is the developer friendly means of handling configuration. Let us see how we can replace the dispatcher-servlet.xml and the Spring Configuration defined in the web.xml to Java classes using JavaConfig.

Replacing dispatcher-servlet.xml with Java File

package com.javahash.spring.config;

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.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration //Marks this class as configuration
//Specifies which package to scan
@ComponentScan("com.javahash.spring")
//Enables Spring's annotations
@EnableWebMvc
public class Config {

 @Bean
 public UrlBasedViewResolver setupViewResolver() {
   UrlBasedViewResolver resolver = new UrlBasedViewResolver();
   resolver.setPrefix("/WEB-INF/views/");
   resolver.setSuffix(".jsp");
   resolver.setViewClass(JstlView.class);
   return resolver;
 }
}

Moving Spring Configuration from web.xml to WebApplicationInitializer

package com.javahash.spring.config;

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 {

public void onStartup(ServletContext servletContext) throws ServletException {

 AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
 ctx.register(Config.class);

 ctx.setServletContext(servletContext);

 Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
 servlet.addMapping("/");
 servlet.setLoadOnStartup(1);

 }

}

Download Source Code

Download – Project Source Code Good Video Tutorial – Spring MVC

相關文章
相關標籤/搜索