搭建使用springmvc的web项目

来源:互联网 发布:电路计算软件 编辑:程序博客网 时间:2024/06/05 17:53

可以使用新建maven项目和java dynamic web项目。本文是基于java dynamic web项目的。

首先我们需要知道spring mvc只是spring framework 的一个模块,要搭建spring mvc项目,我们得用到spring framework,使用spring framewor很简单,只需要导入spring framework的lib目录下的jar包还有其依赖的日志包到工程就好了。

我使用的是版本是spring framework4.3.0RC1,文档链接:http://docs.spring.io/spring/docs/4.3.0.RC1/spring-framework-reference/htmlsingle/

通过文档我们找到下载spring framework的 地址http://repo.spring.io/release/org/springframework/spring/

将spring framework下载下来,再去Apache 下载 Commons Logging的jar包导入工程就能使用spring framework了。

接下来我们只需要按照spring mvc模块的使用流程走就好了。具体用法可以参考spring文档的配置http://docs.spring.io/spring/docs/4.3.0.RC1/spring-framework-reference/htmlsingle/#mvc。

我们需要配置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了。




1 0