Maven环境下搭建SSH框架之Spring整合Struts2

© 版权声明:本文为博主原创文章,转载请注明出处

1.搭建环境

  Struts2:2.5.10

  Spring:4.3.8.RELEASE

  注意:其他版本在某些特性的使用上可能稍微存在差别

2.准备工作

  使用Eclipse或IDEA创建一个maven项目,本次SSH的框架搭建主要以注解方式实现为主。

3.Spring和Struts2整合

  整合内容:此整合主要是将Struts2的Action的创建工作交由Spring进行统一管理,主要是使用Spring的控制反转和依赖注入功能。

  3.1 首先引入Spring和Struts2的核心jar包,又因本项目是web项目,因此还需因为spring-web.jar包,以及Spring和Struts2整合所需的struts2-spring-plugin.jar。

    struts2-spring-plugin.jar必须放在Spring依赖后面,原因可以参考:http://www.cnblogs.com/jinjiyese153/p/6972030.html

    所以需要在pom.xml中引入四个jar包的依赖(这四个jar包的相关依赖maven会自动帮我们引入,所以不需我们配置)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  
  	<modelVersion>4.0.0</modelVersion>
  
	<groupId>org.ssh</groupId>
	<artifactId>SSH</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<!-- 统一源码的编码方式 -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- 统一各个框架版本 -->
		<struts.version>2.5.10</struts.version>
		<spring.version>4.3.8.RELEASE</spring.version>
	</properties>

	<dependencies>
		<!-- Junit依赖 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<!-- Spring 核心依赖 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-core</artifactId>
		    <version>${spring.version}</version>
		</dependency>
		<!-- Spring web依赖 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-web</artifactId>
		    <version>${spring.version}</version>
		</dependency>
        <!-- Struts2 核心依赖 -->
		<dependency>
		    <groupId>org.apache.struts</groupId>
		    <artifactId>struts2-core</artifactId>
		    <version>${struts.version}</version>
		</dependency>
		<!-- Struts2和Spring整合依赖 -->
		<dependency>
		    <groupId>org.apache.struts</groupId>
		    <artifactId>struts2-spring-plugin</artifactId>
		    <version>${struts.version}</version>
		</dependency>
	</dependencies>
	
	<build>
	  	<plugins>
            <!-- 统一源代码编译输出的JDK版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <!-- 打包时跳过单元测试 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
            <!-- 集成Tomcat插件 -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/${project.artifactId}</path>
                </configuration>
            </plugin>
        </plugins>
	</build>
	
</project>

  3.2 在web.xml中配置Struts2过滤器和Spring的监听器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
         
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
	<!-- 配置Struts2过滤器 -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 配置Spring的监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 指定Spring配置文件所在路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
         
</web-app>

  3.3 创建一个测试页面index.jsp(新增商品界面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>新增商品界面</title>
</head>
<body>
	<h1>新增商品</h1>
	<s:actionmessage/>
	<s:form action="product_save" method="post" namespace="/" theme="simple">
		<table width="600px">
			<tr>
				<th>商品名称</th>
				<td><s:textfield name="pname"/></td>
				<td><font color="red"><s:fielderror fieldName="pname"/></font></td>
			</tr>
			<tr>
				<th>商品价格</th>
				<td><s:textfield name="price"/></td>
				<td><font color="red"><s:fielderror fieldName="price"/></font></td>
			</tr>
			<tr>
				<th colspan="2">
					<input type="submit" value="保存"/>
				</th>
				<th> </th>
			</tr>
		</table>
	</s:form>
</body>
</html>

  3.4 创建商品的实体类(Product.java)

package org.ssh.product.model;

public class Product {

	private int pid;// 商品ID
	private String pname;// 商品名称
	private double price;// 商品价格
	
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	
}

  3.5 创建商品操作控制层(ProductAction.java)

package org.ssh.product.action;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 商品操作-控制层
 *
 */
public class ProductAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	private String pname;
	private double price;
	
	/**
	 * 保存商品操作
	 * 
	 * @return
	 */
	public String saveProduct() {
		
		System.out.println(pname);
		this.addActionMessage("保存成功...");
		return SUCCESS;
		
	}

	public String getPname() {
		return pname;
	}

	public void setPname(String pname) {
		this.pname = pname;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}
	
	@Override
	public void validate() {
		
		if(pname == null || "".equals(pname.trim())) {
			this.addFieldError("pname", "商品名称不能为空");
		}
		
	}
	
}

  3.6 创建struts.xml,并创建Struts2的资源文件messageResource.properties

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

	<!-- 默认访问页面 -->
	<package name="default" extends="struts-default" namespace="/">
		<default-action-ref name="default"/>
		<action name="default">
			<result>/WEB-INF/view/index.jsp</result>
		</action>
	</package>

	<!-- 商品相关请求转发 -->
	<!-- Struts2在2.5版本后添加strict-method-invocation(严格方法访问),默认为true,不能使用动态方法调用功能,故需设为false -->
	<package name="product" extends="struts-default" namespace="/"  strict-method-invocation="false">
		<!-- 保存商品 -->
		<action name="product_*" class="productAction" method="{1}Product">
			<result>WEB-INF/view/index.jsp</result>
			<result name="input">WEB-INF/view/index.jsp</result>
		</action>
	</package>
	
	<!-- 引入资源文件 -->
	<constant name="struts.custom.i18n.resources" value="messageResource"></constant>

</struts>

  messageResource.properties

invalid.fieldvalue.price = u5546u54c1u4ef7u683cu8f93u5165u683cu5f0fu6709u8bef

  3.7 创建applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
	<!-- 开启包扫描,并注册注解 -->
	<context:component-scan base-package="org.ssh.*"/>
        
</beans>

  3.8 当开启包扫描后,需要给相应的类添加注解,所以ProdcutAction.java添加@Controller注解;此时Action已交由Spring进行管理。但是Struts2对Action的默认作用域是多实例的(prototype),而Spring默认Bean的作用域是单实例的,所以需设置Action的作用域为多实例的。两者区别可参考http://www.cnblogs.com/jinjiyese153/p/6970683.html

  3.9 此时Action的创建应该交由Spring进行管理,所以将struts.xml中的class改为productAction(@Controller未指定名称,因此默认类名首字母小写)

  3.10 启动项目,查看结果

    1) 启动

    

    2)数据正常

    

    3)数据格式错误

    

  至此,Spring和Struts2的整合完成。接下来要进行Spring和Hibernate的整合。

原文地址:https://www.cnblogs.com/jinjiyese153/p/6964074.html