<?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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<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 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="ssh" extends="struts-default">
<action name="c_*" class="com.action.Action" method="{1}">
<result name="list">/list.jsp</result>
</action>
</package>
</struts>
<?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://localhost:3306/ssh01
</property>
<!-- 用户名 -->
<property name="connection.username">root</property>
<!-- 密码 -->
<property name="connection.password">root</property>
<!-- 方言 -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- 自动生成表create每次加载都创建新的表/update如果有表,在原表的基础上修改;如果没有表创建新表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 打印sql语句 -->
<property name="show_sql">true</property>
<!-- sql格式化 -->
<property name="format_sql">true</property>
<mapping resource="com/dto/Dto.hbm.xml" />
</session-factory>
</hibernate-configuration>
<?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: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-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 实例化一个SessionFactory -->
<!-- 伪代码:
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setConfigLocation("classpath:hibernate.cfg.xml");
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 实例化一个DAO -->
<bean id="dao" class="com.dao.CarDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 实例化一个Service -->
<bean id="service" class="com.service.CarService">
<property name="dao" ref="dao"></property>
</bean>
<!-- 实例化一个事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置被事务管理的方法 -->
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="del*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务植入的切面 -->
<aop:config>
<aop:advisor advice-ref="myAdvice" pointcut="execution(* com.service.*.*(..))"/>
</aop:config>
</beans>
<?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.Car" table="t_car">
<id name="cid">
<generator class="native"></generator>
</id>
<property name="cprice"></property>
<property name="cdate"></property>
<property name="cnum"></property>
<many-to-one name="b" column="brand" lazy="false"></many-to-one>
</class>
<class name="com.dto.Brand" table="t_brand">
<id name="bid">
<generator class="native"></generator>
</id>
<property name="bname"></property>
</class>
</hibernate-mapping>
package com.dto;
public class Car {
private Integer cid;
private String cprice;
private String cdate;
private Integer cnum;
private Brand b;
public Car() {
super();
// TODO Auto-generated constructor stub
}
public Car(Integer cid, String cprice, String cdate, Integer cnum, Brand b) {
super();
this.cid = cid;
this.cprice = cprice;
this.cdate = cdate;
this.cnum = cnum;
this.b = b;
}
@Override
public String toString() {
return "Car [cid=" + cid + ", cprice=" + cprice + ", cdate=" + cdate
+ ", cnum=" + cnum + ", b=" + b + "]";
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getCprice() {
return cprice;
}
public void setCprice(String cprice) {
this.cprice = cprice;
}
public String getCdate() {
return cdate;
}
public void setCdate(String cdate) {
this.cdate = cdate;
}
public Integer getCnum() {
return cnum;
}
public void setCnum(Integer cnum) {
this.cnum = cnum;
}
public Brand getB() {
return b;
}
public void setB(Brand b) {
this.b = b;
}
}
package com.dto;
public class Brand {
private Integer bid;
private String bname;
public Brand() {
super();
// TODO Auto-generated constructor stub
}
public Brand(Integer bid, String bname) {
super();
this.bid = bid;
this.bname = bname;
}
@Override
public String toString() {
return "Brand [bid=" + bid + ", bname=" + bname + "]";
}
public Integer getBid() {
return bid;
}
public void setBid(Integer bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
}
package com.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.alibaba.fastjson.JSONArray;
import com.dto.Car;
import com.service.CarService;
import com.util.PageUtils;
public class Action {
private CarService service;
private List<Car> carList;
private Car car;
private String ids;
private PageUtils pu;
private String mohu;
private Integer cpage;
public String list(){
if(cpage==null){
cpage=1;
}
Integer pageSize = 3;
Integer count = service.getCount(mohu);
pu = new PageUtils(cpage, pageSize, count);
carList = service.findCarList(pu,mohu);
return "list";
}
public void getData() throws IOException{
List downList = service.downList();
car = service.getCar(car);
Map map = new HashMap();
map.put("downList", downList);
map.put("car", car);
String jsonString = JSONArray.toJSONString(map);
System.out.println(jsonString);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.getWriter().print(jsonString);
}
public void update() throws IOException{
int i = service.update(car);
HttpServletResponse response = ServletActionContext.getResponse();
response.getWriter().print(i);
}
public void delete() throws IOException{
System.out.println("delete");
System.out.println("car.id值"+car.getCid());
System.out.println(car.getCid());
int i = service.delete(car);
System.out.println(i);
HttpServletResponse response = ServletActionContext.getResponse();
response.getWriter().print(i);
}
public void dels() throws IOException{
int i = service.dels(ids);
System.out.println(i);
HttpServletResponse response = ServletActionContext.getResponse();
response.getWriter().print(i);
}
public CarService getService() {
return service;
}
public void setService(CarService service) {
this.service = service;
}
public List<Car> getCarList() {
return carList;
}
public void setCarList(List<Car> carList) {
this.carList = carList;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
public PageUtils getPu() {
return pu;
}
public void setPu(PageUtils pu) {
this.pu = pu;
}
public String getMohu() {
return mohu;
}
public void setMohu(String mohu) {
this.mohu = mohu;
}
public Integer getCpage() {
return cpage;
}
public void setCpage(Integer cpage) {
this.cpage = cpage;
}
}
package com.service;
import java.util.List;
import com.dao.CarDao;
import com.dto.Car;
import com.util.PageUtils;
public class CarService {
private CarDao dao;
public CarDao getDao() {
return dao;
}
public void setDao(CarDao dao) {
this.dao = dao;
}
public List<Car> findCarList(PageUtils pu, String mohu) {
// TODO Auto-generated method stub
return dao.findCarList(pu,mohu);
}
public Car getCar(Car car) {
// TODO Auto-generated method stub
return dao.getCar(car);
}
public List downList() {
// TODO Auto-generated method stub
return dao.downList();
}
public int update(Car car) {
// TODO Auto-generated method stub
return dao.update(car);
}
public int delete(Car car) {
// TODO Auto-generated method stub
return dao.delete(car);
}
public int dels(String ids) {
// TODO Auto-generated method stub
return dao.dels(ids);
}
public Integer getCount(String mohu) {
// TODO Auto-generated method stub
return dao.getCount(mohu);
}
}
package com.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.dto.Car;
import com.util.PageUtils;
public class CarDao extends HibernateDaoSupport{
public List<Car> findCarList(PageUtils pu, String mohu) {
String hql = " from Car ";
if(mohu!=null){
hql+=" where cdate like '%"+mohu+"%' ";
}
Query query = getSession().createQuery(hql).setFirstResult(pu.getStartIndex()).setMaxResults(pu.getPageSize());
List list = query.list();
return list;
}
public Car getCar(Car car) {
// TODO Auto-generated method stub
Car c = (Car) getHibernateTemplate().get(Car.class, car.getCid());
return c;
}
public List downList() {
// TODO Auto-generated method stub
return getHibernateTemplate().find("from Brand");
}
public int update(Car car) {
// TODO Auto-generated method stub
try {
getHibernateTemplate().saveOrUpdate(car);
return 1;
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
public int delete(Car car) {
// TODO Auto-generated method stub
System.out.println("dao-delete");
System.out.println(car.getCid());
try {
System.out.println(1);
getHibernateTemplate().delete(car);
System.out.println(2);
return 1;
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(3);
return 0;
}
}
public int dels(String ids) {
// TODO Auto-generated method stub
Query query = getSession().createQuery("delete from Car where cid in("+ids+")");
int i = query.executeUpdate();
return i;
}
public Integer getCount(String mohu) {
// TODO Auto-generated method stub
// Session session = getSession();
// String hql = "select count(*) from Car";
// if(mohu!=null){
// hql+=" where cdate='%"+mohu+"%' ";
// }
// Query query = session.createQuery(hql);
// Integer count = Integer.valueOf(query.toString());
// System.out.println("count是"+count);
// return count;
Session session = getSession();
String hql = "select count(*) from Car";
if(mohu != null){
hql += " where cdate like '%"+mohu+"%' ";
}
Query query = session.createQuery(hql);
Integer count = Integer.valueOf(query.uniqueResult().toString());
return count;
}
}
package com.util;
public class PageUtils {
private Integer cpage;//当前页
private Integer pageSize;//每页展示最大条数
private Integer count;//数据总条数
private Integer totalPage;//总页数
private Integer startIndex;//起始下标
private Integer prevPage;//上一页
private Integer nextPage;//下一页
//使用此工具类,调用这个构造器
public PageUtils(Integer cpage, Integer pageSize, Integer count) {
this.cpage = cpage;
this.pageSize = pageSize;
this.count = count;
calPrevPage();
calStartIndex();
calTotalPage();
calNextPage();
}
private void calTotalPage(){//计算总页数
this.totalPage = count/pageSize + (count%pageSize==0?0:1);
}
private void calStartIndex(){//计算起始下标
this.startIndex = (cpage-1)*pageSize;
}
private void calPrevPage(){//计算上一页
this.prevPage = cpage==1?1:(cpage-1);
}
private void calNextPage(){//计算下一页
this.nextPage = cpage.equals(totalPage)?totalPage:(cpage+1);
}
public Integer getCpage() {
return cpage;
}
public void setCpage(Integer cpage) {
this.cpage = cpage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Integer getStartIndex() {
return startIndex;
}
public void setStartIndex(Integer startIndex) {
this.startIndex = startIndex;
}
public Integer getPrevPage() {
return prevPage;
}
public void setPrevPage(Integer prevPage) {
this.prevPage = prevPage;
}
public Integer getNextPage() {
return nextPage;
}
public void setNextPage(Integer nextPage) {
this.nextPage = nextPage;
}
}
<%@ 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">
-->
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript">
function del(id){
if(confirm("删除?")){
$.post(
"c_delete",
{"car.cid":id},
function (msg){
if(msg==1){
alert("删除成功");
location ="c_list";
}else{
alert("删除失败");
}
},"text"
);
}
}
function allcheck(){
$(".ch").attr("checked",true);
}
function notcheck(){
$(".ch").attr("checked",false);
}
function recheck(){
$(".ch").each(function (){
$(this).attr("checked",!$(this).attr("checked"));
});
}
function dels(){
var ids = "";
$(".ch").each(function (){
if($(this).attr("checked")){
ids += ","+$(this).val();
}
});
ids = ids.substring(1);
if(ids.length>0){
$.post(
"c_dels",
{"ids":ids},
function (msg){
if(msg>0){
alert("删除成功");
location="c_list";
}else{
alert("删除失败");
}
},"text"
);
}else{
alert("请选择");
}
}
function mohu(cpage){
var mohu = $("[name='mohu']").val();
location="c_list?mohu="+mohu+"&cpage="+cpage;
}
function gopage(cpage){
mohu(cpage);
}
</script>
<link rel="stylesheet" href="css/index_work.css" type="text/css"></link></head>
<body>
<table>
<tr>
<th>
<button onclick="allcheck()">全选</button>
<button onclick="notcheck()">不选</button>
<button onclick="recheck()">反选</button>
<input name="mohu" type="text" value="${mohu}">
<input type="button" value="查询" onclick="mohu()">
</th>
</tr>
</table>
<table>
<tr>
<th><input type="button" value="批删" onclick="dels()"></th>
<th>cid</th>
<th>cprice</th>
<th>cdate</th>
<th>cnum</th>
<th>bid</th>
<th>bname</th>
<th><input type="button" value="新增" onclick="location='update.jsp'"></th>
</tr>
<c:forEach items="${carList}" var="c">
<tr>
<th><input type="checkbox" value="${c.cid}" class="ch"></th>
<th>${c.cid}</th>
<th>${c.cprice}</th>
<th>${c.cdate}</th>
<th>${c.cnum}</th>
<th>${c.b.bid}</th>
<th>${c.b.bname}</th>
<th><input type="button" value="删除" onclick="del(${c.cid})">
<input type="button" value="修改" onclick="location='update.jsp?id=${c.cid}'"></th>
</tr>
</c:forEach>
<tr>
<th colspan="21">
<input type="button" value="首页" onclick="gopage(1)">
<input type="button" value="上页" onclick="gopage(${pu.prevPage})">
<input type="button" value="下页" onclick="gopage(${pu.nextPage})">
<input type="button" onclick="gopage(${pu.totalPage})" value="尾页">
第${pu.cpage}页/共${pu.totalPage}页,总共 ${pu.count} 条记录
</th>
</tr>
</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 'update.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">
var id = "${param.id}";
if(id==""){
id=-1;
}
$.post(
"c_getData",
{"car.cid":id},
function (data){
var downList = data.downList;
for ( var i in downList) {
$("select").append("<option value="+downList[i].bid+">"+downList[i].bname+"</option>");
}
var car = data.car;
$("[name='car.cid']").val(car.cid);
$("[name='car.cprice']").val(car.cprice);
$("[name='car.cdate']").val(car.cdate);
$("[name='car.cnum']").val(car.cnum);
$("[name='car.b.bid']").val(car.b.bid);
},"json"
);
function sub(){
$.post(
"c_update",
$("form").serialize(),
function (msg){
if(msg==1){
alert("执行成功");
location="c_list";
}else{
alert("执行失败");
}
},"text"
);
}
</script>
<link rel="stylesheet" href="css/index_work.css" type="text/css"></link></head>
<body>
<form>
<input name="car.cid" type="hidden" type="text"><br>
cprice:<input name="car.cprice" type="text"><br>
cdate:<input name="car.cdate" type="text"><br>
cnum:<input name="car.cnum" type="text"><br>
bid:<select name="car.b.bid">
</select>
</form>
<input type="button" value="提交" onclick="sub()">
</body>
</html>
执子之手,与子偕老,是至慢境界。太多情侣双双,容易相看两厌,将慢字蹉跎成麻木。很多人是不会慢的,急急切切地速战速决,不懂得舞步蹁跹,必须后退。