SSH三大框架的搭建整合(Spring+Hibernate+Struts2)实现增删改查登录

版权声明:西安钰泉私人知识产权,仅供学习交流使用! https://blog.csdn.net/YuQuanZhang/article/details/81326637

SSH说的上是javaweb经典框架,不能说100%要会SSH框架,但是大部分公司都在用,说到框架,都会提到ssh吧,这次就以很简单的注册例子来整合SSH框架。整合框架要注意的是先每个框架单独测通后再整合,不然整合后出现问题比较难排查。 

准备工作:

在做一切之前先将可能使用到的SSHjar包进行导入,不一定为最简,但一定够用:

对于SSH整合,共使用到applicationContext.xml,web.xml,struts.xml,Person.bhm.xml四个配置文件,创建位置在下面详述。


applicationContext.xml文件配置参数: 

  1. <bean id=""  class="" ></bean>
  2. parent:子类实现父类
  3. scope:Spring中Bean的作用域一共有几个值?
  4. 默认单例,protoType为原型,可以创建多个Bean
  5. request session生命周期类型
  6. name:设置名称
  7. <property name="teachingService" ref="theService"></property>
  8. ref:引用
  9. value:相应的值

配置Hibernate框架内容:

applicationContext.xml:

位置  放在src下

1.BasicDataSource中连接数据库的各种参数property,其中有很多参数以供选择

2.SessionFacotry创建session对象的Bean

其中需要引用到DataSource,用设值注入,使用LoaclSessionFactory方法的父类AbstractSessionFactoryBean中的dataSource方法,将属性写入Bean,ref:引用数据库的dataSource。此时获得到sessionFactory。

还需要导入Hibernate配置文件中的show_sql的内容:Hibernate.Properties文件中的show_sql字段。和线程绑定模式的应用。

用法:

  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
   <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
   <property name="username" value="system"></property>
   <property name="password" value="Yuquan980730"></property>
  </bean>
  <!-- 获取session对象 -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="hibernateProperties">
  <props>
  <prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
  </props>
  </property>
  <property name="mappingResources">
  		<list>
  			<value>com/ssh/entity/Person.hbm.xml</value>
  			      
  		</list>
  	</property>
  </bean>

3.创建实体类Person,添加属性构造和getter、setter方法

hbm映射文件:

位置hibernate jar包中

放在实体类的class下。

4.配置hbm文件,配置完成后将目录导入applicationContext.xml文件中value属性中。

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

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

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

<hibernate-mapping package="org.hibernate.subclassProxyInterface">

    <class name="Person">

       <id name="id" type="int">

           <generator class="sequence">

               <param name="sequence">seq_newsId</param>

           </generator>

       </id>

       <propety name="pname" type="string" />

       <propety name="pwd" type="string" />

    </class>

</hibernate-mapping>

5.创建Dao层接口,PersonDao为Person实体的dao。每一个实体使用时都需要dao,因为有特有的方法。不建议建立泛型Dao。

package com.ssh.Dao;

import java.util.List;

import com.ssh.entity.Person;

public interface PersonDao {

     public boolean login(Person person);

     public boolean add(Person person);

     public boolean update(Person person);

     public boolean delete(int pid);

     public Person queryById(int pid);

     public List<Person> queryAll();

}

 添加实现类Impl,在实现类中传入一个session对象,此时的sessionFactory需要从配置文件中注入才可以使用,注意此处不能注入接口,都需要注入实现类。

public class PersonDaoImpl implements PersonDao{

     private SessionFactory sessionFactory;

     boolean flag=false;

     public void setSessionFactory(SessionFactory sessionFactory) {

          this.sessionFactory = sessionFactory;

     }

     @Override

     public boolean login(Person person) {

          String hql = "from Person where pname=? and pwd=?";

          Session session = sessionFactory.openSession();

          Query q = session.createQuery(hql);

          q.setString(0, person.getPname());

          q.setString(1, person.getPwd());

          Object obj = q.uniqueResult();

          if (obj != null) {

              flag = true;

          }

          session.close();

          return flag;

     }

}

6.添加服务层。PersonService接口和PersonSercviceImpl实现类。

package com.ssh.Dao.Impl;

import java.util.List;

import com.ssh.Dao.PersonDao;

import com.ssh.Dao.PersonService;

import com.ssh.entity.Person;

public class PersonServiceImpl implements PersonService{

     private PersonDao ServiceDao;

     

     public void setServiceDao(PersonDao serviceDao) {

          ServiceDao = serviceDao;

     }

     @Override

     public boolean login(Person person) {

          

          return ServiceDao.login(person);

     }

     @Override

     public boolean add(Person person) {

          // TODO Auto-generated method stub

          return ServiceDao.add(person);

     }

     @Override

     public boolean update(Person person) {

          // TODO Auto-generated method stub

          return ServiceDao.update(person);

     }

     @Override

     public boolean delete(int pid) {

          // TODO Auto-generated method stub

          return ServiceDao.delete(pid);

     }

     @Override

     public Person queryById(int pid) {

          // TODO Auto-generated method stub

          return ServiceDao.queryById(pid);

     }

     @Override

     public List<Person> queryAll() {

          // TODO Auto-generated method stub

          return ServiceDao.queryAll();

     }

}

测试类Test:

Person person =new Person(0,"tom","123");

ApplicationContext ac=new ClasspathxmlContext("applicationContext.xml");

PersonService personService=(PersonService)ac.getBean("personSecivce");

boolean falg=personservice.login(person);

此时出现空指针,需要将两个实现类中的Bean注入到配置文件中,实现类引用sessionFactory。

<!--  PersonDaoimpl实现类注入 -->
 <bean id="personDao" class="com.ssh.Dao.Impl.PersonDaoImpl">
  	<property name="sessionFactory" ref="sessionFactory"></property>
  </bean>
  <bean id="personService" class="com.ssh.Dao.Impl.PersonServiceImpl">
  	<property name="personDao" ref="personDao"></property>
  </bean>

添加Hibernate时遇到的问题:

1.注入Impl实现类时,使用到的setter注入,其中id必须和创建的sessionFactory以及setPersonDao的参数名称相同,id sessionFactory与

public void setSessionFactory(SessionFactory sessionFactory) {

          this.sessionFactory = sessionFactory;

     }

名称相同,id personDao和

public void setPersonDao(PersonDao personDao) {

          this.personDao = personDao;

     }

名称相同。

2.实体类中Person构造方法没写。

修改后编译成功,命令行成功显示flag登录的boolean值。


配置Struts2框架内容:

1.导入jar包

2.strut2和web配置文件:

web.xml:

加入file标签  

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

struts.xml:

修改常量

编写action标签获取result两种结果。

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

<!DOCTYPE struts PUBLIC

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

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

<!-- xml两种验证文件 -->

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />

     <!-- 常量 -->

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

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

    <default-action-ref name="index" />

    <global-results>

            <result name="error">/WEB-INF/jsp/error.jsp</result>

        </global-results>

        <global-exception-mappings>

            <exception-mapping exception="java.lang.Exception" result="error"/>

        </global-exception-mappings>

 

    <action name="personAction" class="com.ssh.Action.PersonAction">

    <result>show.jsp</result>

    <result name="input"  type="redirect">login.jsp</result>

    </action>

   

    </package>

</struts>

3.编写jsp登录测试页面

login.jsp和show.jsp:

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

</head>

<body>

    <s:form action="personAction!login" method="post">

    <s:textfield name="pname" label="姓名"></s:textfield>

    <s:password  name="password" label="密码"></s:password>

    

    

    <tr>

       <td colspan="2">

           <s:submit value="提交" theme="simple"></s:submit>

           <s:reset value="重置"  theme="simple"></s:reset>

       </td>

    </tr>

    </s:form>

</body>

</html>



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

</head>

<body>

    <table>

       <tr>

           <th>编号</th>

           <th>姓名</th>

           <th>密码</th>

       </tr>

           <s:iterator value="list">

               <tr>

                  <td>

                  <s:property  value="pid"/>

                  </td>

                  <td>

                  <s:property  value="pname"/>

                  </td>

                  <td>

                  <s:property  value="pwd"/>

                  </td>      

               </tr>

           </s:iterator>

    </table>

</body>

</html>

4.创建Action类继承ActionSupport实现ModelDriven<Person>

使用MODEL第三种方式模型驱动创建实体类对象,编写login方法。

package com.ssh.Action;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.ssh.Dao.PersonService;

import com.ssh.entity.Person;

public class PersonAction extends ActionSupport implements ModelDriven<Person> {

    private Person person;

    private PersonService personService;

    private List<Person> list;

    public List<Person> getList() {

        return list;

    }

    public void setList(List<Person> list) {

        this.list = list;

    }

    public void setPersonService(PersonService personService) {

        this.personService = personService;

    }

    @Override

    public Person getModel() {

        // TODO Auto-generated method stub

        return person;

    }

    public String login() throws Exception {

        boolean flag = true;

        String path = INPUT;

        flag = personService.login(person);

        if (flag) {

            path = SUCCESS;

        }

        queryAll();

        return path;

    }

    public String queryAll() throws Exception {

        boolean flag = false;

        String path = INPUT;

        list = personService.queryAll();

        if (list != null) {

            path = SUCCESS;

        }

        return path;

    }

}

5.将PersonAction注入Spring配置文件中,,此处只能使用name属性,将从sessionFactory获取到的PersonDaoImpl的内容注入PersonAction。

<bean  name="personAction" class="com.ssh.Action.PersonAction">

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

  </bean>

web.xml:

在其中设置spring配置文件,将其在程序启动的同时就加载,使用Listener监听器。

<listener>

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

</listener>



<context-param>

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

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

</context-param>

 

程序到这里实现了登录以及查询所有数据。


注意:在person模型驱动的时候,必须进行实例化Person。不可只定义对象。

模型驱动的用法没搞清楚。

没有更多推荐了,返回首页