1. 新建一個Web項目,準備好jar包和配置文件。html
2. web.xml文件中添加過濾器java
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Test17</display-name> <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> <!-- 過濾器 --> <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>
3. Hibernate主配置文件web
<?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"> <hibernate-configuration> <session-factory> <!-- 數據庫鏈接 --> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.password">laoer123</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="hibernate.connection.username">test0816</property> <!-- 數據庫方案 --> <property name="hibernate.default_schema">TEST0816</property> <!-- 數據庫方言 --> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> <!-- 調試 --> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <!-- 自動建表方式 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 註冊映射文件 --> <mapping resource="com/hanqi/entity/User.hbm.xml"/> </session-factory> </hibernate-configuration>
4. Struts配置文件sql
<?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.action.extension" value="do,action,,"></constant> <!-- 啓用配置調用 --> <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <!-- 定義包 --> <package name="index" extends="struts-default"> <action name="addUser"> <result>/WEB-INF/pages/addUser.jsp</result> </action> <action name="addUser2"> <result>/WEB-INF/pages/addUser2.jsp</result> </action> <!-- 保存User --> <action name="saveUser" class="com.hanqi.action.UserAction" method="saveUser"> <result name="fail">/WEB-INF/pages/fail.jsp</result> <result>/WEB-INF/pages/success.jsp</result> </action> <!-- 查詢用戶 <action name="selectUser" class="com.hanqi.action.UserAction" method="selectUser"> <result name="fail">/WEB-INF/pages/fail.jsp</result> <result>/WEB-INF/pages/selectUser.jsp</result> </action> --> <!-- 通配符方式 --> <action name="*" class="com.hanqi.action.UserAction" method="{1}"> <result name="fail">/WEB-INF/pages/fail.jsp</result> <result>/WEB-INF/pages/{1}.jsp</result> </action> <!-- 刪除用戶 --> <action name="deleteUser" class="com.hanqi.action.UserAction" method="deleteUser"> <result name="fail">/WEB-INF/pages/fail.jsp</result> <result type="redirectAction">selectUser</result> </action> <!-- 查詢單條記錄 --> <action name="updateUser" class="com.hanqi.action.UserAction" method="selectd"> <result>/WEB-INF/pages/update.jsp</result> </action> <!-- 修改單個用戶記錄 --> <action name="EditUser" class="com.hanqi.action.UserAction" method="update"> <result name="fail">/WEB-INF/pages/fail.jsp</result> <result type="redirectAction">selectUser</result> </action> <!-- 驅動模型的數據保存 --> <action name="saveUser2" class="com.hanqi.action.UserAction2" method="saveUser"> <result name="fail">/WEB-INF/pages/fail.jsp</result> <result>/WEB-INF/pages/success.jsp</result> </action> </package> </struts>
5. 用Hibernate建立的持久化類以及映射文件數據庫
package com.hanqi.entity; import java.util.Date; //實體化類 //不要使用final修飾 public class User { private Integer userID; private String userName; private Date birthday; private Double money; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getUserID() { return userID; } public void setUserID(Integer userID) { this.userID = userID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } // 必須提供無參的構造方法 //須要用到反射 public User() { super(); } public User(Integer userID, String userName) { super(); this.userID = userID; this.userName = userName; } @Override public String toString() { return "User [userID=" + userID + ", userName=" + userName + ", birthday=" + birthday + ", money=" + money + ", password=" + password + "]"; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2016-11-7 14:40:01 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping> <class name="com.hanqi.entity.User" table="T_USER"> <id name="userID" type="int"> <column name="USER_ID" /> <generator class="native" /> </id> <property name="userName" type="java.lang.String"> <column name="USER_NAME" length="20" not-null="true" unique="true"/> </property> <property name="birthday" type="java.util.Date"> <column name="BIRTHDAY" sql-type="DATE"/> </property> <property name="money" type="java.lang.Double"> <column name="MONEY" sql-type="NUMBER" default="0" length="8" scale="2"/> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" length="10"></column> </property> </class> </hibernate-mapping>
6.DAO層apache
package com.hanqi.dao; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import com.hanqi.entity.User; public class UserDAO { private Configuration cfg =null; private ServiceRegistry sr =null; private SessionFactory sf = null; private Session se =null; private Transaction ts =null; public UserDAO() { //初始化Hibernate cfg = new Configuration().configure(); sr = new StandardServiceRegistryBuilder(). applySettings(cfg.getProperties()).build(); } // private void init() { sf= cfg.buildSessionFactory(sr); se = sf.openSession(); ts = se.beginTransaction(); } private void destory() { ts.commit(); se.close(); sf.close(); } //保存User public User insert(User user) { init(); se.save(user); destory(); return user; } //查詢列表 public List<User>getAll() { List<User> rtn = new ArrayList<>(); init(); rtn=se.createQuery("from User ") .list(); destory(); return rtn; } //刪除 public void delete(int userID) { init(); //獲取對象 User u=(User)se.get(User.class, userID); se.delete(u); destory(); } //查詢單個 public User selectUser(int userID) { init(); //獲取對象 User u = (User)se.get(User.class, userID); destory(); return u; } //修改 public User update(User user) { init(); // 獲取對象 // User u =(User)se.get(User.class,userID); // //修改數據 // u.setUserID(user.getUserID()); // u.setUserName(user.getUserName()); // u.setPassword(user.getPassword()); // u.setMoney(user.getMoney()); // u.setBirthday(user.getBirthday()); se.update(user); destory(); return user; } }
7. Service層session
package com.hanqi.service; import java.util.List; import com.hanqi.dao.UserDAO; import com.hanqi.entity.User; public class UserService { // 添加User的方法 public User add(User user) { return new UserDAO().insert(user); } //全表查詢 public List<User> getAll() { return new UserDAO().getAll(); } //刪除記錄 public void delete(int userID) { new UserDAO().delete(userID); } //查詢單個 public User select(int userID) { return new UserDAO().selectUser(userID); } //修改記錄 public User update(User user) { return new UserDAO().update(user); } }
8.Action類oracle
package com.hanqi.action; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.hanqi.entity.User; import com.hanqi.service.UserService; import com.opensymphony.xwork2.ActionContext; public class UserAction { //域模型方式 private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String insertUser() { return saveUser(); } //處理保存User的方法 public String saveUser() { String rtn ="fail"; System.out.println(user); try{ // 調用Service層(模型層,業務邏輯層) User u1=new UserService().add(user); //使用request轉發到下一個頁面 ActionContext ac = ActionContext.getContext(); Map<String,Object>mo=(Map<String,Object>)ac.get("request"); mo.put("user", u1); rtn="success"; } catch(Exception e) { e.printStackTrace(); } return rtn; } //查詢 public String selectUser() { String rtn ="fail"; try { //調用查詢的方法 List<User> lu = new UserService().getAll(); //獲得原生的request HttpServletRequest hsr=ServletActionContext.getRequest(); hsr.setAttribute("userlist", lu); rtn = "success"; } catch(Exception e) { e.printStackTrace(); } return rtn; } //刪除 public String deleteUser() { String rtn="fail"; try { //獲取userid; //獲得原生的request HttpServletRequest hsr=ServletActionContext.getRequest(); String uid = hsr.getParameter("userid"); //執行刪除 new UserService().delete(Integer.parseInt(uid)); rtn = "success"; } catch(Exception e) { e.printStackTrace(); } return rtn; } //查詢單條記錄 public String selectd() { String rtn="fail"; try { //獲得原生的request HttpServletRequest hsr=ServletActionContext.getRequest(); String uid=hsr.getParameter("userid"); int userid = Integer.parseInt(uid); User u= new UserService().select(userid); hsr.setAttribute("user", u); rtn="success"; } catch(Exception e) { e.printStackTrace(); } return rtn; } //修改單個用戶記錄 public String update() { String rtn="fail"; try { // HttpServletRequest hsr=ServletActionContext.getRequest(); // String uid=hsr.getParameter("userid"); //執行修改 new UserService().update(user); rtn="success"; } catch(Exception e) { e.printStackTrace(); } return rtn; } // 分頁查詢 public String selectUserf() { String rtn="fail"; try { //獲得原生的request HttpServletRequest hsr= ServletActionContext.getRequest(); int page= Integer.parseInt(hsr.getParameter("pages")); //調用查詢的方法 List<User>list=new UserService().selectf(page); hsr.setAttribute("pages", page+1); hsr.setAttribute("fselect", list); rtn="success"; } catch(Exception e) { e.printStackTrace(); } return rtn; } }
package com.hanqi.action; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.hanqi.entity.User; import com.hanqi.service.UserService; import com.opensymphony.xwork2.ModelDriven; // 使用模型驅動的方式 // 實現接口ModelDriven<實體類> public class UserAction2 implements ModelDriven<User>{ //必需要實例化 private User user = new User(); // 返回實體類的實例 @Override public User getModel() { // 返回的必須是模型的 實例 return user; } // 保存數據 public String saveUser() { String rtn ="fail"; try { //保存 new UserService().add(user); HttpServletRequest hsr = ServletActionContext.getRequest(); hsr.setAttribute("user", user); rtn="success"; } catch(Exception e) { e.printStackTrace(); } return rtn; } }
9. index.jsp 主界面app
<%@ 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>Insert title here</title> </head> <body> <a href="addUser">添加用戶</a> <br> <br> <a href="selectUser?pages=1">用戶列表</a> <br> <br> <a href="addUser2">添加用戶2</a> </body> </html>
添加用戶界面jsp
<%@page import="com.hanqi.service.UserService"%> <%@page import="com.hanqi.entity.User"%> <%@ 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>Insert title here</title> </head> <body> 添加用戶 <br> <br> <form action="saveUser!insertUser.action" method="post"> 用戶名:<input type="text" name="user.userName"> <br> 密碼:<input type="password" name="user.password"> <br> 生日:<input type="text" name="user.birthday"> <br> 薪酬:<input type="text" name="user.money"> <br><br> <input type="submit" value="保存"> </form> </body> </html>
跳轉成功的界面
<%@ 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>Insert title here</title> </head> <body> 操做成功! <br> User =${user } <br> </body> </html>
跳轉失敗的界面
<%@ 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>Insert title here</title> </head> <body> 操做失敗 </body> </html>
查詢用戶的界面
<%@page import="com.hanqi.entity.User"%> <%@page import="java.util.List"%> <%@ 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>Insert title here</title> </head> <body> <% List<User>lu = (List<User>)request.getAttribute("userlist"); for(User u:lu) { out.print(u+"【<a href='deleteUser?userid="+u.getUserID()+"'>刪除</a>】【<a href='updateUser?userid="+u.getUserID()+"'>修改</a>】<br>"); int pages = Integer.parseInt(request.getParameter("pages")); } %> <br><br> </body> </html>
修改用戶的界面
<%@page import="com.hanqi.entity.User"%> <%@ 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>Insert title here</title> </head> <body> <% User us = (User)request.getAttribute("user"); %> <br> <br> <form action="EditUser" method="post"> 用戶ID:<input type="text" readonly="readonly" name="user.userID" value="<% out.print(us.getUserID());%>"> 用戶名:<input type="text" name="user.userName" value="<% out.print(us.getUserName());%>"> <br> 密碼:<input type="password" name="user.password" value="<% out.print(us.getPassword());%>"> <br> 生日:<input type="text" name="user.birthday" value="<% out.print(us.getBirthday());%>"> <br> 薪酬:<input type="text" name="user.money" value="<%out.print(us.getMoney());%>"> <br><br> <input type="submit" value="保存"> </form> </body> </html>
用模型驅動方式添加用戶的界面
<%@page import="com.hanqi.service.UserService"%> <%@page import="com.hanqi.entity.User"%> <%@ 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>Insert title here</title> </head> <body> 添加用戶-模型驅動方式 <br> <br> <form action="saveUser2" method="post"> 用戶名:<input type="text" name="userName"> <br> 密碼:<input type="password" name="password"> <br> 生日:<input type="text" name="birthday"> <br> 薪酬:<input type="text" name="money"> <br><br> <input type="submit" value="保存"> </form> </body> </html>