当前位置: 代码迷 >> VC/MFC >> 二、Spring4 MVC HelloWorld 注解和JavaConfig实例
  详细解决方案

二、Spring4 MVC HelloWorld 注解和JavaConfig实例

热度:463   发布时间:2016-05-02 03:12:14.0
2、Spring4 MVC HelloWorld 注解和JavaConfig实例

使用Spring和Servlet依赖更新pom.xml
<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>
首先要注意这里maven-war-plugin 插件的声明。正如我们将完全删除web.xml ,我们需要配置这个插件,以避免Maven构建war包失败。第二个变化是加入了JSP/Servlet/Jstl 的依赖关系,这些我们可能需要,因为我们将要使用 servlet API和JSTL视图在我们的代码中。在一般情况下,容器已经包含这些库,从而在pom.xml中为他们提供了,我们可以设置作用范围。

添加控制器
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";
}

}
[email protected] bean 以及 @RequestMapping注解声明了这个类是默认处理程序键入“/”的所有请求。第一种方法没有声明因此任何映射,它将继承映射的映射声明是在类级别上,默认处理GET请求。方法二(由于额外的映射声明使用value属性)形式 /hello 将再次请求。属性方法说哪种类型的HTTP请求这种方法可以服务。
方法说哪种类型的HTTP请求这种方法可以服务。 ModelMap是一个Map实现,在这里作为替代[request.getAttribute()/request.setAttribute()] 设定值作为请求属性。请注意,我们从这个方法返回“welcome”字符串。此字符串将后缀和前缀后缀,在视图解析器定义的前缀(见上面的 spring-servlet.xml),形成真正的视图文件名。
添加视图
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HelloWorld page</title>
</head>
<body>
Greeting : ${greeting}
</body>
</html>
添加配置类
在src/main/java下添加下面提到的类指定的包,如下图所示。这种构造类可以被看作是一个替代 spring-servlet.xml,因为它包含了所有必需的组件的扫描和视图解析器的信息。
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 {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");

return viewResolver;
}

}
@[email protected] 生产 bean管理是由Spring容器的一个或多个bean方法。 以上配置类对应等同于以下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 />

<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>
@EnableWebMvc 等同于 mvc:annotation-driven 在XML中. [email protected]?[email protected] 类。
@ComponentScan 等同于 context:component-scan base-package="..." 提供 spring 在哪里寻找 管理 beans/classes.

添加初始化类
添加一个初始化类实现 WebApplicationInitializer 在src/main/java 中使用如下图所示指定包(在这种情况下,作为替代在 web.xml 中定义的任何 Spring 配置)。在Servlet 3.0的容器启动时,这个类将被加载并初始化,并在启动由servlet容器调用方法
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("/");
}

}
内容上面类似 web.xml 在之前的教程中的内容,因为我们使用的是前端控制器 DispatcherServlet,分配映射(URL模式的XML)和而不是提供给 Spring 配置文件(spring-servlet.xml)的路径,在这里,我们正在注册的配置类。总体而言,我们都在做同样的事情,只是方式有所不同
更新:请注意,现在你可以更简洁写上面的类[和它的最佳方法] 来扩展 AbstractAnnotationConfigDispatcherServletInitializer 类,如下所示
package com.yiibai.springmvc.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { HelloWorldConfiguration.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

}
构建和部署应用程序

有一点要记住,像WebApplicationInitializer,Spring 是基于Java 的配置API依赖于 Servlet3.0容器。确保你没有使用Servlet声明任何小于3.0。对于我们的情况,我们将从应用程序中删除 web.xml 文件。
现在构建war (无论是作为Eclipse中提到的最后一个教程)或通过Maven的命令行(mvn clean install)。部署war 到Servlet3.0容器。由于我在这里使用Tomcat,我就干脆把这个 war 文件放到 Tomcat 的 webapps 文件夹,然后在 tomcat 的bin 目录里面点击 start.bat 运行
或者 右键工程 =>Run As => Maven install 完成后,再次 右键工程 =>Run As => Maven build,弹出选择:




  相关解决方案