SSH三大框架的搭建整合(Spring+Hibernate+Struts2)實現增刪改查登入

小章魚啊發表於2018-08-01

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。不可只定義物件。

模型驅動的用法沒搞清楚。

相關文章