1. 创建Dynamic web project
2. 修改WEB-INF/web.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3. 创建/WEB-INF/applicationContext.xml,添加如下内容:
<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="com.vito.action" /> <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<!-- 这个配置是配置JSP页面的位置,按照你自己的配置来配 -->
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> </beans>
4. 创建java文件,注意package名字
package com.vito.action; 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("/welcome")
public class HelloWorldController {
@RequestMapping(value="/hello",method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
}
5. 【关键】创建WEB-INF/lib,将如下jar包导入,注意不要填加多余的包。由于之前将所有的sping jar包导入,导致出错,找原因花了一天时间。
6. 将上面的jar加入build path
7. 试试http://localhost:8080/DemoSpringMVC/welcome/hello 吧!