package com.etc.action; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.etc.biz.FamilyBiz; import com.etc.entity.Family; import com.etc.entity.Pet; import com.google.gson.Gson; import com.opensymphony.xwork2.ActionSupport; public class FamilyAction extends ActionSupport { private List<Family> list ; private List<Pet> pets ; private FamilyBiz biz; private Family family;//a 用于接收来自表单的输入 private Pet pet;//a 用于接收来自ajax的宠物输入 public List<Pet> getPets() { return pets; } public void setPets(List<Pet> pets) { this.pets = pets; } public Pet getPet() { return pet; } public void setPet(Pet pet) { this.pet = pet; } private boolean isshow; private String msg; public boolean isIsshow() { return isshow; } public void setIsshow(boolean isshow) { this.isshow = isshow; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Family getFamily() { return family; } public void setFamily(Family family) { this.family = family; } public List<Family> getList() { return list; } public void setList(List<Family> list) { this.list = list; } public FamilyBiz getBiz() { return biz; } public void setBiz(FamilyBiz biz) { this.biz = biz; } public String findall() { list = biz.findAll(); return "findall_success"; } public String add() { //1 让表单输入的宠物list,作为family的set对象 Set<Pet> ps = new HashSet<Pet>(this.pets); for(Pet p:ps) p.setFamily(family); family.setPets(ps); try { biz.add(family); } catch (Exception e) { isshow = true; msg = "添加过程发现未知异常!"+e.getMessage(); return "my_error"; } isshow = true; msg = "添加成功!"; return "add_success"; } public String toupdate() { int fid = family.getFid(); family = biz.findById(fid); return "toupdate_success"; } public String update() { //1 让表单输入的宠物list,作为family的set对象 Set<Pet> ps = new HashSet<Pet>(this.pets); for(Pet p:ps) p.setFamily(family); family.setPets(ps); try { biz.update(family); } catch (Exception e) { isshow = true; msg = "修改过程发现未知异常!"+e.getMessage(); return "my_error"; } isshow = true; msg = "修改成功!"; return "update_success"; } public String addpet() throws IOException { //让pet和family对象发生关联关系 pet.setFamily(family); try { int pid = biz.add(pet); pet.setPid(pid);//添加成功,使用返回的主键让pet对象完整。 } catch (Exception e) { } Gson gson = new Gson(); String json = gson.toJson(pet);//将pet对象转成json字符串返回 //先设置响应编码 HttpServletResponse res = ServletActionContext.getResponse(); res.setContentType("text/html;charset=utf-8"); PrintWriter pw = res.getWriter(); //写回客户端 pw.print(json); pw.flush(); pw.close(); return "addpet_success"; } public String delpet() throws IOException { int pid = pet.getPid(); //family = new Family(); //pet.setFamily(family); String restxt = ""; try { biz.delpet(pid); restxt = "1"; } catch (Exception e) { restxt = "0"; } //先设置响应编码 HttpServletResponse res = ServletActionContext.getResponse(); res.setContentType("text/html;charset=utf-8"); PrintWriter pw = res.getWriter(); //写回客户端 pw.print(restxt); pw.flush(); pw.close(); return "delpet_success"; } public String delete() { int fid = family.getFid(); try { biz.del(fid); } catch (Exception e) { isshow = true; msg = "删除过程发现未知异常!"+e.getMessage(); return "my_error"; } isshow = true; msg = "删除成功!"; return "delete_success"; } }
package com.etc.biz; import java.util.List; import com.etc.entity.Family; import com.etc.entity.Pet; public interface FamilyBiz { List<Family> findAll(); void add(Family family); Family findById(int fid); void update(Family family); //ajax专用,返回添加后的主键 int add(Pet pet); void del(int fid); void delpet(int pid); }
package com.etc.biz.imp; import java.util.List; import com.etc.biz.FamilyBiz; import com.etc.dao.FamilyDao; import com.etc.entity.Family; import com.etc.entity.Pet; public class FamilyBizImp implements FamilyBiz { private FamilyDao dao; public FamilyDao getDao() { return dao; } public void setDao(FamilyDao dao) { this.dao = dao; } public List<Family> findAll() { return dao.findAll(); } public void add(Family family) { dao.add(family); } public Family findById(int fid) { return dao.findById(fid); } public void update(Family family) { dao.update(family); } public int add(Pet pet) { return dao.add(pet); } public void delpet(int pid) { dao.delpet(pid); } public void del(int fid) { dao.del(fid); } }
package com.etc.dao; import java.util.List; import com.etc.entity.Family; import com.etc.entity.Pet; public interface FamilyDao { List<Family> findAll(); void add(Family family); Family findById(int fid); void update(Family family); //ajax专用 int add(Pet pet); void del(int fid); void delpet(int pid); }
package com.etc.dao.imp; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.etc.dao.FamilyDao; import com.etc.entity.Family; import com.etc.entity.Pet; public class FamilyDaoImp extends HibernateDaoSupport implements FamilyDao { public List<Family> findAll() { String hql = "from Family"; return this.getHibernateTemplate().find(hql); } public void add(Family family) { this.getHibernateTemplate().save(family); } public Family findById(int fid) { return this.getHibernateTemplate().get(Family.class, fid); } public void update(Family family) { this.getHibernateTemplate().update(family); } public int add(Pet pet) { return (Integer) this.getHibernateTemplate().save(pet); } public void delpet(int pid) { //先查再删除 Pet p = this.getHibernateTemplate().get(Pet.class, pid); this.getHibernateTemplate().delete(p); } public void del(int fid) { //先查再删除 Family f = this.getHibernateTemplate().get(Family.class, fid); this.getHibernateTemplate().delete(f); } }
package com.etc.entity; import java.util.HashSet; import java.util.Set; /** * Family entity. @author MyEclipse Persistence Tools */ public class Family implements java.io.Serializable { // Fields private Integer fid; private String fname; private Float wealth; private Set pets = new HashSet(0); // Constructors /** default constructor */ public Family() { } /** minimal constructor */ public Family(Float wealth) { this.wealth = wealth; } /** full constructor */ public Family(String fname, Float wealth, Set pets) { this.fname = fname; this.wealth = wealth; this.pets = pets; } // Property accessors public Integer getFid() { return this.fid; } public void setFid(Integer fid) { this.fid = fid; } public String getFname() { return this.fname; } public void setFname(String fname) { this.fname = fname; } public Float getWealth() { return this.wealth; } public void setWealth(Float wealth) { this.wealth = wealth; } public Set getPets() { return this.pets; } public void setPets(Set pets) { this.pets = pets; } }
package com.etc.entity; /** * Pet entity. @author MyEclipse Persistence Tools */ public class Pet implements java.io.Serializable { // Fields private Integer pid; private Family family; private String pname; private Float price; private Integer cohesion; // Constructors /** default constructor */ public Pet() { } /** minimal constructor */ public Pet(Family family, Float price, Integer cohesion) { this.family = family; this.price = price; this.cohesion = cohesion; } /** full constructor */ public Pet(Family family, String pname, Float price, Integer cohesion) { this.family = family; this.pname = pname; this.price = price; this.cohesion = cohesion; } // Property accessors public Integer getPid() { return this.pid; } public void setPid(Integer pid) { this.pid = pid; } public Family getFamily() { return this.family; } public void setFamily(Family family) { this.family = family; } public String getPname() { return this.pname; } public void setPname(String pname) { this.pname = pname; } public Float getPrice() { return this.price; } public void setPrice(Float price) { this.price = price; } public Integer getCohesion() { return this.cohesion; } public void setCohesion(Integer cohesion) { this.cohesion = cohesion; } }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.etc.entity.Family" table="family" catalog="java"> <id name="fid" type="java.lang.Integer"> <column name="fid" /> <generator class="identity" /> </id> <property name="fname" type="java.lang.String"> <column name="fname" length="20" /> </property> <property name="wealth" type="java.lang.Float"> <column name="wealth" precision="12" scale="0" not-null="true" /> </property> <!-- 关联对象集合的配置,默认是lazy=true,延迟加载 .通过cascade配置成关联对象的级联添加--> <set name="pets" inverse="true" lazy="true" cascade="save-update,delete"> <key> <column name="fid" not-null="true" /> </key> <one-to-many class="com.etc.entity.Pet" /> </set> </class> </hibernate-mapping>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.etc.entity.Pet" table="pet" catalog="java"> <id name="pid" type="java.lang.Integer"> <column name="pid" /> <generator class="identity" /> </id> <many-to-one name="family" class="com.etc.entity.Family" fetch="select"> <column name="fid" not-null="true" /> </many-to-one> <property name="pname" type="java.lang.String"> <column name="pname" length="20" /> </property> <property name="price" type="java.lang.Float"> <column name="price" precision="12" scale="0" not-null="true" /> </property> <property name="cohesion" type="java.lang.Integer"> <column name="cohesion" not-null="true" /> </property> </class> </hibernate-mapping>
package com.etc.test; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.etc.action.FamilyAction; import com.etc.entity.Family; import com.etc.entity.Pet; public class TestFamliyAction { BeanFactory fac = new ClassPathXmlApplicationContext("applicationContext.xml"); FamilyAction action = (FamilyAction) fac.getBean("familyaction"); //@Test public void test_findAll() { System.out.println(action.findall()); System.out.println(action.getList().size()); } //@Test public void test_add() { //使用创建对象,模拟表单的输入 Family f = new Family(10000f); f.setFname("辛普森一家"); Set<Pet> pets = new HashSet<Pet>(); pets.add(new Pet(f,"蜥蜴",20f,5)); f.setPets(pets); action.setFamily(f); System.out.println(action.add()); //调用添加的控制器方法 //调用查询全部方法,判断有没有成功 System.out.println(action.findall()); System.out.println(action.getList().size()); } @Test public void test_delpet() throws IOException { Pet p = new Pet(); p.setPid(2); action.setPet(p); System.out.println(action.delpet()); } }
applicationContext.xml:<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"> </property> </bean> <bean id="dao" class="com.etc.dao.imp.FamilyDaoImp"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="biz" class="com.etc.biz.imp.FamilyBizImp"> <property name="dao" ref="dao"></property> </bean> <bean id="familyaction" class="com.etc.action.FamilyAction" scope="prototype"> <property name="biz" ref="biz"/> </bean> <bean id="tm" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:advice id="myadvice" transaction-manager="tm"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="find*" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.etc.biz.*.*(..))" id="mypc"/> <aop:advisor advice-ref="myadvice" pointcut-ref="mypc"/> </aop:config> </beans>
struts.xml:<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="p" namespace="/" extends="struts-default"> <action name="*" class="familyaction" method="{1}"> <result name="findall_success"> /showlist.jsp </result> <result name="add_success" type="chain"> <param name="actionName">findall</param> <param name="namespace">/</param> </result> <result name="toupdate_success"> /update_family.jsp </result> <result name="update_success" type="chain"> <param name="actionName">findall</param> <param name="namespace">/</param> </result> <result name="addpet_success" type="stream"> </result> <result name="delpet_success" type="stream"> </result> <result name="delete_success" type="chain"> <param name="actionName">findall</param> <param name="namespace">/</param> </result> <result name="input"> /show_input_error.jsp </result> <result name="my_error"> /show_my_error.jsp </result> </action> </package> </struts>
web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <!-- 配置全局的配置参数 ,spring配置文件的位置 --> <param-name> contextConfigLocation </param-name> <param-value> classpath:applicationContext.xml </param-value> </context-param> <!-- 通过spring提供的web监听器来启动对象工厂 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 声明1个延迟加载过滤器 --> <filter> <filter-name>lazyFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>false</param-value> </init-param> </filter> <!--设定过滤器只对.action请求有效 --> <filter-mapping> <filter-name>lazyFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <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>*.action</url-pattern> </filter-mapping></web-app>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘add_famliy.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="add.action" method="post"> 家庭名: <input name="family.fname" /> <br/> 财产: <input name="family.wealth"/><br/> 宠物名: <input name="pets[0].pname"> 宠物价格: <input name="pets[0].price"> 亲密度: <input name="pets[0].cohesion"> <input type="button" value="+"/> <br/> <input type="submit" value="添加"/> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘showlist.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <script> alert(‘输入有误!‘); history.go(-1); </script> <s:fielderror/> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘showlist.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <script> alert("${msg}"); location.href="findall.action"; </script> <s:fielderror/> </body> </html>
<%@ page language="java" import="java.util.*,com.etc.entity.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘showlist.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <script> function showmsg(isshow,msg) { if(isshow) alert(msg); } </script> <body > 家庭信息<br/> <table border="1"> <tr> <th>编号</th> <th>名称</th> <th>资产</th> <th>宠物数</th> <th>操作</th> </tr> <s:iterator value="list" var="f"> <tr> <td>${f.fid }</td> <td>${f.fname }</td> <td>${f.wealth }</td> <td> <%= ((Family) request.getAttribute("f")).getPets().size() %> </td> <td><a href="delete.action?family.fid=${f.fid}">删除</a> <a href="toupdate.action?family.fid=${f.fid}">修改</a></td> </tr> </s:iterator> </table> <br/> <a href="add_family.jsp">添加</a> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <style> input { width: 60px; } </style> <head> <base href="<%=basePath%>"> <title>My JSP ‘add_famliy.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <script type="text/javascript" src="js/jquery.js"> </script> <script> $(document).ready( function() { $("#add").click( function() { addnew(); } ); } ) function addnew() { var pname = window.prompt("宠物名","宠物名"); if(pname==null) return; var price = window.prompt("价格","100"); if(price==null) return; var cohesion = window.prompt("亲密度","50"); if(price==null) return; var msg = pname+","+price+","+cohesion+",确认添加 ?"; if (window.confirm(msg)) send_ajax_add_request(pname,price,cohesion); } function send_ajax_add_request(pname,price,cohesion) { var paras = "pet.pname="+pname+"&pet.price=" +price+"&pet.cohesion="+cohesion+"&family.fid=${family.fid}"; $.ajax( { type:"post", url:"addpet.action", data:paras, dataType:"json", success:function(obj) { var old = $("#sp").html(); var html = "<span id=‘inner_sp_"+obj.pid+"‘>" +"编号: <input name=‘pets["+petcount+"].pid‘ value=‘"+obj.pid+"‘ readonly=‘readonly‘>" +"宠物名: <input name=‘pets["+petcount+"].pname‘ value=‘"+obj.pname+"‘>" +"宠物价格: <input name=‘pets["+petcount+"].price‘ value=‘"+obj.price+"‘>" +"亲密度: <input name=‘pets["+petcount+"].cohesion‘ value=‘"+obj.cohesion+"‘>" +"<input type=‘button‘ value=‘删除‘ onclick=‘send_ajax_delete_request("+obj.pid+")‘/><br/>" +"</span>"; $("#sp").html(old+html); petcount++; } } ); } function send_ajax_delete_request(pid) { var paras = "pet.pid="+pid; var url = "delpet.action"; $.post(url, { "pet.pid": pid}, function(txt){ if(txt=="1") $("#inner_sp_"+pid).remove(); }); } </script> <body> <form action="update.action" method="post"> 编号: <input name="family.fid" readonly="readonly" value="${family.fid }" /> <br /> 家庭名: <input name="family.fname" value="${family.fname }"/> <br /> 财产: <input name="family.wealth" value="${family.wealth }"/> <br /> <s:set var="i" value="0"/> <span id="sp"> <s:iterator value="family.pets" var="p"> <span id="inner_sp_${p.pid}"> 编号: <input name="pets[${i}].pid" value="${p.pid }" readonly="readonly"> 宠物名: <input name="pets[${i}].pname" value="${p.pname }"> 宠物价格: <input name="pets[${i}].price" value="${p.price }"> 亲密度: <input name="pets[${i}].cohesion" value="${p.cohesion }"> <s:set var="i" value="#attr.i+1"/> <input type="button" value="删除" onclick="send_ajax_delete_request(${p.pid })" /><br/> </span> </s:iterator> </span> <script> var petcount = ${i}; //记录总的宠物个数 </script> <br /> <input id="add" type="button" value="添加宠物"/><br/> <input type="submit" value="修改" /> </form> </body> </html>
时间: 2024-10-14 02:25:44