程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> SSH案例--入門級,ssh案例--

SSH案例--入門級,ssh案例--

編輯:JAVA綜合教程

SSH案例--入門級,ssh案例--


1.項目功能展示

(1)注冊

  (2)修改地址與級別信息,點擊修改

   (3)再添加一位成員,進行刪除

點擊第二行的刪除

(4)登錄模塊測試

輸入數據庫中沒有的信息:

輸入數據庫中存在的信息:

  2. Web.xml

  Spring提供了ContextLoaderListener,該監聽器實現了ServletContextListener接口,他在Web應用程序啟動時被觸發。當他創建時會自動查找WEB-INF/下的applicationContext.xml,所以當只有一個配置文件且文件名為applicationContext.xml時,則只需要在web.xml文件中配置ContextLoaderListener監聽器即可.當有多個配置文件需要載入,則應該使用<context-param>元素指定配置文件的文件名,ContextLoaderListener加載時,會查找名為contextConfigLocation的初始化參數。當Web應用程序啟動時先讀取web.xml文件,然後創建spring容器,之後根據配置文件內容,裝配Bean實例。

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>ssh</display-name> <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> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app> View Code

3. 實體類與其映射文件

(1)Member.java

package com.entity; public class Member { private long id; private String name; private String password; private String address; private String email; private int level; public Member(){} public Member(String name,String password,String address,String email,int level){ this.name = name; this.password = password; this.address = address; this.email = email; this.level = level; } public long getId() { return id; } public void setId(long id) { this.id = id; } 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } } View Code

(2)Member.hbm.xml

<?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> <class name="com.entity.Member" table="MEMBER"> <id name="id" type="long"> <column name="ID" /> <generator class="identity" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" /> </property> <property name="address" type="java.lang.String"> <column name="ADDRESS" /> </property> <property name="email" type="java.lang.String"> <column name="EMAIL" /> </property> <property name="level" type="int"> <column name="LEVEL" /> </property> </class> </hibernate-mapping> View Code

4.DAO層

(1)接口MemberDAO.java

package com.dao; import java.util.List; import com.entity.Member; public interface MemberDAO { public void add(Member member); public void update(Member member); public void delete(long id); public Member findByName(String name,String password); public Member findById(long id); public List<Member> findAll(); } View Code

(2)實現類MemberDAOImpl.java(sessionFactory通過構造方法注入,使其可以操作數據庫)

package com.dao; import java.util.List; import com.entity.Member; import org.hibernate.*; import org.springframework.beans.factory.annotation.Autowired; public class MemberDAOImpl implements MemberDAO { private SessionFactory sessionFactory; //構造方法注入SessionFactory對象 public MemberDAOImpl(SessionFactory sessionFactory) { this.sessionFactory=sessionFactory; } //使用SessionFactory對象返回Session對象 public Session currentSession(){ return sessionFactory.openSession(); } @Override public void add(Member member) { Session session=null; try { session=currentSession(); Transaction tx = session.beginTransaction(); session.save(member); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); }finally{ session.close(); } } @Override public void update(Member member) { Session session=null; try { session=currentSession(); Transaction tx = session.beginTransaction(); session.update(member); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); }finally{ session.close(); } } @Override public void delete(long id) { Session session=null; try { session=currentSession(); Transaction tx = session.beginTransaction(); Member mb = (Member)session.get(Member.class, id); session.delete(mb); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); }finally{ session.close(); } } @Override public Member findByName(String name, String password) { Session session=null; Member result = null; try { session=currentSession(); Transaction tx = session.beginTransaction(); String hsql = " from Member m where m.name = :mname and m.password = :mpassword"; Query query = session.createQuery(hsql); query.setParameter("mname", name); query.setParameter("mpassword", password); result = (Member)query.uniqueResult(); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); }finally{ session.close(); } return result; } @Override public Member findById(long id) { Session session=null; Member result = null; try { session=currentSession(); Transaction tx = session.beginTransaction(); String hsql = " from Member m where m.id = :id"; Query query = session.createQuery(hsql); query.setParameter("id",id); result = (Member)query.uniqueResult(); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); }finally{ session.close(); } return result; } @Override public List<Member> findAll() { Session session=null; List<Member> list = null; try { session=currentSession(); Transaction tx = session.beginTransaction(); String hsql = " from Member"; Query query = session.createQuery(hsql); list = query.list(); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); }finally{ session.close(); } return list; } } View Code

5.業務邏輯層

(1)接口MemberService.java

package com.service; import java.util.List; import com.entity.Member; public interface MemberService { public void add(Member member); public void update(Member member); public void delete(long id); public Member findByName(String name,String password); public Member findById(long id); public List<Member> findAll(); } View Code

(2)實現類MemberServiceImpl.java(設值注入DAO層組件)

package com.service; import java.util.List; import com.dao.MemberDAO; import com.entity.Member; public class MemberServiceImpl implements MemberService { private MemberDAO memberDao; //設值注入DAO對象 public void setMemberDao(MemberDAO memberDao) { this.memberDao = memberDao; } @Override public void add(Member member) { if(memberDao.findById(member.getId())==null) memberDao.add(member); } @Override public void update(Member member) { if(memberDao.findById(member.getId())!=null) memberDao.update(member); } @Override public void delete(long id) { if(memberDao.findById(id)!=null) memberDao.delete(id); } @Override public Member findByName(String name, String password) { return memberDao.findByName(name, password); } @Override public Member findById(long id) { return memberDao.findById(id); } @Override public List<Member> findAll() { return memberDao.findAll(); } } View Code

6. Action類

(1)注冊MemberRegisterAction.java(設值注入業務邏輯組件)

package com.action; import com.entity.Member; import com.opensymphony.xwork2.ActionSupport; import com.service.MemberService; public class MemberRegisterAction extends ActionSupport { private Member member; private MemberService memberService; public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } //注入業務邏輯組件 public void setMemberService(MemberService memberService) { this.memberService = memberService; } public String execute(){ memberService.add(member); return SUCCESS; } } View Code

(2)刪除MemberDeleteAction.java(設置注入業務邏輯組件,注意傳入參數id的相應getter和setter方法)

package com.action; import com.opensymphony.xwork2.ActionSupport; import com.service.MemberService; public class MemberDeleteAction extends ActionSupport { private MemberService memberService; public void setMemberService(MemberService memberService) { this.memberService = memberService; } private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } public String execute(){ memberService.delete(getId()); return SUCCESS; } } View Code

(3)查詢MemberQueryAction.java(用於查看所有會員信息)

package com.action; import java.util.List; import org.apache.struts2.ServletActionContext; import com.entity.Member; import com.opensymphony.xwork2.ActionSupport; import com.service.MemberService; public class MemberQueryAction extends ActionSupport { private MemberService memberService; public void setMemberService(MemberService memberService) { this.memberService = memberService; } public String execute(){ List<Member> list = memberService.findAll(); ServletActionContext.getRequest().setAttribute("memberList", list); return SUCCESS; } } View Code

(4)修改MemberUpdateAction.java(有兩個方法,execute()和showMember(),當需要修改時,showMember()方法轉向update.jsp.並設置好需要修改的對象,修改完成之後,由spring托管的memberUpdateAction組件執行execute方法進行update操作)

package com.action; import com.entity.Member; import com.opensymphony.xwork2.ActionSupport; import com.service.MemberService; public class MemberUpdateAction extends ActionSupport { private MemberService memberService; private Member member; private long id; public void setMemberService(MemberService memberService) { this.memberService = memberService; } public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String showMember(){ Member mb = memberService.findById(getId()); setMember(mb); return SUCCESS; } public String execute(){ memberService.update(member); return SUCCESS; } } View Code

(5)登錄MemberLoginAction.java(將輸入的信息與數據庫中進行比較)

package com.action; import com.entity.Member; import com.opensymphony.xwork2.ActionSupport; import com.service.MemberService; public class MemberLoginAction extends ActionSupport { private Member member; private MemberService memberService; public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } //注入業務邏輯組件 public void setMemberService(MemberService memberService) { this.memberService = memberService; } public String execute(){ Member mb =memberService.findByName(member.getName(), member.getPassword()); if(mb!=null) return SUCCESS; else return ERROR; } } View Code

7.struts.xml

  spring托管將Struts2中的Action的實例化工作交由Spring容器統一管理,同時使Struts2中的Action實例能夠訪問Spring提供的業務邏輯資源,spring容器依賴注入的優勢也可以體現,Struts2提供的spring插件struts2-spring-plugin-2.3.16.3.jar配合<constant name="struts.objectFactory" value="spring">使得Struts2的action由Spring來負責進行實例化.

<?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"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.objectFactory" value="spring"></constant> <package name="default" namespace="/" extends="struts-default"> <!-- class屬性值是spring定義的Bean,當執行execute()返回success時,控制轉到另一個動作memberQuery --> <action name="memberRegister" class="memberRegisterAction"> <result name="success" type="redirectAction">/memberQuery</result> </action> <action name="memberLogin" class="memberLoginAction"> <result name="success">/welcome.jsp</result> <result name="error">/register.jsp</result> </action> <action name="memberQuery" class="memberQueryAction"> <result name="success">/displayAll.jsp</result> </action> <action name="memberDelete" class="memberDeleteAction"> <result name="success" type="redirectAction">/memberQuery</result> </action> <action name="memberShow" class="memberUpdateAction" method="showMember"> <result name="success">/update.jsp</result> </action> <action name="memberUpdate" class="memberUpdateAction"> <result name="success" type="redirectAction">/memberQuery</result> </action> </package> </struts> View Code

8.applicationContext.xml

  spring 框架提供了多種數據源類,可以使用spring提供的DriverManagerDataSource類還可以使用第三方數據源,如C3P0的ComboPooledDataSource數據源類,注意相應的兩個jar包c3p0-0.9.2.1.jar mchange-commons-java-0.2.3.4.jar.

  Hibernate4已經完全實現自己的事物管理,所以spring4不提供HibernateDaoSupport和HibernateTemplete的支持。可以在應用程序的spring上下文中,像配置其他bean那樣來配置HibernateSession工廠。如果要使用XML文件定義對象與數據庫之間的映射,則需要在spring中配置LocalSessionFactoryBean。hibernateProperties屬性配置了Hibernate如何進行操作的細節。"hibernate.current_session_context_class"是為當前Session提供一個策略,Session由org.springframework.orm.hibernate4.SpringSessionContext.currentSession得到。將sessionFactory注入到其他Bean中,如注入到DAO組件中,使其獲得SessionFactory的引用後,就可以實現對數據庫的訪問。

<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/zzh?useUnicode=true&amp;characterEncoding=UTF-8"/> <property name="user" value="root"/> <property name="password" value="root"/> <property name="maxPoolSize" value="40"/> <property name="minPoolSize" value="1"/> <property name="initialPoolSize" value="2"/> <property name="maxIdleTime" value="20"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingResources"> <list> <value>com/entity/Member.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop> <prop key="hibernate.current_session_context_class"> org.springframework.orm.hibernate4.SpringSessionContext </prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> </props> </property> </bean> <bean id="memberDao" class="com.dao.MemberDAOImpl"> <!-- 構造方法注入會話工廠組件sessionFactory --> <constructor-arg> <ref bean="sessionFactory"/> </constructor-arg> </bean> <bean id="memberService" class="com.service.MemberServiceImpl"> <!-- 設值注入DAO組件 --> <property name="memberDao" ref="memberDao"></property> </bean> <bean id="memberRegisterAction" class="com.action.MemberRegisterAction"> <!-- 設值注入業務邏輯組件 --> <property name="memberService" ref="memberService"></property> </bean> <bean id="memberLoginAction" class="com.action.MemberLoginAction"> <property name="memberService" ref="memberService"></property> </bean> <bean id="memberQueryAction" class="com.action.MemberQueryAction"> <property name="memberService" ref="memberService"></property> </bean> <bean id="memberDeleteAction" class="com.action.MemberDeleteAction"> <property name="memberService" ref="memberService"></property> </bean> <bean id="memberUpdateAction" class="com.action.MemberUpdateAction"> <property name="memberService" ref="memberService"></property> </bean> </beans> View Code

9.jsp

(1)注冊register.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>會員注冊頁面</title> </head> <body> <s:form action="memberRegister" method="post"> <h4><s:text name="歡迎注冊會員"></s:text></h4> <s:property value="exception.message"/> <s:textfield name="member.name" label="會員姓名" tooltip="Enter your name!" required="true"></s:textfield> <s:password name="member.password" label="會員口令" tooltip="Enter your password!"></s:password> <s:textfield name="member.address" label="會員地址"></s:textfield> <s:textfield name="member.email" label="會員郵箱"></s:textfield> <s:textfield name="member.level" label="會員級別"></s:textfield> <s:submit value="提交"/> </s:form> </body> </html> View Code

(2)所有會員信息displayAll.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>顯示會員信息</title> </head> <body> <h4>會員信息</h4> <table border='1'> <tr> <td>會員id</td><td>會員名</td><td>密碼</td><td>地址</td><td>郵箱</td><td>級別</td><td>刪除</td><td>修改</td> </tr> <s:iterator value="#request.memberList" id="mb"> <tr> <td><s:property value="#mb.id"/></td> <td><s:property value="#mb.name"/></td> <td><s:property value="#mb.password"/></td> <td><s:property value="#mb.address"/></td> <td><s:property value="#mb.email"/></td> <td><s:property value="#mb.level"/></td> <td> <a href="<s:url action="memberDelete"><s:param name="id"><s:property value="#mb.id"/></s:param> </s:url>">刪除</a> </td> <td> <a href="<s:url action="memberShow"><s:param name="id"><s:property value="#mb.id"/></s:param> </s:url>">修改</a> </td> </tr> </s:iterator> </table> <a href="register.jsp">返回注冊頁面</a> </body> </html> View Code

(3)修改頁面update.jsp

  注意:不允許修改會員id,當需要將會員id傳遞給更新會員動作,所以使用隱藏表單域標簽來接收顯示會員頁面傳遞來的會員id在update.jsp頁面提交時再傳遞給更新會員的動作memberUpdate。

<%@ 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>修改會員信息</title> </head> <body> <s:form action="memberUpdate" method="post"> <h4><s:text name="修改會員信息"></s:text></h4> <s:actionerror/> <s:hidden name="member.id" value="%{member.id}"></s:hidden> <s:textfield name="member.name" label="會員姓名" required="true"></s:textfield> <s:textfield name="member.password" label="會員口令"></s:textfield> <s:textfield name="member.address" label="會員地址"></s:textfield> <s:textfield name="member.email" label="會員郵箱"></s:textfield> <s:textfield name="member.level" label="會員級別"></s:textfield> <s:submit value="提交"/> </s:form> </body> </html> View Code

(4)登錄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>會員登錄</title> </head> <body> <s:form action="memberLogin" method="post"> <s:textfield name="member.name" label="會員姓名"></s:textfield> <s:password name="member.password" label="會員口令"></s:password> <s:submit value="提交"></s:submit> </s:form> </body> </html> View Code

(5)welcome.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>貴賓你好!</title> </head> <body> 合法成員 </body> </html> View Code

 

10. END

  本篇案例算是最簡單的ssh整合,注入形式也都一目了然,如果對你有幫助,請點贊或關注我,謝謝觀看!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved