搭建使用springmvc的web專案
阿新 • • 發佈:2019-02-17
可以使用新建maven專案和java dynamic web專案。本文是基於java dynamic web專案的。
首先我們需要知道spring mvc只是spring framework 的一個模組,要搭建spring mvc專案,我們得用到spring framework,使用spring framewor很簡單,只需要匯入spring framework的lib目錄下的jar包還有其依賴的日誌包到工程就好了。
將spring framework下載下來,再去Apache 下載 Commons Logging的jar包匯入工程就能使用spring framework了。
我們需要配置springmvc的DispacherServlet,
在web.xml裡面進行如下配置:
<web-app> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/root-context.xml</param-value> </context-param> <servlet> <servlet-name>dispatcher</servlet-name>具體為什麼這樣配置請看文件,在此不多說了。<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
然後在src目錄下新建root-context.xml,root-context.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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="org.expc.controller"/> <!-- ... --> </beans>然後新建包org.expc.controller ,在包裡新建一個TestController,程式碼如下:
package org.expc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/")
public class TestController {
@RequestMapping("test")
public @ResponseBody String test()
{
return "Test!";
}
}
然後在server上執行工程就OK了。