Struts2 整合Spring(Maven,注解版)

时间:2022-08-02 15:30:44

这两天正在试验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两大框架。