这两天正在试验Struts2与Spring框架的整合,和他们各自的“注解”。今天就总结一下这两个框架怎么用注解进行整合。

一,加入两者的依赖包,除了两者的必要依赖外,还需要导入struts2-spring-plugin.jar来完成两者的整合。

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.2.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-convention-plugin</artifactId>
        <version>2.2.1</version>
    </dependency> 

    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-spring-plugin</artifactId>
        <version>2.2.1</version>
    </dependency>

二,web.xml的配置:在此需要用context-param标签添加Spring的配置文件的位置,并且添加Spring的contextLoaderListener监听,自动装配ApplicationContext(再次出就是bean.xml文件)的配置信息

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
  </context-param>

  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      <init-param>
          <param-name>actionPackages</param-name>
          <param-value>org.toybrick.pro.action</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>*.action</url-pattern>
  </filter-mapping>
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

三,beans.xml Spring配置文件,因为我们要用注解的形式来进行配置,所以这里我们就不要再spring配置文件里声明bean了。在这里需要通过component-scan标签

开启自动Spring的自动扫描功能(多个包之间用逗号隔开)

<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 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-3.0.xsd
                    ">
<context:component-scan base-package="org.toybrick.pro.dao.impl,org.toybrick.pro.action"></context:component-scan>
</beans>

四,struts.xml ,需要要让spring来管理Struts2的对象

<struts>

    <constant name="struts.i18n.encoding" value="UTF-8" />
    <constant name="objectFactory" value="spring"/>

</struts>

五,登陆逻辑处理类,将所有的action都是用注解形式类声明。注意紫色部分我们将这个类声明为了一个springbean并规定了scope为prototype。注意红色部分,我们用注解形式注入了一个属性。@Autowired注解用来注入属性,但是默认的注入形式是按类型注入,@Quality注解用来将注入类型修改为按名称注入。

@Namespace("/main/user")
@ParentPackage(value="struts-default")
@Results({
    @Result(name="success" , location="/main/desktop/desktop.jsp"),
    @Result(name="fail" , location="/main/user/login.jsp")
})
@Service(value="userAction")
@Scope(value="prototype")
public class UserAction extends BaseAction {
    private static final long serialVersionUID = 1L;

    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;

    private User entity;

    @Action("login")
    public String login(){
        String result="";
        try {
            userDao.login(entity);
            result="success";
        } catch (ServiceException e) {
            System.out.println(e.getMessage());
            this.setMessage(e.getMessage());
            result="fail";
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void validate() {
        if(entity == null){
            entity = new User();
        }
        if(entity.getName() == null || "".equals(entity.getName())){
            addFieldError("message", "用户名不可为空!");
        }
        if(entity.getPassw() == null || "".equals(entity.getPassw())){
            addFieldError("message", "密码不可为空!");
        }
    }

    public User getEntity() {
        return entity;
    }

    public void setEntity(User entity) {
        this.entity = entity;
    }

}

六,数据访问对象(DAO)的实现类,我们将它声明为一个spring bean,用来注入到上面的UserAction中。

@Repository(value="userDao")
public class UserDaoImpl implements UserDao {

    public void login(User user) throws ServiceException {
        ServiceException e = new ServiceException();
        if( ! user.getName().equals(user.getPassw())){
            e.setMessage("用户名密码错误!");
            throw e;
        }
    }

七,登陆页面(用了bootstrap框架)

<div class="panel panel-primary" style="margin:100px;">
  <div class="panel-heading">登录</div>
  <div class="panel-body">
    <form action="<%=contextPath%>/main/user/login.action" method="post" class="col-md-4 col-md-offset-4" >
    <div class="alert alert-warning" role="alert"><s:property value="message"/></div>
    <div class="input-group margin">
      <span class="input-group-addon" id="userNameAddon" >账号</span>
      <input type="text" id="userName" name="entity.name" value="" class="form-control" required placeholder="用户名/邮箱/手机号" aria-describedby="userNameAddon"/>
    </div>

    <div class="input-group margin">
      <span class="input-group-addon" id="passwordAddon" >密码</span>
      <input type="password" id="password" name="entity.passw" value="" class="form-control" required placeholder="密码" aria-describedby="passwordAddon"/>
    </div>

    <button type="submit" class="btn btn-block btn-primary margin">登录</button>

  </form>
  </div>
</div>

到此,我们就完成了以注解形式整合Struts2和Spring两大框架。

Struts2 整合Spring(Maven,注解版)的更多相关文章

  1. Spring Boot整合MyBatis(非注解版)

    Spring Boot整合MyBatis(非注解版),开发时采用的时IDEA,JDK1.8 直接上图: 文件夹不存在,创建一个新的路径文件夹 创建完成目录结构如下: 本人第一步习惯先把需要的包结构创建 ...

  2. struts2整合spring的思路

    struts2整合spring有有两种策略: >sping容器负责管理控制器Action,并利用依赖注入为控制器注入业务逻辑组件. >利用spring的自动装配,Action将自动会从Sp ...

  3. struts2整合spring出现的Unable to instantiate Action异常

    在struts2整合spring的时候,完全一步步按照官方文档上去做的,最后发现出现 Unable to instantiate Action,网上一搜发现很多人和我一样的问题,配置什么都没有错误,就 ...

  4. 集成框架 javaweb开发平台ssmy_m(生成代码) java struts2 mybatis spring maven jquery

    网页地址 http://blog.csdn.net/lpy3654321/article/details/31841573 项目设想,在项目开发中,我们的开发者大多数时间都在反复开发 相同的keywo ...

  5. struts2整合spring应用实例

    我们知道struts1与spring整合是靠org.springframework.web.struts.DelegatingActionProxy来实现的,以下通过具体一个用户登录实现来说明stru ...

  6. Struts2—整合Spring

    Struts2—整合Spring Spring框架是一个非常优秀的轻量级java EE容器,大部分javaEE应用,都会考虑使用Spring容器来管理应用中的组件. Struts2是一个MVC框架,是 ...

  7. struts2+hibernate-jpa+Spring+maven 整合(1)

    1.0.0 struts2 与 spring 的整合. 1.1.0 新建maven工程 , 编写pom.xml ,这里只需要简单的添加 一个组件就够了: 在myeclipse 生成的pom.xml 添 ...

  8. springboot 用redis缓存整合spring cache注解,使用Json序列化和反序列化。

    springboot下用cache注解整合redis并使用json序列化反序列化. cache注解整合redis 最近发现spring的注解用起来真的是很方便.随即产生了能不能吧spring注解使用r ...

  9. spring mvc注解版01

    spring mvc是基于servlet实现的在spring mvc xml版中已经说过了,注解版相较于xml版更加简洁灵活. web项目的jar包: commons-logging-1.1.3.ja ...

随机推荐

  1. Fedora 24 Gnome Boxes 无法ping通网络

    安装Fedora 24在试用虚拟机时发现无法ping通外网. 我傻傻地以为是软件问题. 问题描述: 尝试ping程序来测试网络连通性: (我之前也是ping百度,后来在为了少打字百度了一些比较短的域名 ...

  2. Git 学习笔记参考

    1.参考学习资料 网上资料: http://www.cnblogs.com/aoguren/p/4189086.html http://www.liaoxuefeng.com/wiki/0013739 ...

  3. SQL实现类似于自动刷新数据的功能

    有时需要在SQL中,定时刷新某张表,比如说是要定时查询某张表的行数,通常做法就是手动的按F5去执行来刷新数据.但是如果这个定时查询历时较长,10分钟,或半小时,手动的话肯定是要崩溃了.貌似SQL没有像 ...

  4. ios图文混排

    图文混排的形式 1. 富文本形式 2. core Text(文字排版) 3. TextKit 4. UIWebView 一.富文本 我们可以采用attributeString来进行图文混排.例如一个文 ...

  5. tyvj1087 sumsets

    背景 广东汕头聿怀初中 Train#2 Problem1 描述     正整数N可以被表示成若干2的幂次之和.例如,N = 7时,共有下列6种不同的方案:1) 1+1+1+1+1+1+12) 1+1+ ...

  6. rqnoj343 mty的考验

    题目描述 啊!几经周折.mty终于找到了他的偶像.他就是….fyc! 可是fyc这样的高级人士可不喜欢一个人总是缠着他.于是他出了一道难题想考考mty.fyc有几个手下:陈乐天,舒步鸡,胡巍……现在f ...

  7. linux内核调度算法(2)--CPU时间片如何分配 转!

    http://blog.csdn.net/russell_tao/article/details/7103012 内核在微观上,把CPU的运行时间分成许多分,然后安排给各个进程轮流运行,造成宏观上所有 ...

  8. 守护神 Supervisor

    参考: http://linbo.github.io/2013/04/04/supervisor/ http://www.restran.net/2015/10/04/supervisord-tuto ...

  9. [转] ImageView的android:adjustViewBounds属性

    原文链接:http://blog.csdn.net/pingchuanyang/article/details/9252689   取值为true时: Adjust the ImageView's b ...

  10. NEFU 558 迷宫寻路

    题目链接 简单搜索题 #include <cstdio> #include <iostream> #include <cstring> using namespac ...