Spring MVC 基于注解

在先前的 Spring MVC入门 (基于XML配置)文章中, 我们已经使用XML配置开发了一个Spring MVC 入门 Web应用程序。但是,XML不是配置Spring应用程序的唯一途径。我们还可以使用Java配置来配置应用程序。
回顾上一篇文章,发现我有两个地方使用XML配置:
1. spring-servlet.xml 定义视图解析识别真正的视图,位置搜索,通过组件扫描Bean。
2. web.xml 定义前端控制器配置和URL模式将被寻找匹配。

在这篇文章中,我们使用Java配置来一步一步的简单学习Spring MVC 的注解,项目设置,代码,部署和运行。

1. 常见项目,结构如下:

2. 更新pom.xml,添加项目所需依赖

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

<dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.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>
</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>springmvc</warName>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</pluginManagement>
	<finalName>springmvc2</finalName>
</build>

3. 创建控制器

/**
 *  @Controller 注解声明这个类的Spring bean
 *  @RequestMapping 注解声明了这个类是默认处理程序键入“/”的所有请求。
 *  ModelMap是一个Map实现,在这里作为替代[request.getAttribute()/request.setAttribute()] 设定值作为请求属性。
 *  printHello方法返回“hello”字符串。此字符串和视图解析器定义的后缀和前缀(见之前文章的 spring-servlet.xml),形成真正的视图文件名。 
 *
 */
@Controller
@RequestMapping("/")
public class HelloController {

	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "index";
	}
	
	@RequestMapping(value="/hello", method = RequestMethod.GET)
	public String printHello(ModelMap model) {
		model.addAttribute("message", "Hello Spring MVC Framework from Angelia!");
		return "hello";
	}
}

4. 添加视图

<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
	<h2>${message}</h2>
</body>
<

5. 添加配置类

/**
 * 此种构造类可以被看作是一个替代 spring-servlet.xml的类,因为它包含了所有必需的组件的扫描和视图解析器的信息。
 * @Configuration 指明该类包含注解为@Bean 生产 bean管理是由Spring容器的一个或多个bean方法。
 * @EnableWebMvc 等同于XML中 mvc:annotation-driven. 它能够为使用@RequestMapping向特定的方法传入的请求映射@Controller-annotated类。
 * @ComponentScan 等同于 context:component-scan base-package="..." 提供 spring在哪里寻找 管理 beans/classes. 
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.angelia.springmvc")
public class HelloConfiguration {
	
	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/jsp/");
		viewResolver.setSuffix(".jsp");

		return viewResolver;
	}
}

6. 创建初始化类

/**
 * 添加一个实现 WebApplicationInitializer的初始化类,等同于 web.xml中定义的任何 Spring配置。
 * 在Servlet3.0的容器启动时,这个类将被加载并初始化,并在启动由servlet容器调用方法。 
 *
 */
public class HelloInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext container) throws ServletException {
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(HelloConfiguration.class);
		ctx.setServletContext(container);

		ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

		servlet.setLoadOnStartup(1);
		servlet.addMapping("/");
	}
}
/**
 * 添加一个实现 WebApplicationInitializer的初始化类,等同于 web.xml中定义的任何 Spring配置。
 * 在Servlet3.0的容器启动时,这个类将被加载并初始化,并在启动由servlet容器调用方法。 
 * 扩展 AbstractAnnotationConfigDispatcherServletInitializer类可以达到相同的效果,不过更简单,推荐使用。
 */
public class HelloInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { HelloConfiguration.class };
	}
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

	/*@Override
	public void onStartup(ServletContext container) throws ServletException {
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(HelloConfiguration.class);
		ctx.setServletContext(container);

		ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

		servlet.setLoadOnStartup(1);
		servlet.addMapping("/");
	}*/
}

7. 构建和部署应用程序

构建war,右键工程 =>Run As => Maven install,完成后,再次 右键工程 =>Run As => Maven build。在弹出框输入: org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run-war。最后访问http://localhost:8080/springmvc2。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AngeliaZheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值