ssi框架搭建

Struts2主要来源于webwork框架,与Struts1相比,在数据传递方面,Struts2提供了更加强大OGNL标签功能,使其能够通过在action中定义变量来直接与jsp页面中的数据进行相互传值,省去了Struts1中的formbean;而在跳转控制方面,Struts2简化了配置文件的信息量,使页面和action之间的交换更加的简洁和直观,便于开发人员的管理。

Spring功能非常的强大,比如它的控制反转/依赖注入机制,省去了我们自己书写工厂模式的工作,实现类对我们将要用到控制类、业务逻辑类、数据访问类、以及JNDI或者JDBC数据源的托管;Spring对AOP支持使我们在用户chmod.html' target='_blank'>权限控制、事务处理方面节省了很多工作量;

iBatis则是一种轻量级的OR Mapping框架,与Hibernate相比,iBatis提供了半自动化对象关系 映射的实现,开发人员需要编写具体的sql语句,为系统设计提供了更大的自由空间,为sql语句优化提供了便利。

下面这张图就是我们所用到的这三种框架的结合体,下面对其作以简单介绍。

                  

在控制层,利用Strtus2标签功能,在Action中直接与jsp页面上的数据进行交互。在调用业务逻辑层应用时,Struts2提供了对Sping的支持。开发人员需要完成对struts.xml的配置工作和对各个Action类的编写。

在业务逻辑层,利用Spring框架的依赖注入实现对业务逻辑类和DAO类的实例托管;在事务处理方面,利用Spring提供的面向切面的事务处理功能,使对数据的事务控制脱离于数据访问接口实现;在对象关系映射方面,利用Spring对数据库连接池的托管和对iBatis框架的支持。开发人员需要完成对数据源的配置、对不同模块所对应的application*.xml文件的配置,以及对业务逻辑接口的定义和业务逻辑实现的编写。

在持久层,利用iBatis提供的半自动化对象关系映射的实现,开发人员需要编写具体的sql语句,为系统设计提供了更大的自由空间。另外,开发人员需要完成对SqlMapConfig.xml和*SqlMap.xml的配置,以及对DAO接口的定义和DAO接口的实现。

在各层之间进行交换的过程中,利用数据传输类进行数据的传递和交互。其中,数据传输类与数据库表一一对应。

SSI框架能够降低我们代码的耦合度,增强了代码的健壮性和可重用性,加快了开发速度,但是也有一些不足之处,比如由于三种框架的配置文件较多,也给我们带来了一些不便,特别是对于较小的应用来说更是如此。

                                                                                                    

一:首先引入struts2 spring ibatis 各自的jar包 在此就不一一罗列了。

二:添加配置文件

   我们首先从web.xml文件说起 

   web.xml加载过程:
   1 启动WEB项目的时候,容器(如:Tomcat)会读他的配置文件web.xml读两个节点
         <listener></listener>和<context-param></context-param>
    2 紧接着,容器创建一个ServletContext(上下文) 这个WEB项目所有部分都将共享这个上下文
    3 容器将<context-param></context-param>转化为键值对并交给ServletContext
    4 容器创建<listener></listener>中的类的实例,即创建监听
    5 在监听中会有contextInitialized(ServletContextEvent args)初始化方法,在这个方法中获得:
              ServletContext = ServletContextEvent.getServletContext();   
              context-param的值 = ServletContext.getInitParameter("context-param的键"); 

     web.xml节点加载顺序
     节点的加载顺序与它们在web.xml文件中的先后顺序无关。即不会因为filter写在listener的前面而会先加载filter最终得出的结论是:listener->filter->servlet
     同时还存在着这样一种配置节点:context-param,它用于向 ServletContext 提供键值对,即应用程序上下文信息。我们的 listener, filter 等在初始化时会用到这些上下文 的信息,那么context-param 配置节是不是应该写在 listener 配置节前呢?实际上 context-param 配置节可写在任意位置,因此真正的加载顺序为:
context-param -> listener -> filter -> servlet
     加载spring
     <listener>  
             <listener-class>  
               org.springframework.web.context.ContextLoaderListener   
            </listener-class>  
       </listener>
     最终结论:

     web.xml 的加载顺序是:[context-param -> listener -> filter -> servlet -> spring] ,而同类型节点之间的实际程序调用的时候的顺序是根据对应的 mapping 的顺序进行调  用的。

    打开web.xml文件,根据实际需要添加如下内容

<!--上下文参数用于log4j以及spring中使用-->
<context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<!--应用程序上下文参数,指定spring配置文件位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/beans.xml</param-value>
</context-param> 

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener

-class>
</listener>

<!--监听器 用于初始化spring框架-->
<listener>
     <listener-

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


在这说说SSI整合时的一些配置文件:

 1.contextConfigLocation:Spring容器启动时需要加载Spring的配置文件。默认是/WEB-INF目录下的applicationContext.xml文件

   当然也可以放在classpath下,可以包括多个spring配置文件,这就得依靠contextConfigLocation

<!-- 加载spring的配置文件 如果文件名为applicationContext.xml并且是在WEB-INF目录下 则无需此配置 -->
    <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/beans.xml</param-value>
	</context-param> 

如果web.xml中没有配置context-param,spring的配置就像如上这段代码示例一下,自动去WEB-INF目录下寻找applicationContext.xml。此时,如果你修改applicationContext.xml的名称,或者移除它,再启动服务器,你会得到如下异常信息:

1.nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]  

这证实了其默认配置。默认配置情况下spring只会去WEB-INF目录下寻找配置文件,而不会去classpath下寻找。 
如果我们不想将配置文件放在WEB-INF目录下呢?开发中经常在src下面创建一个config目录,用于存放配置文件。此时,对应的param-value改为:classpath:config/applicationContext.xml。
一定要加上classpath,这告诉spring去classes目录下的config目录下面寻找配置文件。

2.如何启动Spring容器

两种方法,一种以listener启动  一种以load-on-startup Servlet。

<!-- 配置spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

第二种

<servlet>
 <servlet-name>context</servlet-name>
 <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>


 

 3.整合Struts2

   

<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


4.Spring整合ibatis配置文件

  

<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation"> 
			<value>classpath:SqlMapConfig.xml</value>
		</property>
	</bean>


5.Struts.xml

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

<package name="surveyParkPkg" namespace="/" extends="struts-default">
<!-- logAction -->
  <action name="UserAction_*" class="userAction" method="{1}">
    <result name="userList">/userList.jsp</result>
    <result name="showUsers" type="redirectAction">UserAction_findAllUser</result>
    <result name="updateUser">/updateUser.jsp</result>
  </action>
</package>
</struts>

constant配置struts的常量(也可在struts.properties)文件中配置,将struts的对象工厂托由spring管理。

6.beans.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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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
                         http://www.springframework.org/schema/tx
                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                         http://www.springframework.org/schema/aop 
                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- 数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123456f"/>
    </bean>
    
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    </bean>
    
    <!-- ================================事务相关控制=================================================    -->
    <bean name="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <tx:advice id="userTxAdvice"
        transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="select*" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pc" expression="execution(* cn.itcast.mybatis.service.*.*(..))" />
        <!--把事务控制在Service层-->
        <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
    </aop:config>
    
    <bean id="userDao" class="cn.itcast.mybatis.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sessionFactory"/>
    </bean>
    
    <bean id="userService" class="cn.itcast.mybatis.service.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
    </bean>
    
    <bean id="userAction" class="cn.itcast.mybatis.action.UserAction" scope="prototype">
        <property name="userService" ref="userService"/>
    </bean>
</beans>

7User.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.itcast.mybatis.domain.User">
    <select id="selectUserById" parameterType="string" resultType="User">
        select * from user where id = #{uid}
    </select>
    
    <select id="selectUserByIdForMap" parameterType="string" resultType="hashmap">
        select * from user where id = #{uid}
    </select>
    
    <select id="selectAllUser" resultType="User">
        select * from user
    </select>
    
    <select id="selectAllUserForMap" resultType="hashmap">
        select * from user
    </select>
    
    <delete id="deleteUserById" parameterType="string">
        delete from user where id  = #{uid}
    </delete>
    
    <insert id="saveUser" parameterType="User">
        insert into user (id,name,age,address) values(#{id},#{name},#{age},#{address})
    </insert>
    
    <insert id="saveUserForMap" parameterType="hashmap">
        insert into user (id,name,age,address) values(#{id},#{name},#{age},#{address})
    </insert>
    
    <update id="updateUserById" parameterType="User">
        update user set name = #{name} ,age = #{age},address = #{address} where id = #{id}
    </update>
    
    <update id="updateUserByIdForMap" parameterType="hashmap">
        update user set name = #{name} ,age = #{age},address = #{address} where id = #{id}
    </update>
    
    <!-- 动态sql -->
    <select id="selectUserByCondition" parameterType="User" resultType="User">
        select * from user where 1=1
        <if test="id != null">
            and id = #{id}
        </if>
        <if test="name != null">
            and name = #{name}
        </if>
        <if test="age != null">
            and age = #{age}
        </if>
        <if test="address != null">
            and address = #{address}
        </if>
    </select>
    
    <!-- 动态sql -->
    <select id="selectUserByConditionForMap" parameterType="hashmap" resultType="User">
        select * from user where 1=1
        <if test="id != null">
            and id = #{id}
        </if>
        <if test="name != null">
            and name = #{name}
        </if>
        <if test="age != null">
            and age = #{age}
        </if>
        <if test="address != null">
            and address = #{address}
        </if>
    </select>
    
    <!-- 动态sql -->
    <select id="selectUserByCondition2" parameterType="User" resultType="User">
        select * from user
        <where>
            <if test="id != null">
                id = #{id}
            </if>
            <if test="name != null">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="address != null">
                and address = #{address}
            </if>
        </where>
    </select>
    
    <!-- 动态sql 更新 -->
    <update id="updateUserByCondition" parameterType="User">
        update user 
        <set>
            <if test="name != null">
                 name = #{name},
            </if>
            <if test="age != null">
                 age = #{age},
            </if>
            <if test="address != null">
                 address = #{address}
            </if>
        </set>
            where id = #{id}
    </update>
    
</mapper>

8.UserAction

package cn.itcast.mybatis.action;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import cn.itcast.mybatis.domain.User;
import cn.itcast.mybatis.service.IUserService;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    public UserAction() {}
    private IUserService userService;
    private String id;
    /*
     * 查询所有数据
     */
    public String findAllUser(){
        HttpServletRequest req = ServletActionContext.getRequest();
        //User u = userService.findUserById(id);
        List<User> users = userService.selectUserByCondition(new User());
        req.setAttribute("users", users);
        return "userList";
    }
    /*
     * 根据选择的id进行删除  然后回显到  显示所有.jsp处
     */
    public String deleteUserById(){
        userService.deleteUserById(id);
        
        return "showUsers";
    }
    /*
     * 插入数据 并 保存数据库   然后回显到  显示所有.jsp处
     */
    public String saveUser(){
        HttpServletRequest req = ServletActionContext.getRequest();
        String id = UUID.randomUUID().toString();//javaJDK提供的一个自动生成主键的方法-16位
        String name = req.getParameter("name");
        String address = req.getParameter("address");
        String ageStr = req.getParameter("age");
        
        User u = new User();
        u.setId(id);
        u.setName(name);
        u.setAddress(address);
        u.setAge(new Integer(ageStr));
        
        userService.insertUser(u);
        
        return "showUsers";
    }
    /*
     * 点击修改链接  根据id进入一个编辑界面updateUser.jsp  里面存放的是根据点击的id查询到的数据信息
     * 修改完成后  <form action="<%=path %>/UserAction_updateUser" method="POST">
     * 把修改后的数据全部获取  然后封装到user中  通过updateUserByCondition(u)保到数据库
     * 然后回显    显示所有.jsp处
     */
    public String updateUserUI(){
        HttpServletRequest req = ServletActionContext.getRequest();
        String id = req.getParameter("id");
    
        User u = userService.findUserById(id);
        req.setAttribute("user", u);
        return "updateUser";
    }
    /*
     * 点击修改链接  根据id先回显到 本次数据    然后进行修改  修改完成后回显到显示所有.jsp处
     */
    public String updateUser(){
        HttpServletRequest req = ServletActionContext.getRequest();
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String address = req.getParameter("address");
        String ageStr = req.getParameter("age");
        
        User u = new User();
        u.setId(id);
        u.setName(name);
        u.setAddress(address);
        u.setAge(new Integer(ageStr));
        
        userService.updateUserByCondition(u);
        return "showUsers";
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

}

9.最后的页面显示部分   三个

UserList.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'userList.jsp' starting page</title>
  </head>
  
  <body> 
   <h3>UserList</h3>
   <a href="addUser.jsp">添加User</a>
   <table border="1" width="70%">
   		<tr>
   			<td>id</td>
   			<td>name</td>
   			<td>age</td>
   			<td>address</td>
   			<td>删除</td>
   			<td>修改</td>
   		</tr>
   		<c:forEach items="${requestScope.users}" var="user">
   		<tr>
   			<td>${user.id }</td>
   			<td>${user.name }</td>
   			<td>${user.age }</td>
   			<td>${user.address }</td>
   			<td><a href="<%=path %>/UserAction_deleteUserById?id=${user.id }">删除</a></td>
   			<td><a href="<%=path %>/UserAction_updateUserUI?id=${user.id }">修改</a></td>
   		</tr>
   		</c:forEach>
   </table>
  </body>
</html>

  addUser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'userList.jsp' starting page</title>
  </head>
  
  <body> 
   <h3>UserList</h3>
   <a href="addUser.jsp">添加User</a>
   <table border="1" width="70%">
   		<tr>
   			<td>id</td>
   			<td>name</td>
   			<td>age</td>
   			<td>address</td>
   			<td>删除</td>
   			<td>修改</td>
   		</tr>
   		<c:forEach items="${requestScope.users}" var="user">
   		<tr>
   			<td>${user.id }</td>
   			<td>${user.name }</td>
   			<td>${user.age }</td>
   			<td>${user.address }</td>
   			<td><a href="<%=path %>/UserAction_deleteUserById?id=${user.id }">删除</a></td>
   			<td><a href="<%=path %>/UserAction_updateUserUI?id=${user.id }">修改</a></td>
   		</tr>
   		</c:forEach>
   </table>
  </body>
</html>

  updateUser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<html>
	<head>
		<title>My JSP 'addUser.jsp' starting page</title>
	</head>

	<body>
		<form action="<%=path %>/UserAction_updateUser" method="POST">
			<input type="hidden" name="id" value="${user.id }">
			<table>
				<tr>
					<td> 
						name: 
					</td>
					<td>
						<input type="text" name="name" value="${user.name }">
					</td>
				</tr>
				<tr>
					<td>
						age:
					</td>
					<td>
						<input type="text" name="age" value="${user.age }">
					</td>
				</tr>
				<tr>
					<td>
						address:
					</td>
					<td>
						<input type="text" name="address" value="${user.address }">
					</td>
				</tr>
				<tr>
					<td>
						<input type="submit" value="保存">
					</td>
					<td>
						<input type="reset" value="重置">
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>

  项目搭建到 这基本完成  .......有些类就省略了  比较简单  最重要的还是思路吧   顺便截个屏  方便有心的人继续补全项目

原文地址:https://www.cnblogs.com/hoobey/p/7048326.html