1.SpringMVC开发环境搭建

来源:互联网 发布:奥林巴斯显微镜 知乎 编辑:程序博客网 时间:2024/06/09 13:40

本文将带领你在Eclipse环境下(web服务器为tomcat)搭建springmvc 开发环境,并运行helloworld程序

1.下载spring mvc开发包和apach的commonlogging.jar。
下载地址:
SpringMVC开发包
http://repo.spring.io/libs-release-local/org/springframework/spring/3.2.9.RELEASE/spring-framework-3.2.9.RELEASE-dist.zip
apach-commonlogging http://apache.fayea.com//commons/logging/binaries/commons-logging-1.2-bin.zip

2.下载完毕后解压下载的文件, 导入到项目工程的lib目录下。如图
导入jar包

3.在web.xml中配置springmvc DispatcherServlet,并指定其随WEB容器一起启动

<servlet>    <servlet-name>hello</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>hello</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>

在WEB-INF目录下新建一个和上面配置的servlet-name字段一致的并加上-servlet结尾的xml文件 (hello-servlet.xml)并添加如下配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:attr="http://www.springframework.org/schema/p"    xmlns:mvc="http://www.springframework.org/schema/mvc"    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.xsd      http://www.springframework.org/schema/mvc      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">    <!-- 配置自动扫描的包 -->    <context:component-scan base-package="com.hello" />    <!-- 配置视图解析器 -->    <bean        class="org.springframework.web.servlet.view.InternalResourceViewResolver"        attr:prefix="/WEB-INF/view/"         attr:suffix=".jsp" /></beans>

4.新建控制器类,所在包名和配置的hello-servlet.xml自动扫描的包名必须一致,如图
新建控制器

5.启动项目在浏览器输入http://localhost:8080/HelloSpring/hello (HelloSpring为项目名称),界面显示helloworld ok!

注:关于视图解析器:
attr:prefix=”/WEB-INF/view/”
前缀 :则我们在控制器中返回的hello字符前+”/WEB-INF/view/hello”
attr:suffix=”.jsp”
后缀:加上前缀完整路径为:/WEB-INF/view/hello.jsp。所以需要保证你的项目的WEB-INF目录下有view文件夹,文件夹中有hello.jsp

0 0
原创粉丝点击