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

© 版權聲明:本文爲博主原創文章,轉載請註明出處html

1.搭建環境java

  Struts2:2.5.10web

  Spring:4.3.8.RELEASEspring

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

2.準備工做tomcat

  使用Eclipse或IDEA建立一個maven項目,本次SSH的框架搭建主要以註解方式實現爲主。app

3.Spring和Struts2整合框架

  整合內容:此整合主要是將Struts2的Action的建立工做交由Spring進行統一管理,主要是使用Spring的控制反轉和依賴注入功能。ssh

  3.1 首先引入Spring和Struts2的核心jar包,又因本項目是web項目,所以還需由於spring-web.jar包,以及Spring和Struts2整合所需的struts2-spring-plugin.jar。jsp

    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 = \u5546\u54c1\u4ef7\u683c\u8f93\u5165\u683c\u5f0f\u6709\u8bef

  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的整合。

相關文章
相關標籤/搜索