1.項目功能展示 (1)註冊 (2)修改地址與級別信息,點擊修改 (3)再添加一位成員,進行刪除 點擊第二行的刪除 (4)登錄模塊測試 輸入資料庫中沒有的信息: 輸入資料庫中存在的信息: 2. Web.xml Spring提供了ContextLoaderListener,該監聽器實現了Servlet ...
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&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> </