整合的之前需要从官网上下载spring完整的jar包,我下载的是spring-framework-3.2.2.RELEASE。整合步骤如下:
1、在eclipse中新建一个web项目,将下载的spring的jar包拷入lib目录下,但是spring启动的时候依赖一个commons-logging-1.1.jar的jar包,你需要额外的下载。
2、编写web.xml,配置spring的分发器和spring配置文件的位置。具体内容如下:
<servlet>
<servlet-name>spring_springMVC_IntegrationDemo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring_springMVC_IntegrationDemo</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3、在src下新建config包名,然后新建spring.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:p="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">
<!-- 开启注解 -->
<mvc:annotation-driven />
<!-- 注解扫描范围 -->
<context:component-scan base-package="com.evan"></context:component-scan>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
4、新建类名UserAction,具体内容如下:
package com.evan.action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.evan.service.IUserService;
@Controller
@RequestMapping("/user")
public class UserAction {
@Autowired
IUserService userService;
@RequestMapping("/add")
public String addUser() {
System.out.println(userService.addUser());
return "addUserView";
}
}
5、新建IUserService接口,接口内容如下:
package com.evan.service;
public interface IUserService {
public int addUser();
}
6、新建UserServiceImpl类名,具体内容如下:
package com.evan.service.impl;
import org.springframework.stereotype.Service;
import com.evan.service.IUserService;
@Service
public class UserServiceImpl implements IUserService {
@Override
public int addUser() {
System.out.println("添加用户成功");
return 1;
}
}
7、在webContent目录下新建addUserView.jsp,内容是一句提示:
spring和springMVC整合成功!!
8、将项目添加到tomcat运行目录,访问http://localhost:8080/Spring_SpringMVC_IntegrationDemo/user/add 能正常访问,表示整合成功。
9、整个项目源码目录结构截图如下:
10、项目源码下载地址(免积分):
http://download.csdn.net/detail/zl544434558/8566553
时间: 2024-11-14 09:22:30