1. 程式人生 > >Spring mvc基於註解方式實現簡單HelloWorld

Spring mvc基於註解方式實現簡單HelloWorld

實現spring MVC有兩種不同的方式:基於XML配置檔案和基於註解。

上篇部落格介紹了基於XML配置檔案的方式,這裡我們使用基於註解的方式來實現。

下面只重點介紹與XML配置檔案方式不同的兩個地方:Spring配置檔案(springmvc-servlet.xml)和Controller類。

其中,springmvc-servlet,xml檔案內容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<!-- 載入springmvc註解驅動 -->
	<mvc:annotation-driven/>
	
	<!-- 掃描器 (預設掃描的包com.xjc)-->
	<context:component-scan base-package="com.xjc"/>
	
	<!-- 配置檢視解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 字首 -->
		<property name="prefix" value="/"></property>
		<!-- 字尾 -->
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

控制器HelloController類(注意:這裡不再繼承AbstractController類,而是通過添加註解@Controller的方式來說明它屬於控制器):

package com.xjc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController{
	
	@RequestMapping(value="/hello.do")
	public String toIndex(String hello,Model model) {
		
		model.addAttribute("helloworld", "hello "+hello);
		return "index";
	}

}