下面看一下各个文件的源码。
<?xml version="1.0" encoding="UTF-8"?> <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"> <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>
<?xml version="1.0" encoding="UTF-8"?> <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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="letian.spring.controller" /> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="resourceLoaderPath"> <value>/WEB-INF/template/</value> </property> <property name="configLocation" value="/WEB-INF/template/velocity.properties"/> <!--在配置中防止中文乱码--> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="suffix"> <value>.vm</value> </property> <property name="contentType"> <value>text/html;charset=UTF-8</value> <!--防止中文乱码--> </property> </bean> </beans>
input.encoding=UTF-8 output.encoding=UTF-8
<html> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <head> <title>My first example using Spring 3 MVC</title> </head> <body> <h2>你好</h2> </body> </html>
<html> <head> <title>Velocity</title> </head> <body> <h1>${message}</h1> </body> </html>
package letian.spring.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; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { @RequestMapping(value = "/",method = RequestMethod.GET) public String printWelcome(ModelMap model) { model.addAttribute("message", "Hi, I am Velocity"); return "hello"; } @RequestMapping(value = "/hi",method = RequestMethod.GET) public ModelAndView printHi(ModelMap model) { return new ModelAndView("index"); } }