s2sh整合

最近的struts2-hibernate -spring整合开发

1.简单讲解spring和struts2整合

首先导入struts的jar,hibernate的jar,spring的jar,数据库的驱动包XX.jar放入lib包中。

接下来编写实体类
User.java
package com.s2sh.mobel;

import java.io.Serializable;

public class User implements Serializable{

	private static final long serialVersionUID = -2974230401163436730L;
	private Integer id;
	private String name;
	private String password;
	private String firstname;
	private String lastname;
	private Integer age;
	
	private User(){}
	
	private User(Integer id , String firstname , String lastname , Integer age,String name,String password){
		this.id = id;
		this.firstname = firstname;
		this.lastname = lastname;
		this.age = age;
		this.name=name;
		this.password=password;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

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

	public String getName() {
		return name;
	}
}




将User.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>
	<class name="com.s2sh.mobel.User" table="users">
		<id name="id" column="id" type="integer">
			<generator class="native"></generator>
		</id>
        <property name="name" column="name" type="string"/>
		<property name="password" column="password" type="string"/>
		<property name="firstname" column="firstname" type="string" not-null="false"/>
		<property name="lastname" column="lastname" type="string" not-null="false"/>
		<property name="age" column="age" type="integer" not-null="false"/>	
	</class>
</hibernate-mapping>     


提供hibernate配置文件
hibernate.cfg.xml

<?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>
    
    </session-factory>

</hibernate-configuration>



在spring中,本身没有提供ORM的实现,但是提供了一些帮助类他们会提供ORM工具的支持,例如Hibernate、Ojdbc、iBatis等。


<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 数据源配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName">
		<value>com.mysql.jdbc.Driver</value>
	</property>
	<property name="url">
		<value>jdbc:mysql://localhost:3306/s2sh</value>
	</property>
	<property name="username">
		<value>root</value>
	</property>
	<property name="password">
		<value>wj</value>
	</property>
</bean>


注意:bean的id 可以随便写,sessionfactory依赖数据源,所以要注射进来bean id=“”,接下来<property name="driverClassName">要设置成数据源,

工厂:
<!-- sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<property name="dataSource">
		<ref local="dataSource"/>
	</property>
	
	<property name="mappingResources">
		<list>
			<value>com/s2sh/mobel/User.hbm.xml</value>
		</list>
	</property>
	<property name="hibernateProperties">
		<props>
			<prop key="hibernate.dialect">
				org.hibernate.dialect.MySQLDialect
			</prop>
			<prop key="hibernate.show_sql">
				true
			</prop>
		</props>
	</property>
</bean>



还有一个,mvc三层架构,dao实现类注入,Servce业务逻辑注入,action注入
<!--实现层  -->
<bean id="userDao" class="com.s2sh.dao.impl.UserDaoImpl" scope="singleton">
	<property name="sessionFactory">
		<ref bean="sessionFactory"/>
	</property>
</bean>
<!--service层 -->
<bean id="userService" class="com.s2sh.service.impl.UserServiceImpl">
	<property name="userDao" ref="userDao"/>
</bean>
<!-- action -->
<bean id="saveUserAction" class="com.s2sh.action.user.UserAction" scope="prototype">
	<property name="userService" ref="userService" />
</bean>


简单的用户登录填写:

<!-- login -->
<bean id="loginUserAction" class="com.s2sh.action.user.UserAction" scope="prototype">
	<property name="userService" ref="userService" />
</bean>

注意,url请求找web.xml,通过拦截器和监听器进行操作,然后寻找struts.xml,然后struts class=“”会告诉继续找spring,spring的class=“”,会告诉具体找那个struts的action类,找到之后 获取rquest 参数,然后调用业务逻辑,把记过放进作用于,返回。在这里,我采用action注入servce,action注入user对象,servce类中注入dao,dao类中注入hibernateTemplate。


2.可以使用spring中的HibernateDaoSupport和HibernateTemplate类简化HibernateDao的实现类的编写。

public void delete(User id){
//获得hibernate事务
 template =getHiberanteTemplate();
//获得对象
user =(User)template.get(User.class,id);
//spring事务会进行操作删除对象
template.delete(user);
}



注意:因为dao继承HibernateDaoSupper 所以要重写delete(),然后获取hibernateTemplate,HibernateTemplate封装了session的操作,user =(User)template.get(User.class,id);查找User对象,查找后在通过template在把这个对象删除掉。现在不用管session,因为我们用到spring,我们注射进来了,所以session关闭交给spring。


3.修改web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">

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


注意:url请求过来首先找web.xml,通过过滤器进行拦截,找对应的action。

4.接着编写web.xml

<!--监听器-->
</filter-mapping>
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>


注意:监听器是spring,其实就是struts不管事务了,交给spring进行管理,对象交给spring进行管理。


5.web.xml架构
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
<!--过滤器-->
<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>
<!--监听器-->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>



编写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>
<package name="s2sh"  namespace="/" extends="struts-default" >

<!-- login 用户登录-->
		<action name="loginUser" class="loginUserAction" method="login">
		<result name="success">/list.jsp</result>
		<result name="error">/error.jsp</result>
		</action>
</struts>




注意name可以随便写,真正的寻找action类交给了spring,所以class=“”是spring的id=“”。他会继续到spring中找。

applicationContext.xml
<bean id="loginUserAction" class="com.s2sh.action.user.UserAction" scope="prototype">
	<property name="userService" ref="userService" />
</bean>


注意:spring的id一定是struts的class =“”,然后spring的class=“”会告诉这个action类在哪里?jurisdiction 另外<property name="userService" ref="userService" />说名action要调业务逻辑,所以要注入业务逻辑类。

action编写:
package com.s2sh.action.user;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.s2sh.mobel.User;
import com.s2sh.service.UserService;

public class UserAction extends ActionSupport {

	private static final long serialVersionUID = -7467352669343037994L;
	
	private User user;
	private UserService userService;
	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public UserService getUserService() {
		return userService;
	}
	private String name;
	private String password;
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}
	public void setUser(User user) {
		this.user = user;
	}
public String login()throws Exception{
		System.out.println(user.getName());
	if(null!=this.userService.findUser(user)){
			return SUCCESS;
		}else {
			return ERROR;
		}
		   
	}



dao接口编写

package com.s2sh.dao;

import java.util.List;

import com.s2sh.mobel.User;

public interface UserDao {
//根据用户用户来登录,不过你可以根据自己需求来写
	public User findUser(User user);
}


dao接口实现类

package com.s2sh.dao.impl;

import java.util.List;

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

import com.s2sh.dao.UserDao;
import com.s2sh.mobel.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao{
//用户登录
		public User findUser(User user) {
			try{
			String hql="from User where name=? and password=?";
			List list = (List) this.getHibernateTemplate().find(hql,new String[]{user.getName(),user.getPassword()});
			if(list.size()>=1){
				return (User)list.get(0);
			}else {
				return null;
			}
			}catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
}

编写servce接口

package com.s2sh.service;

import java.util.List;

import com.s2sh.mobel.User;

public interface UserService {
          //根据user登录
	public User findUser(User user);
}


编写servce实现类

package com.s2sh.service.impl;

import java.util.List;

import com.s2sh.dao.UserDao;
import com.s2sh.mobel.User;
import com.s2sh.service.UserService;

public class UserServiceImpl implements UserService{

	private UserDao userDao;
	//注入
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	//用户登录
	public User findUser(User user){
		return (User)this.userDao.findUser(user);
	}
}



编写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>
<%@ taglib uri="/struts-tags" prefix="s" %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用户登录</title>
</head>

<script type=text/javascript></script>
<script>
function longin(){
  var name = document.getElementById("UserName").value;
  var password = document.getElementById("UserPassword").value;
  if(name.length==""){
  alert("用户名不能为空");
  return false;
  }else if(password.length<6){
  alert("密码长度不能小于6位");
  return false;
  }else if(password.length>6){
  alert("密码长度不能大于6位");
  }
  return login.submit();
}
</script>

<body>
 <!-- 
    <s:form action="loginUser" method="post">
        <s:textfield name="user.name" label="name" id="username"></s:textfield>
        <s:textfield name="user.password" label="password" id="UserPassword"></s:textfield>
    	<s:submit value="登录"/>	
    </s:form>
          -->
      
     <form action="loginUser" name="login" method="post">
    用户名: <input type="text"  name="user.name" id="UserName"/>
     <br/>
   密码:&nbsp;&nbsp;<input type="password" name="user.password" id="UserPassword"/>
     <br/>
     <input type="button" value="登录" onclick="longin()"/>
     </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>
<%@ taglib uri="/struts-tags" prefix="s" %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
     ------------------>程序失败<--------------------------------
</body>
</html>

注意:如果有什么需要帮助的可以加我QQ503229799 备注:s2sh寻求帮助,我会同意添加好友,另外我有QQ开发群,看我的首页,在群里喊我也行!这只是简单的登录,如果想要整个模块的增删改查的代码,请在本片评价上留言!我会给你们整合一个完整的代码,包括jar包上传····数据库设计····另外加注释·····

接下来咱们开始演示吧~~~~

url输入地址:http://localhost:8088/s2sh/login.jsp

你可能感兴趣的:(spring,Hibernate,struts s2sh全新整合)