1. 建立Dynamic web projectjava
2. 修改WEB-INF/web.xml,內容以下:web
<?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,添加以下內容:spring
<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名字app
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包導入,致使出錯,找緣由花了一天時間。jsp
6. 將上面的jar加入build pathui
7. 試試http://localhost:8080/DemoSpringMVC/welcome/hello 吧!url