---
title: "从Struts到Spring MVC的应用"
author: "yeminping"
date: "2009-09-27T11:42:57Z"
tags: ["Bean", "Hibernate", "MVC", "Spring", "Struts"]
slug: "struts-spring-mvc"
draft: false
lastmod: "2009-09-28T09:53:55Z"
id: 478464
url: "https://yeminping.iteye.com/blog/478464"
---

**从 Struts 转到 Spring MVC 的应用**

 

之前的项目比较简单，多是用 JSP 、 Servlet + JDBC 直接搞定，去年开始在项目中尝试用 Struts(Spring MVC)+Spring+Hibernate, 严格按照分层概念驱动项目开发，因项目需求一直不断变化，功能不断扩充、增强，技术构建也几经改变到目前有个稳定的应用，体会了很多感受，这次先对 MVC 层进行一些个人总结。

 

MVC 作为 WEB 项目开发的核心环节，正如三个单词的分解那样， C( 控制器 ) 将 V( 视图、用户客户端 ) 与 M （模块，业务）分开构成了 MVC ，这边不去是否应用 MVC ，或 MVC 的更多原理进行讨论，而是将实践中如何从应用 SSH, 到 Spring MVC + Spring+Hibernate 进行演化

 

先看 Struts 如何与 Spring 结合处理一次简单的请求响应代码，前台可以设为用 AJAX 调用：

 

    1. 在 struts-config.xml 文件中加入

 

 

```
<!--用于声明GetPersonList.do请求委托Spring处理-->

<action path="/GetPersonList" scope="request"

         type="org.springframework.web.struts.DelegatingActionProxy">

</action>
```

 

    2.在 applicationContext.xml 文件中加入

 

```
<!— 指定GetPersonList.do处理的代码，和注入实现业务的代码 -->

    <bean name="/GetPersonList" class="cn.base.GetPersonListAction">

       <property name="getPersonList" ref=" getPersonListServices"></property>

    </bean>
```

 

 

     3.cn.base.GetPersonListAction 实现请求响应代码

 

 

可以看出一次请求需求如此多的步骤，在加上一个项目下来有很多这样的请求响应，将给配置文件管理带来很大的麻烦。

 

经过对 Spring 的深入应用， Spring 本身提供的 URL 请求控制，对其天然支持可以让我们不需要 applicationContext.xml 再次声明一次 URL 请求 Bean ，即减少了 Struts 的声明 URL ，达到减少些繁琐的配置。但只是少了一些而已，同样也会面临着配置文件的管理问题。

 

```
<bean id="beanNameUrlHandlerMapping" class="org.springframework.web.servlet.handler.BeanNameHandlerMapping" />
<bean name="/a.html" class="example.chapter7.ControllerA" />
<bean name="/a.html" class="example.chapter7.ControllerB" />
```

 

 

 

Spring 注解将给我们的工作带来些轻松，利用反射机制原理出现的注解就是为了解决配置大量的配置问题。请看下处理一次简单的请求响应代码

 

 

```
@Controller  --声明控制器

@RequestMapping("/person.do") –声明URL

public class PersonControl extends BaseController {

   

   

    @Autowired –业务接口注入

    private personServices personServices;

      

    /**

     * 获得人员列表

     * @param request

     * @param response

     * @throws Exception

     */

    @RequestMapping(params = "method=geList")  --即处理/person.do? method=geList方法

    public void getnodeList(HttpServletRequest request,

           HttpServletResponse response) throws Exception {    

       //处理请求

 

       //处理响应

    }

}
```

 

 

可以看出，在代码上加入注解可以省去我们上面说的多个配置文件的工作，达到简便的 MVC 处理请求响应。

 

在配上简单的配置文件声明，即可轻松处理项目的全部请求控制工作。