<?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">
<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>
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///ssh01</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="com/dto/Dto.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<?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">
<hibernate-mapping>
<class name="com.dto.Dog" table="t_dog">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"/>
<property name="age"/>
<many-to-one name="t" lazy="false"></many-to-one>
</class>
<class name="com.dto.Type" table="t_type">
<id name="tid">
<generator class="native"></generator>
</id>
<property name="tname"/>
</class>
</hibernate-mapping>
package com.dto;
public class Dog {
private Integer id;
private String name;
private Integer age;
private Type t;
public Dog() {
super();
// TODO Auto-generated constructor stub
}
public Dog(Integer id, String name, Integer age, Type t) {
super();
this.id = id;
this.name = name;
this.age = age;
this.t = t;
}
@Override
public String toString() {
return "Dog [id=" + id + ", name=" + name + ", age=" + age + ", t=" + t
+ "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Type getT() {
return t;
}
public void setT(Type t) {
this.t = t;
}
}
package com.dto;
public class Type {
private Integer tid;
private String tname;
public Type() {
super();
// TODO Auto-generated constructor stub
}
public Type(Integer tid, String tname) {
super();
this.tid = tid;
this.tname = tname;
}
@Override
public String toString() {
return "Type [tid=" + tid + ", tname=" + tname + "]";
}
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
}
package com.action;
/* * 2018-6-8 14:26:47 * hao * 多对一 * */
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import net.sf.json.JSONObject;
import com.dto.Dog;
import com.dto.Type;
import com.opensymphony.xwork2.ActionSupport;
import com.service.DogService;
public class Action extends ActionSupport{
private DogService service = new DogService();
private List<Dog> dogList;
private Dog dog;
public String list() throws Exception {
// TODO Auto-generated method stub
dogList = service.dogList();
return "list";
}
public void getType() throws Exception {
// TODO Auto-generated method stub
Map<String, Object> map = new HashMap<String, Object>();
List<Type> typeList = service.getType();
map.put("typeList", typeList);
dog = service.getDog(dog);
map.put("dog", dog);
JSONObject jsonObject = JSONObject.fromObject(map);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.getWriter().print(jsonObject);
}
public void add() throws Exception {
// TODO Auto-generated method stub
int i = service.add(dog);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.getWriter().print(i);
}
public void del() throws Exception {
// TODO Auto-generated method stub
int i = service.del(dog);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.getWriter().print(i);
}
public List<Dog> getDogList() {
return dogList;
}
public void setDogList(List<Dog> dogList) {
this.dogList = dogList;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
package com.service;
import java.util.List;
import com.dao.DogDao;
import com.dto.Dog;
import com.dto.Type;
public class DogService {
private DogDao dao = new DogDao();
public List<Dog> dogList() {
// TODO Auto-generated method stub
return dao.dogList();
}
public List<Type> getType() {
// TODO Auto-generated method stub
return dao.getType();
}
public Dog getDog(Dog dog) {
// TODO Auto-generated method stub
return dao.getDog(dog);
}
public int add(Dog dog) {
// TODO Auto-generated method stub
return dao.add(dog);
}
public int del(Dog dog) {
// TODO Auto-generated method stub
return dao.del(dog);
}
}
package com.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.dto.Dog;
import com.dto.Type;
import com.util.HibernateUtils;
public class DogDao {
public List<Dog> dogList() {
// TODO Auto-generated method stub
Session session = HibernateUtils.getSession();
String hql =" from Dog ";
Query query = session.createQuery(hql);
List list = query.list();
return list;
}
public List<Type> getType() {
// TODO Auto-generated method stub
Session session = HibernateUtils.getSession();
Query query = session.createQuery(" from Type ");
List list = query.list();
session.close();
return list;
}
public Dog getDog(Dog dog) {
// TODO Auto-generated method stub
Session session = HibernateUtils.getSession();
Dog d = (Dog) session.get(Dog.class, dog.getId());
session.close();
return d;
}
public int add(Dog dog) {
// TODO Auto-generated method stub
Session session = HibernateUtils.getSession();
try {
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(dog);
transaction.commit();
return 1;
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}finally {
session.close();
}
}
public int del(Dog dog) {
// TODO Auto-generated method stub
Session session = HibernateUtils.getSession();
try {
Transaction transaction = session.beginTransaction();
session.delete(dog);
transaction.commit();
return 1;
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}finally {
session.close();
}
}
}
package com.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static SessionFactory sessionFactory = null;
static{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public static Session getSession(){
return sessionFactory.openSession();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="abc" extends="struts-default">
<action name="d_*" class="com.action.Action" method="{1}">
<result name="list">list.jsp</result>
</action>
</package>
</struts>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<% 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 'list.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"> -->
<link rel="stylesheet" href="css/index_work.css" type="text/css"></link>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript"> function del(id){ if(confirm("确认要删除吗?")){ $.post( "d_del", {"dog.id":id}, function (obj){ if(obj==1){ alert("删除成功"); location = " d_list "; }else if(obj==0){ alert("删除失败"); } } ); } } </script>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>t</th>
<th>
<input type="button" value="添加" onclick="location='add.jsp'"/>
</th>
</tr>
<c:forEach var="s" items="${dogList}">
<tr>
<th>${s.id}</th>
<th>${s.name}</th>
<th>${s.age}</th>
<th>${s.t.tname}</th>
<th>
<input type="button" value="修改" onclick="location='add.jsp?id=${s.id}'"/>
<input type="button" value="删除" onclick="del(${s.id})"/>
</th>
</tr>
</c:forEach>
</table>
</body>
</html>
<%@ 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.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"> -->
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript"> $(function (){ var id = "${param.id}"; if(id==""){ id=-1; } $.post( "d_getType", {"dog.id":id}, function (data){ var typeList = data.typeList; for(var i in typeList){ var t = typeList[i]; $('[name="dog.t.tid"]').append('<option value="'+t.tid+'">'+t.tname+'</option>'); } var dog = data.dog; $("[name='dog.id']").val(dog.id); $("[name='dog.name']").val(dog.name); $("[name='dog.age']").val(dog.age); $("[name='dog.t.tid']").val(dog.t.tid); },"json" ); }); function sub(){ $.post( "d_add", $("form").serialize(), function (obj){ if(obj==1){ alert("提交成功"); location=" d_list "; }else if(obj==0){ alert("提交失败"); } },"json" ) } </script>
</head>
<body>
<form>
<input name="dog.id" value="${param.id}" type="hidden"/>
name:<input name="dog.name"/><br>
age:<input name="dog.age"/><br>
t:<select name="dog.t.tid">
</select>
</form>
<button onclick="sub()">提交</button>
</body>
</html>
烟花易冷,人宸异变。等到那人心已变,一纸红鸢,又是谁人醉?
人生世事,世事无常。待到山花花已谢,一船忧愁,哪有闲人念。