SSH框架搭建小例

来源:互联网 发布:艾宾浩斯背单词软件 编辑:程序博客网 时间:2024/06/05 16:04

SSH环境搭建


目录

一、概述 2

1.资源下载 2

2.开发环境安装 2

2.1 JDK的安装 3

2.2 Eclipse的安装 5

2.3 Tomcat的安装 5

2.4 将Tomcat导入到Eclipse中 7

2.4 将SVN导入到Eclipse中 12

二、 SSH框架实例 14

1.SSH基本原理 14

2.例程简介 15

3.创建工程搭建框架 17

3.1 新建一个工程 17

3.2 在Eclipse中配置数据源 18

3.3 SSH框架搭建 25

3.3.1 映射数据库 25

3.3.2 建立Dao接口和接口的应用文件 26

3.3.3 业务逻辑层配置 30

3.3.4 struts层配置 31

3.3.6 测试文件 37

3.3.7 登陆测试 38

一、概述

1.资源下载

所需安装文件下载列表

l jdk-7u5-windows-i586.exe

Oracle官方网站:http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1637583.html

l eclipse-jee-indigo-SR1-win32.zip

Eclipse官方网站:http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/indigo/SR1/eclipse-jee-indigo-SR1-win32.zip

l apache-tomcat-7.0.29-windows-x86.zip(点击“32-bit Windows zip (pgp, md5)”下载)

Apache官方网站:http://tomcat.apache.org/download-70.cgi#7.0.29

l Tomcat插件tomcatPluginV33.zip

http://www.eclipsetotale.com/tomcatPlugin.html 

l SVN插件site-1.0.6.zip

http://subclipse.tigris.org/servlets/ProjectDocumentList?folderID=2240

l MySQL5.5.25

http://www.mysql.com/downloads/mysql/5.5.html

l Spring3.1.0:

直接下载jar包,然后在工程中引入spring的jar包,下载地址:http://www.springsource.org/download

l Struts2.2.1:

http://struts.apache.org/downloads.html

l Hibernate:

hibernate-distribution-3.6.0.Final-dist.zip

http://sourceforge.net/projects/hibernate/files/hibernate3/3.6.0.Final/

注:以上安装文件在

\\10.96.92.89\htdocs\software\SSH框架搭建\开发工具软件

示例代码

\\10.96.92.89\htdocs\software\SSH框架搭建\Login

\\10.96.92.89\htdocs\software\SSH框架搭建\sql

2.开发环境安装

JDK的安装目录统一为 C:\Program Files\Java\jdk1.7.0_01

eclipse的安装目录统一为 D:\eclipse

tomcat的安装目录统一为 D:\apache-tomcat-7.0.29-windows-x86\apache-tomcat-7.0.29

2.1 JDK的安装

直接双击JDK的安装文件安装即可。

安装完JDK以后,需要配置一下环境变量,在我的电脑->属性->高级->环境变量->系统变量中添加以下环境变量:

JAVA_HOME= C:\Program Files\Java\jdk1.7.0_01 classpath=.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;

(.;一定不能少,因为它代表当前路径) 

path=%JAVA_HOME%\bin

然后在命令行输入javac,java,java -version如果出现如PIC1,PIC2和PIC3所示,就说明JDK安装成功。

PIC1

PIC2

PIC3

2.2 Eclipse的安装

将下载的Eclipse放在桌面上,然后解压到D:\eclipse。

双击eclipse会出现PIC4,PIC4显示的是我们设置的默认工作区的路径。

PIC4

我们默认工作区域,点击OK,出现如PIC5的界面说明安装成功。

PIC5

2.3 Tomcat的安装

1) 将下载好的apache-tomcat-7.0.29-windows-x86解压到

D:\apache-tomcat-7.0.29-windows-x86\apache-tomcat-7.0.29

2) 在我的电脑->属性->高级->环境变量->系统变量中添加以下环境变量(上述Tomcat安装目录:D:\apache-tomcat-7.0.29-windows-x86\apache-tomcat-7.0.29):

CATALINA_HOME:D:\apache-tomcat-7.0.29-windows-x86\apache-tomcat-7.0.2 9

CATALINA_BASE: D:\apache-tomcat-7.0.29-windows-x86\apache-tomcat-7.0.29

TOMCAT_HOME: D:\apache-tomcat-7.0.29-windows-x86\apache-tomcat-7.0.29

3) 修改环境变量中的classpath,把D:\apache-tomcat-7.0.29-windows-x86\apache-tomcat-7.0.29\lib\servlet-api.jar追加到classpath中去。

4) 双击D:\apache-tomcat-7.0.29-windows-x86\apache-tomcat-7.0.29\bin\startup.启动Tomcat,在浏览器中输入:http://localhost:8080,如果看到如PIC6Tomcat的欢迎界面,说明安装成功。

PIC6

5) 修改Tomcat启动最大允许时间

当启动tomcat时候出现 Server Tomcat v6.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor. 的错误,那表示你的tomcat启动超时了,有时候你重新启动下就好了,但有时需要重新启动很多次,如果你不想这样的话,你只需修改下tomcat的启动时间就行了,步骤如下:

修改 workspace\.metadata\.plugins\org.eclipse.wst.server.core\servers.xml文件。

<servers>

<server hostname="localhost" id="JBoss v5.0 at localhost" name="JBoss v5.0 at localhost" runtime-id="JBoss v5.0" server-type="org.eclipse.jst.server.generic.jboss5" server-type-id="org.eclipse.jst.server.generic.jboss5" start-timeout="1000" stop- timeout="15" timestamp="0">

<map jndiPort="1099" key="generic_server_instance_properties" port="8090" serverAddress="127.0.0.1" serverConfig="default"/>

</server>

</servers>

把 start-timeout="45" 改为 start-timeout="1000" 或者更长 重启eclipse就可以了。

2.4 将Tomcat导入到Eclipse中

方法一:

将Tomcat配置到Eclipse中,采用插件的方式:

1)将解压后的tomcatPlugin文件夹放到D:\eclipse\plugins目录 下。

2)重新启动 Eclipse,可在菜单栏看到 Tomcat 选项如图PIC5。如果没有看到Tomcat选项,需要改配置文件D:\eclipse\configuration\config.ini,将org.eclipse.update.reconcile=false 改为org.eclipse.update.reconcile=true.

3)重新启动 Eclipse,可在菜单栏看到 Tomcat 选项如图PIC7,此时还需 对其进行配置,在Window>Preferences>Tomcat 中,选择 Tomcat 版本 Version7.x,在Tomcat home中输入tomcat7所在的文件夹的路径即可;Context Declaration mode选择Context files模式,Contexts directory中也输入tomcat7所在的文件夹的路径;如PIC8:

PIC7

PIC8

4)通过eclipse菜单栏的tomcat按钮启动tomcat:在浏览器上输入:  http://localhost:8080/

若出现如图PIC9,则说明配置成功:

PIC9

方法二:

1)打开Eclipse,在下方的工作区找到servers,在servers空白区域右键->new->Server出现如PIC10的界面,选择Apache->Tomcat v7.0 Server->Next出现图PIC11界面,设置Tomcat安装目录。

2)重新打开eclipse,此时还需对其进行配置,在Window>Preferences>Tomcat 中,选择 Tomcat 版本 Version7.x,在Tomcat home中输入tomcat7所在的文件夹的路径即可;Context Declaration mode选择Context files模式,  Contexts directory中也输入tomcat7所在的文件夹的路径。

注:用此方法配置服务器,在Eclipse菜单栏不会出现Tomcat图标,每次运行项目时要选中项目右键->Run as->Run on Server->选择这个服务器。

PIC10

PIC11

3)在浏览器上输入:http://localhost:8080/

如果不成功,双击新建的server,更改两项内容,如下图所示。Deploy path 为D:\apache-tomcat-7.0.29-windows-x64\apache-tomcat-7.0.29\webapps

PIC12

2.4 将SVN导入到Eclipse中

1) 在eclipse根目录下新建文件夹links,这样就得到了eclipse\links

2)新建3个文件夹,myplugins,svn,eclipse,目录结构为:   D:\eclipse\myplugins\svn\eclipse

3) 将svn 解压缩之后的文件放到D:\eclipse\myplugins\svn\eclipse

4) 在eclipse\links下新建一个link文件(需要为每个插件建一个.link文件),比如svn.link,在这里我们svn插件安装目录结构为D:\eclipse\myplugins\svn\eclipse,所以link文件名命名为svn.link

5) 在svn.link中写入如下一句话path=D:\\eclipse\\myplugins\\svn即path=你的插件安装目录(代表eclipse 去哪个路径加载查件)注:svn.link 写路径的时候不能有汉字,否则失败。

6) 重新启动eclipse(如果你的eclipse安装SVN插件之前启动过需要先把eclipse关掉)

注:path路径的写法使用"/"或"\\"而不是用"\"取代。此处容易出错。

重要:如果发现插件没有安装成功,则删除eclipse目录下configuration目录中的件夹org.eclipse.update(这是一个记录插件更新情况的文件夹),删除掉这个文件后,eclipse会重新扫描所有插件,此时重启eclipse,可能会比较缓慢。如果仍然能发现插件,则打开eclipse\configuration\config.ini,做如下图所示的修改。

PIC13

7)重启eclipse,点击Open Perspective->Other如出现如图PIC13,则说明发现了插件,将上述的true重新改为false,否则每次启动eclipse速度都很缓慢。

PIC13

PIC14

二、SSH框架实例

1.SSH基本原理

SSH框架四个主要配置文件及关联关系的介绍:

    SSH是struts,spring和hibernate的简称,简单来说,struts是控制用的,hibernate是操作数据库的,spring是用来解耦的。

具体来说:

1)struts 负责 web 层 .ActionFormBean 接收网页中表单提交的数据,然后通过 Action 进行处理,再 Forward 到对应的网页。在 struts.xml 中定义 <action-mapping>, ActionServlet 会加载。

2) spring 负责业务层管理,即 Service (或 Manager).service 为 action 提供统计的调用接口,封装持久层的 DAO.也可以写一 些自己的业务方 法。统一的 javabean 管理方法,声明式事务管理,集成 Hiberante等。

3)Hibernate,负责持久化层,完成数据库的增删改查操作,hibernate为 持久层,提供 OR/Mapping。它有一组 .hbm.xml 文件和 POJO, 是跟数据 库中的表相对应的。然后定义 DAO ,这些是跟数据库打交道的类,它们会 使用 PO 。

在 struts+spring+hibernate 的系统中,对象的调用流程是: jsp-> Action - > Service ->DAO ->Hibernate 。数据的流向是 ActionFormBean 接受用户的数据, Action 将数据从 ActionFromBean 中取出,封装成 VO (value object值对象)或 PO(持久 化对象),再调用业务层的 Bean 类,完成各种业务处理后再 forward 。而 业务层 Bean 收到这个 PO 对象之后,会调用 DAO 接口方法,进行持久化操作。

spring:Aop管理事务控制,IoC管理各个组件的耦合,DaoTemplate作为常规 持久层的快速开发模板

struts:控制层Action,页面标签和Model数据,调用业务层

Hibernate:负责数据库和对象的映射,负责DAO层(Data Access Object:数 据访问)

spring整合hibernate和struts,只要在配好了applicationContext.xml,在struts的action中直接调用就可以了。hibernate访问数据库的操作都在spring中实现了,spring的调用又在stuts的action中实现了。通过以上思路这个ssh框架就连到了一起。

一般来说SSH框架主要包括四类配置文件web.xml,applicationcontext.xml(Spring),struts.xml(Struts),cfg.xml(Hibernate)。

2.例程简介

    实现简单用户登录操作(用户名和密码均为admin),用户将看到一个登录页面,要求用户输入用户名以及密码。如果用户名以及密码都是admin,提示登录成功。否则提示登录失败。

首先需要导入框架所需要的jar包。导入jar包的方法是将所需要的jar包复制到所建工程目录/WebContent/WEB-INF/lib文件夹下。

注:SSH所需jar包可在\\10.96.92.84\ShareFolder\项目\SSH框架搭建\ssh所需JAR包文件夹下找到。

所需要的包如下图PIC15所示:

PIC15

最后得到的工程结构图如下所示:

PIC16

3.创建工程搭建框架

3.1 新建一个工程

打开eclipse,进入eclipse开发页面,新建一个动态的web工程:

PIC17

PIC18

建好的工程如下图所示名为test的工程:

PIC19

3.2 在Eclipse中配置数据源

3.2.1在Window选项中选择Show view选项中的Data Source Explorer,将其显示在控制台区域,如图所示:

PIC20

3.2.2 右键单击,选择new,弹出对话框,选择MySQL:如图所示

PIC21

PIC22

PIC23

在工程的lib文件夹下选择数据库驱动jar。

PIC24

PIC25

PIC26

PIC27

注:驱动版本和jar包版本要一样。

点击右下角,Test Connection,如果出现以下对话框,说明数据源配置成功:

PIC28

3.3 SSH框架搭建

3.3.1 映射数据库

首先是用到Hibernate层将数据库映射对象,以后的我们操作数据库时只需要对对象进行操作,不需要再进入数据库操作。这部分主要用到两个文件,一个是将数据库建模,另一个是配置数据库的映射文件(.xml)。

在src文件夹下面,建立一个java包com.hitachi.riskmanagement.model,在这个包里建立一个User.java文件用来建模数据,语句如下:

package com.hitachi.riskmanagement.model;

public class User {

private int id;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

private String name;

private String pass;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getPass() {

return pass;

}

public void setPass(String pass) {

this.pass = pass;

}

}

数据库中id为主键,name和pass分别为用户名和密码。

接下来配置映射文件User.hbm.xml具体语句如下:

<?xml version="1.0" encoding="GBK"?>

<!-- 指定Hibernate映射文件的DTD信息 -->

<!DOCTYPE hibernate-mapping PUBLIC 

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- Hibernate映射文件的根元素 -->

<hibernate-mapping package="com.hitachi.riskmanagement.model">

<class name="User" table="loginuser">

<!-- 映射标识属性 -->

<idname="id" type="integer" column="user_id">

<!-- 指定使用identity主键生成策略 -->

<generator class="identity"/>

</id>

<!-- 映射普通属性 -->

<property name="name" column="user_name"type="string"

not-null="true" length="50" unique="true"/>

<property name="pass" column="user_password"type="string"

not-null="true" length="50"/>

</class>

</hibernate-mapping>

3.3.2 建立Dao接口和接口的应用文件

dao接口放在文件夹com.hitachi.riskmanagement.dao,在这个文件夹下面建立UserDao.java文件,具体内容如下:

package com.hitachi.riskmanagement.dao;

import com.hitachi.riskmanagement.model.User;

public interface UserDao {

public User getUser(String name,String pass);

}

在文件夹com.hitachi.riskmanagement.dao.impl文件夹下建立继承实现接口的文件UserDaoImpl.java文件。具体内容如下:

package com.hitachi.riskmanagement.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hitachi.riskmanagement.dao.UserDao;

import com.hitachi.riskmanagement.model.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

public User getUser(String name, String pass) {

List<User> list=getHibernateTemplate().find("from User");

if (list.size()==0)

return null;

for(int i=0;i<list.size();i++){

User u=list.get(i);

if(u.getName().equals(name)&&u.getPass().endsWith(pass)){

return u;

}

}

return null;

}

public static void main(String[] args){

User u=new UserDaoImpl().getUser("admin","admin");

if(u!=null){

System.out.println(u.toString());

}

}

}

创建Session工厂,对数据进行持久化操作,对数据的每个操作都通过Session工厂来完成。

 ·SessionFactory接口:SessionFactory接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。   ·Configuration接口:Configuration接口负责配置并启动Hibernate,创建SessionFactory对象。在Hibernate的启动的过程中,Configuration类的实例首先定位映射文档位置、读取配置,然后创建SessionFactory对象。 

在文件夹com.hitachi.riskmanagement目录下建立文件HibernateSessionFactory.java具体内容如下:

package com.hitachi.riskmanagement;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.cfg.Configuration;

import org.hibernate.cfg.AnnotationConfiguration;

/**

 * Configures and provides access to Hibernate sessions, tied to the

 * current thread of execution.  Follows the Thread Local Session

 * pattern, see {@link http://hibernate.org/42.html }.

 */

public class HibernateSessionFactory {

    /** 

     * Location of hibernate.cfg.xml file.

     * Location should be on the classpath as Hibernate uses  

     * #resourceAsStream style lookup for its configuration file. 

     * The default classpath location of the hibernate config file is 

     * in the default package. Use #setConfigFile() to update 

     * the location of the configuration file for the current session.   

     */

    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    private  static Configuration configuration = new AnnotationConfiguration();    

    private static org.hibernate.SessionFactory sessionFactory;

    private static String configFile = CONFIG_FILE_LOCATION;

static {

    try {

configuration.configure(configFile);

sessionFactory = configuration.buildSessionFactory();

} catch (Exception e) {

System.err

.println("%%%% Error Creating SessionFactory %%%%");

e.printStackTrace();

}

    }

    private HibernateSessionFactory() {

    }

/**

     * Returns the ThreadLocal Session instance.  Lazy initialize

     * the <code>SessionFactory</code> if needed.

     *

     *  @return Session

     *  @throws HibernateException

     */

    public static Session getSession() throws HibernateException {

        Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {

if (sessionFactory == null) {

rebuildSessionFactory();

}

session = (sessionFactory != null) ? sessionFactory.openSession()

: null;

threadLocal.set(session);

}

        return session;

    }

/**

     *  Rebuild hibernate session factory

     *

     */

public static void rebuildSessionFactory() {

try {

configuration.configure(configFile);

sessionFactory = configuration.buildSessionFactory();

} catch (Exception e) {

System.err

.println("%%%% Error Creating SessionFactory %%%%");

e.printStackTrace();

}

}

/**

     *  Close the single hibernate session instance.

     *

     *  @throws HibernateException

     */

    public static void closeSession() throws HibernateException {

        Session session = (Session) threadLocal.get();

        threadLocal.set(null);

        if (session != null) {

            session.close();

        }

    }

/**

     *  return session factory

     *

     */

public static org.hibernate.SessionFactory getSessionFactory() {

return sessionFactory;

}

/**

     *  return session factory

     *

     *session factory will be rebuilded in the next call

     */

public static void setConfigFile(String configFile) {

HibernateSessionFactory.configFile = configFile;

sessionFactory = null;

}

/**

     *  return hibernate configuration

     *

     */

public static Configuration getConfiguration() {

return configuration;

}

}

3.3.3 业务逻辑层配置

以上主要涉及到Hibernate层的设置,接下来讨论spring层的文件配置:

主要包括业务逻辑接口和业务逻辑继承和实现的对象。具体service接口放在文件夹com.hitachi.riskmanagement.service目录下,名称为UserService.java,具体内容为:

package com.hitachi.riskmanagement.service;

import com.hitachi.riskmanagement.model.User;

public interface UserService {

public User getUser(String name,String pass);

}

在文件夹com.hitachi.riskmanagement.service.impl目录下有UserServiceImpl.java文件具体内容为:

package com.hitachi.riskmanagement.service.impl;

import com.hitachi.riskmanagement.dao.UserDao;

import com.hitachi.riskmanagement.model.User;

import com.hitachi.riskmanagement.service.UserService;

public class UserServiceImpl implements UserService {

private UserDao userDao;

public UserDao getUserDao() {

return userDao;

}

public void setUserDao(UserDao userDao) {

this.userDao = userDao;

}

public User getUser(String name, String pass) {

return userDao.getUser(name, pass);

}

}

3.3.4 struts层配置

下面是struts层文件,主要涉及到action的创建,在文件夹com.hitachi.riskmanagement.action目录下有UserAction.java文件,具体内容为:

package com.hitachi.riskmanagement.action;

import com.hitachi.riskmanagement.model.User;

import com.hitachi.riskmanagement.service.UserService;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{

/**

 * 

 */

private static final long serialVersionUID = 1L;

private UserService userService;

public UserService getUserService() {

return userService;

}

public void setUserService(UserService userService) {

this.userService = userService;

}

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

private String pwd;

public String execute(){

System.out.println("name:"+name+",pwd:"+pwd);

User u=userService.getUser(name, pwd);

if(u==null){

return "error";

}

return "success";

}

}

3.3.5 .xml文件配置 

配置好各层文件后下面配置.xml文件,将上述各个不同层次的文件连接起来。主要涉及到首先配置Hibernate与数据库相连接的文件hibernate.cfg.xml将其直接放在src文件夹下面,具体内容如下:

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->

<hibernate-configuration>

<session-factory>

<property name="dialect">

org.hibernate.dialect.MySQLDialect

</property>

<property name="connection.url">

jdbc:mysql://localhost:3306/mysql

</property>

<property name="connection.username">root</property>

<property name="connection.password">123qwe</property>

<property name="connection.driver_class">

com.mysql.jdbc.Driver

</property>

<!-- 格式化得输出SQL语句  -->

<property name="show_sql">true</property>

<property name="format_sql">true</property>

<!-- 在不设置此项的时候不能使用getCurrentSession()方法 -->

<property name="current_session_context_class">thread</property>

<!-- 在此设置映射关系 -->

<mapping resource="com/hitachi/riskmanagement/model/User.hbm.xml" class="com.hitachi.riskmanagement.model.User"/>

</session-factory>

</hibernate-configuration>

其次是struts配置文件,其主要内容是有不同的action组成,由于本实例比较简单,只涉及到一个action。将structs.xml文件直接放在src文件夹中。

structs.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<!-- 指定Struts2配置文件的DTD信息 -->

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"

"http://struts.apache.org/dtds/struts-2.1.7.dtd">

<!-- Struts2配置文件的根元素 -->

<struts>

<!-- 配置了系列常量 -->

<constant name="struts.custom.i18n.resources" value="resource"/>

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

<constant name="struts.devMode" value="true"/>

<constant name="struts.objectFactory" value="spring" /> 

<package name="default" namespace="/" extends="struts-default">

<!-- 定义处理登录系统的的Action -->

<action name="processLogin"class="com.hitachi.riskmanagement.action.UserAction" method="execute">

<result name="success">/success.jsp</result>

<result name="error">/error.jsp</result>

</action>

</package>

</struts>

接下来配置Spring配置文件applicationContext.xml,将这个文件放在WebContent\WEB-INF文件夹下面。具体内容如下:

<?xml version="1.0" encoding="GBK"?>

<!-- 指定Spring配置文件的Schema信息 -->

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:p="http://www.springframework.org/schema/p" 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/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,使用C3P0数据源实现 -->

<!-- 设置连接数据库的驱动、URL、用户名、密码 连接池最大连接数、最小连接数、初始连接数等参数 -->

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

destroy-method="close" p:driverClass="com.mysql.jdbc.Driver"

p:jdbcUrl="jdbc:mysql://localhost:3306/mysql" p:user="root"

p:password="123qwe" p:maxPoolSize="40" p:minPoolSize="1"

p:initialPoolSize="1" p:maxIdleTime="20" />

<!-- 定义Hibernate的SessionFactory -->

<!-- 依赖注入数据源,注入正是上面定义的dataSource -->

<bean id="sessionFactory"

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"

p:dataSource-ref="dataSource">

<!-- mappingResouces属性用来列出全部映射文件 -->

<property name="mappingResources">

<list>

<!-- 以下用来列出Hibernate映射文件 -->

<value>com/hitachi/riskmanagement/model/User.hbm.xml</value>

</list>

</property>

<!-- 定义Hibernate的SessionFactory的属性 -->

<property name="hibernateProperties">

<!-- 指定数据库方言、是否自动建表 是否生成SQL语句等 -->

<value>

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect

hibernate.hbm2ddl.auto=update

hibernate.show_sql=true

hibernate.format_sql=true

#开启二级缓存

hibernate.cache.use_second_level_cache=true

#设置二级缓存的提供者

hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

</value>

</property>

</bean>

<!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 -->

<!-- 该类实现PlatformTransactionManager接口,是针对Hibernate的特定实现 -->

<!-- 并注入SessionFactory的引用 -->

<bean id="transactionManager"

class="org.springframework.orm.hibernate3.HibernateTransactionManager"

p:sessionFactory-ref="sessionFactory" />

<!-- 配置事务增强处理Bean,指定事务管理器 -->

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<!-- 用于配置详细的事务语义 -->

<tx:attributes>

<!-- 所有以'get'开头的方法是read-only的 -->

<tx:method name="get*" read-only="true" />

<!-- 其他方法使用默认的事务设置 -->

<tx:method name="*" />

</tx:attributes>

</tx:advice>

<aop:config>

<!-- 配置一个切入点,匹配empManager和mgrManager 两个Bean的所有方法的执行 -->

<aop:pointcut id="leePointcut"

expression="execution(* com.hitachi.riskmanagement.service.impl.*.*(..))" />

<!-- 指定在leePointcut切入点应用txAdvice事务增强处理 -->

<aop:advisor advice-ref="txAdvice" pointcut-ref="leePointcut" />

</aop:config>

<bean id="userDao" class="com.hitachi.riskmanagement.dao.impl.UserDaoImpl">

<property name="sessionFactory" ref="sessionFactory"></property>

</bean>

<bean id="userService" class="com.hitachi.riskmanagement.service.impl.UserServiceImpl">

<property name="userDao" ref="userDao"></property>

</bean>

<bean id="userAction" class="com.hitachi.riskmanagement.action.UserAction">

<property name="userService" ref="userService"></property>

</bean>

</beans>

最后配置Web.xml文件,其内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>login</display-name>

  <welcome-file-list>

    <welcome-file>login.jsp</welcome-file>

  </welcome-file-list>

   <context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/applicationContext.xml</param-value>

</context-param>

<listener>

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

</listener-class>

</listener>

  <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>

  <!--

   -->

</web-app>

3.3.6 测试文件

编辑三个jsp文件作为测试用,具体如下:

Login.jsp主要用来登陆内容为:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!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>Insert title here</title>

</head>

<body>

<form action="processLogin" method="post">

用户名:<input name="name" type="text"><br/>

密码:<input name="pwd" type="password"><br/>

<input type="submit" value="提交"> <input type="reset" value="重置"> 

</form>

</body>

</html>

Error.jsp登陆错误时跳转到此页面,内容为:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!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>Insert title here</title>

</head>

<body>

登录失败!

</body>

</html>

Success.jsp当登陆成功时,跳转到此页面,具体内容为:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!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>Insert title here</title></head>

<body>

登陆成功!

</body>

</html>

3.3.7 登陆测试

完成以上各步骤后,运行此项目,出现PIC29界面后,输入用户名admin密码admin得到PIC30。说明框架搭建成功。

PIC29

PIC30

原创粉丝点击