首页 > 其他分享 >SSH 环境搭建(Spring3+Struts2+Hibernate3)

SSH 环境搭建(Spring3+Struts2+Hibernate3)

时间:2022-12-11 14:37:10浏览次数:78  
标签:Hibernate3 void firstSSH Struts2 session SSH edu com public


首先下载相应的文件和包:mysql tomcat spring3 struts2 hibernate3

1.先搭建一个struts2的web项目

打开Eclipse,File>>New>>Dynamic Web Project。在WebContent/WEB-INF文件夹下新建一个web.xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<!-- 配置struts2为项目的controller -->
<filter>
<filter-name>SSH</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>SSH</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>

这个web.xml中的<filter>元素定义了一个名为SSH的拦截器以及拦截器的实现类。<filter-mapping>定义了拦截器要拦截的用户请求,这里的话所有的请求都会被拦截下来,然后交给我们写的action来处理,这样的话,通过在web.xml中定义一个filter,完成了struts2的引入。

当然除此之外,我们还要导入struts2的jar包,下载解压后,将要用到的包复制到WebContent/WEB-INF/lib文件夹下。必须的jar包名字大致如下:


commons-fileupload-1.2.2.jar


commons-io-2.0.1.jar


commons-lang-2.5.jar


commons-logging-1.1.1.jar


freemarker-2.3.18.jar


ognl-3.0.4.jar


struts2-core-2.3.1.2.jar


xwork-core-2.3.1.2.jar


javassist-3.11.0.GA.jar



struts.xml:


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

<struts>

<include file="struts-default.xml" />
<package name="register" extends="struts-default">
<action name="register" class="com.edu.nju.firstSSH.Action.RegisterAction">
<result name="input">/WEB-INF/view/register.jsp</result>
<result name="success">/WEB-INF/view/success.jsp</result>
<result name="error">/WEB-INF/view/fail.jsp</result>
</action>
</package>

</struts>





下面建立Action类,代码如下:

package com.edu.nju.firstSSH.Action;


import com.edu.nju.firstSSH.FormBean.UserForm;
import com.edu.nju.firstSSH.Service.UserService;
import com.edu.nju.firstSSH.Service.UserServiceImp;
import com.opensymphony.xwork2.ActionSupport;


public class RegisterAction extends ActionSupport{


/**
*
*/
private static final long serialVersionUID = 1L;
private UserForm userform;
private UserService userService;


public String execute(){
userService = new UserServiceImp();
userService.register(userform);
return "success";
}


public UserForm getUserform() {
return userform;
}


public void setUserform(UserForm userform) {
this.userform = userform;
}


}


最后建立Userform类,封装表达数据:

package com.edu.nju.firstSSH.FormBean;


public class UserForm {


private String username;
private String password;
private int gender;

public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}




}

注册表单页面:

<%@ 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>User Register Page</title>
</head>
<body>

<s:form action="register" method="post">
<s:textfield name="userform.username" label="用户名"></s:textfield>
<s:password name="userform.password" label="密码"></s:password>
<s:select list="#{'1':'男','0':'女'}" listKey="key" listValue="value"
name="userform.gender" label="性别" value="1"></s:select>
<s:submit value="注册"></s:submit>
</s:form>

</body>
</html>


启动项目(run on server),浏览器访问如下:

SSH 环境搭建(Spring3+Struts2+Hibernate3)_struts

说明struts2配置完成。

项目目录如下:

SSH 环境搭建(Spring3+Struts2+Hibernate3)_xml_02

2.加入Hibernate

首先把要用到的hibernate包导入到lib下。

编写PO,首先写数据库实体类,User类,代码如下:

package com.edu.nju.firstSSH.Bean;

public class User {

private String name;
private String password;
private int gender;
private int userid;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}

public int getUserid() {
return userid;
}

public void setUserid(int userid) {
this.userid = userid;
}
}

User类与数据库中的表结构一一对应。

然后写PO的hibernate配置文件,每一个数据库表都要有一个配置文件和对应的类。配置文件命名为:User.hbm.xml,代码为:

<?xml version="1.0" encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.edu.nju.firstSSH.Bean">
<class name="User" table="test">
<id name="userid" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name" type="java.lang.String"
not-null="true" length="16"></property>
<property name="password" column="password" type="java.lang.String"
not-null="true" length="16" />
<property name="gender" column="gender" type="java.lang.Integer" length="1" />
</class>
</hibernate-mapping>

最后配置hibernate,在src中新建hibernate.cfg.xml,代码为:

<?xml version='1.0' encoding='utf-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property> -->

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<!-- <property name="current_session_context_class">thread</property> -->

<!-- Disable the second-level cache -->
<!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> -->

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">update</property> -->
<mapping resource="com/edu/nju/firstSSH/Bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>


这里还要引入数据库的驱动程序,放在lib下即可。这个配置文件指定了数据源的信息和POJO配置文件列表。


下面建立UserDao借口以及实现程序:

UserDao:

package com.edu.nju.firstSSH.UserDao;

import org.hibernate.Session;

public interface UserDao {

public void save(Object o);

public void setSession(Session session);

}

UserDaoImp:

package com.edu.nju.firstSSH.UserDao;  

import org.hibernate.HibernateException;
import org.hibernate.Session;

public class UserDaoImp implements UserDao {

private Session session;


public Session getSession() {
return session;
}


public void setSession(Session session) {
this.session = session;
}

@Override
public void save(Object obj) throws HibernateException {
session.save(obj);
}

}


这里的session方法是为了使用sessionFactory的。



最后是service层:

UserService:

package com.edu.nju.firstSSH.Service;

import com.edu.nju.firstSSH.FormBean.UserForm;

public interface UserService {

public void register(UserForm userForm);
}


UserServiceImp:


package com.edu.nju.firstSSH.Service;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.edu.nju.firstSSH.Bean.User;
import com.edu.nju.firstSSH.FormBean.UserForm;
import com.edu.nju.firstSSH.UserDao.UserDao;
import com.edu.nju.firstSSH.UserDao.UserDaoImp;

public class UserServiceImp implements UserService{

private Session session;
private UserDao userDao;

public UserServiceImp(){
userDao = new UserDaoImp();
}

@Override
public void register(UserForm userForm) {

session = HibernateSessionFactory.currentSession();
userDao.setSession(session);
// 获取事务
Transaction ts = session.beginTransaction();
// 构造User对象
User user = new User();
System.out.println("userForm: "+userForm);
user.setName(userForm.getUsername());
user.setPassword(userForm.getPassword());
user.setGender(userForm.getGender());
// 保存User对象
userDao.save(user);
// 提交事务
ts.commit();
// 关闭Session
HibernateSessionFactory.closeSession();

}
public Session getSession() {
return session;
}

public void setSession(Session session) {
this.session = session;
}


}

HibernateSessionFactory类:

package com.edu.nju.firstSSH.Service;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static final Configuration cfg = new Configuration() .configure();
private static SessionFactory sessionFactory;
public static Session currentSession() throws HibernateException {
Session session = threadLocal.get();
if (session == null || session.isOpen() == false) {
if (sessionFactory == null) {
try {
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() throws HibernateException {
Session session = threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
}

这是hibernate3获取hibernateFactory的方法。

项目目录为:

SSH 环境搭建(Spring3+Struts2+Hibernate3)_xml_03

至此,项目中加入了hibernate3。


3.引入spring3

首先写spring的配置文件,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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<!-- 定义数据源的信息 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="jdbcUrl">
<value>jdbc:mysql://localhost/test</value>
</property>
<property name="user">
<value>root</value>
</property>
<property name="password">
<value></value>
</property>
<property name="maxPoolSize">
<value>80</value>
</property>
<property name="minPoolSize">
<value>1</value>
</property>
<property name="initialPoolSize">
<value>1</value>
</property>
<property name="maxIdleTime">
<value>20</value>
</property>
</bean>

<!--定义Hibernate的SessionFactory -->
<!-- SessionFactory使用的数据源为上面的数据源 -->
<!-- 指定了Hibernate的映射文件和配置信息 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<property name="mappingResources">
<list>
<value>com/edu/nju/firstSSH/Bean/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
</props>
</property>
</bean>

<!-- 注册Dao -->
<bean id="userDao" class="com.edu.nju.firstSSH.UserDao.UserDaoImp">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>

<!-- 注册业务逻辑类 -->
<bean id="userService" class="com.edu.nju.firstSSH.Service.UserServiceImp">
<property name="userDao">
<ref bean="userDao" />
</property>
</bean>

<!-- 注册的Action -->
<bean id="reg" class="com.edu.nju.firstSSH.Action.RegisterAction">
<property name="userService">
<ref bean="userService" />
</property>
</bean>

<!-- more bean definitions go here -->

</beans>

这个文件其实声明了所有要用的对象实例,spring通过这个文件来管理这些实例,每一个实例就是一个<bean>,这样的话java文件中的private属性就不需要初始化了,只需要声明,然后提供getter setter方法就可以,spring会为我们注入这些实例,把他们赋值。

下面修改struts.xml文件为:

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

<struts>

<include file="struts-default.xml" />
<package name="register" extends="struts-default">
<action name="register" class="reg">
<result name="input">/WEB-INF/view/register.jsp</result>
<result name="success">/WEB-INF/view/success.jsp</result>
<result name="error">/WEB-INF/view/fail.jsp</result>
</action>
</package>

</struts>

这里主要改了<action>标签里面的class,原先直接写class=类名,但是这里的话action实例要被spring创建,也就是说交给spring管理,所以要用到applicationContext.xml里面配置好的action才行。这一点很重要,因为如果不用spring的action实例,那么action就是通过构造方法创建的,这样的话,action里面的属性就是空,因为没写初始化(要用spring啊),所以这里必须改为使用spring创建的action实例,这样action里面的属性才会被赋值,否则报nullpointer,我就是遇到这个问题了,开始还以为spring没有注入,但是我在run on server时,它提示了很多关于注入的错误(比如setter没写),所以我觉得spring是注入了,最后才发现是这里的问题。

但是把这里改了以后,又报了一个新错​​Action class  not found - action - file​​,大致就是说,reg这个东西并不是类,事实上它也确实不是一个类啊,它是spring管理的一个实例,也就是说struts2不认识spring创建的这个实例,查了半天,才发先是缺少一个包所致,这个包是struts2-spring-plugin-2.0.11.2.jar,它就是负责struts2与spring来整合的,说白了就是让spring来管理struts2的action实例,让struts2识别spring的action实例。到此,spring方面的解决了。

最后还得把spring配置加入到项目中,要修改web.xml为:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<!-- 配置struts2为项目的controller -->
<filter>
<filter-name>SSH</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>SSH</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>

添加一个listerner即可。



当然其他的类也需要修改,大致的内容就是把原来写new实例化的地方去掉,然后为这个private属性添加getter 和setter方法。

删掉之前的HibernateSessionFactory 类,我们用spring来管理sessionFactory,需要调用session的地方就用下面的方式:

Session session = sessionFactory.openSession();   
session.save(obj);

这是不使用事务的方式,如果要使用事务的话,要先从session得到事务,再save,再提交事务。

总之hibernate的数据操作流程就是先得到factory,这个又spring提供,然后由factory得到session,session才是操作数据的对象。

还要删掉hibernate.cfg.xml。

下面贴出其他的类的最终实现:

UserDao:

package com.edu.nju.firstSSH.UserDao;


public interface UserDao {

public void save(Object o);

}

UserDaoImp:

package com.edu.nju.firstSSH.UserDao;  

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class UserDaoImp implements UserDao {

private SessionFactory sessionFactory;
@Override
public void save(Object obj) throws HibernateException {
Session session = sessionFactory.openSession();
//开始事务;
Transaction tr = session.beginTransaction();
//存储 ;
session.save(obj);
//提交事务 ;
tr.commit();
session.close();
sessionFactory.close();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

}

UserService:


package com.edu.nju.firstSSH.Service;

import com.edu.nju.firstSSH.FormBean.UserForm;

public interface UserService {

public void register(UserForm userForm);
}

UserServiceImp:

package com.edu.nju.firstSSH.Service;


import com.edu.nju.firstSSH.Bean.User;
import com.edu.nju.firstSSH.FormBean.UserForm;
import com.edu.nju.firstSSH.UserDao.UserDao;

public class UserServiceImp implements UserService{

private UserDao userDao;

@Override
public void register(UserForm userForm) {

//userDao.setSession(session);
// 构造User对象
User user = new User();
user.setName(userForm.getUsername());
user.setPassword(userForm.getPassword());
user.setGender(userForm.getGender());
// 保存User对象
userDao.save(user);

}

public UserDao getUserDao() {
return userDao;
}

public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}

}

UserForm:

package com.edu.nju.firstSSH.FormBean;

public class UserForm {

private String username;
private String password;
private int gender;

public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}


}

User:

package com.edu.nju.firstSSH.Bean;

public class User {

private String name;
private String password;
private int gender;
private int userid;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}

public int getUserid() {
return userid;
}

public void setUserid(int userid) {
this.userid = userid;
}
}

User.hbm.xml不变

RegisterAction:

package com.edu.nju.firstSSH.Action;

import com.edu.nju.firstSSH.FormBean.UserForm;
import com.edu.nju.firstSSH.Service.UserService;
import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport{

/**
*
*/
private static final long serialVersionUID = 1L;
private UserForm userform;
private UserService userService;

public String execute(){
//userService = new UserServiceImp();
userService.register(userform);

return "success";
}

public UserForm getUserform() {
return userform;
}

public void setUserform(UserForm userform) {
this.userform = userform;
}

public UserService getUserService() {
return userService;
}

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

}

项目目录结构:

SSH 环境搭建(Spring3+Struts2+Hibernate3)_xml_04



访问:

SSH 环境搭建(Spring3+Struts2+Hibernate3)_struts_05




搭建成功!

最后附上项目源码:

​http://pan.baidu.com/s/1pKrBv43​



标签:Hibernate3,void,firstSSH,Struts2,session,SSH,edu,com,public
From: https://blog.51cto.com/u_15873544/5928271

相关文章

  • 安装Ubuntu18.04并配置ssh服务
    安装Ubuntu18.04并配置ssh服务打开终端界面切换到root用户提示:输入密码是隐藏的,并不会显示,实际是输入了的运行以下代码切换到root:sudosu一.解决Ubuntu终端无法......
  • SSH协商过程-简版
    1.二进制协议格式每个数据包为以下格式uint32packet_lengthbytepadding_lengthbyte[n1]payload;n1=packet_length-padding_length-1byte[n2]r......
  • 记录一次debug网络延迟问题--解决使用SSH工具连接远程主机,命令行卡顿问题
        如题,最近在学习k8s,于是买了两个比较便宜的云服务器搭建k8s集群,然后使用的过程中连接服务器发现敲命令的时候总是一卡一卡的,不能忍受,开始以为是服务器到家里网......
  • MAC之Git的SSH配置
    一,查询是否有.ssh目录cd~/.ssh(进入.ssh目录)无法进入,则表明没有生成SSH二,生成SSH1,设置用户名和邮箱$gitconfig--globaluser.name"YourName"$gitconfig--glo......
  • 使用 SSH 连接 Git 服务器
    关于SSHSSH(SecureShell)是一种安全的远程登录协议,可以让你通过安全的加密连接进行远程登录。目前,Mac、Windows10、Linux系统均有内置OpenSSH客户端。如果你想通......
  • 树莓派SSH连接问题
    1.使用默认账号和密码连不上提示Permissiondenied错误。修改默认用户名密码sudorename-user用新的用户名密码登录 2.在使用SSH远程连接时会出现乱码 sudovi/......
  • HCL虚拟环境搭建并且支持ssh远程访问
    1.连接设备新建设备和host主机,连线,host主机选择本地网卡(不选host-only网卡)2.启动设备,打开终端,按ctrl+c3.执行命令<H3C>system-view[H3C]intg0/0[H3C-GigabitEthe......
  • Ubuntu——基于cpolar配置内网穿透,外网随时随地实现SSH访问主机!
    发现了一个超好的免费内网穿透工具!!可以实现外网SSH访问主机,极大地提升工作效率,并解除工作空间的限制!1.安装cpolarUbuntu用户安装Cpolar内网穿透安装完成后,需要进行认......
  • 附带ssh的alpine镜像
    附带ssh的alpine镜像#指定创建的基础镜像FROMalpine:3#作者描述信息MAINTAINERalpine_sshd_service#替换阿里源,安装openssh,并修改配置文件和生成key,并且同步时......
  • struts2中OGNL中访问静态方法
     在struts2中,有时需要使用ognl去访问静态方法,典型的例子是,在新闻发布系统中,如果标题大于某个字数,必须截断,于是可以这样做:首先写一个静态的方法,然后在页面中这样写: <s:prop......