您的位置:首页 > 编程语言 > Java开发

Spring+SpringMVC项目搭建

2016-02-20 13:23 288 查看
前言:本文基于上一篇内容-Spring项目搭建

修改pom.xml文件,添加SpringMVC的jar包依赖

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>


修改web.xml文件,添加SpringMVC拦截器配置

<!-- SpringMVC拦截器配置,配置文件名称默认为/WEB-INF/'<serlet-name>值'-servlet.xml -->
<servlet>
<servlet-name>applicationContext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<!-- SpringMVC拦截内容 -->
<servlet-mapping>
<servlet-name>applicationContext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>


在WEB-INF下创建SpringMVC的配置文件applicationContext-servlet.xml,静态资源文件css、js、images文件夹放在webapp目录下

<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- 注解自动扫描包设置 -->
<context:component-scan base-package="com.MyTest.controller" />

<!-- 注解驱动配置 -->
<mvc:annotation-driven />

<!-- 视图控制器,主页配置 -->
<mvc:view-controller path="/" view-name="index"/>

<!-- 资源目录配置 -->
<mvc:resources mapping="/css/*.css" location="/css/"/>
<mvc:resources mapping="/js/*.js" location="/js/"/>
<mvc:resources mapping="/images/**" location="/images/"/>

<!-- 视图解析器配置 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

</beans>


配置已经都做完了,下面进行下简单的测试。在com.MyTest.controller包下创建MyTestController.java文件

package com.MyTest.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyTestController {

@RequestMapping("/myTest")
public String myTest(){
return "MyTest";
}
}


根据applicationContext-servlet.xml的配置可知,视图文件的路径是/WEB-INF/views,那么在该路径下创建MyTest.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
This is MyTest page!
</body>
</html>


最后,将项目打包,部署到服务器中,进行测试。服务器启动后,浏览器访问地址http://localhost:8080/SpringDemo/myTest,如果能够看到“This is MyTest page!”就说明搭建成功了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Spring SpringMVC