具体步奏
步骤1.下载 mybatis-spring插件或者添加maven依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
步骤2.配置dbcp数据源
步骤3.配置SqlSessionFactoryBean设置数据源以及mybatis配置文件的位置
步骤四.配置SqlSessionTemplate 通过构造器注入SqlSessionFactoryBean
步骤五.配置DataSourceTransactionManager注入数据源配置事物
步骤六.配置MapperScannerConfigurer扫描注解对应的mapper文件对应的包
步骤七 配置spring事物的切面以及通知
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springIntegrationMybatis</groupId>
<artifactId>springIntegrationMybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name/>
<description/>
<dependencies>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>javaee-api</artifactId>
<version>5.0-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>1.2_04</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>1.2_04</version>
<scope>provided</scope>
</dependency>
<!-- 配置mybatis的依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- 配置本地的jar -->
<dependency>
<groupId>ojdbc</groupId>
<artifactId>objdc1</artifactId>
<version>3.2.8</version>
<scope>system</scope>
<systemPath>C:\app\Administrator\product\11.2.0\dbhome_1\jdbc\lib\ojdbc6.jar</systemPath>
</dependency>
<!-- spring和springMvc的jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!-- json的jar -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.3</version>
<classifier>jdk15</classifier>
</dependency>
<!-- jackson的一系列jar -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.12</version>
</dependency>
<!-- mybatis集成spring的核心jar -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- dbcp的数据源jar -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
<!-- 打印日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src</sourceDirectory>
<outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webappDirectory>${basedir}/WebRoot</webappDirectory>
<warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
spring.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
">
<context:component-scan base-package="cn.et.day20170606">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 加载资源文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 定义 数据源 通过el表达式把值设置进去 加载资源文件 -->
<bean id="datasoure" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${url}"></property>
<property name="driverClassName" value="${driverClassName}"></property>
<property name="username" value="${userAccount}"></property>
<property name="password" value="${password}"></property>
<property name="validationQuery" value="SELECT sysdate FROM DUAL"/>
</bean>
<!-- 数据库的操作类 -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasoure"></property>
<property name="configLocation" value="classpath:mybatis_config.xml"></property>
</bean>
<!-- 配置扫描 扫描接口映射的注解和xml文件-->
<bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 这么注入才不会覆盖加载资源文件 -->
<property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
<property name="basePackage" value="cn.et.day20170606.dao.mapper"></property>
</bean>
<!-- 声明事物管理器 数据库的事物控制类 用来控制事物 -->
<bean id="trancsaction" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--必须要加载这个属性 通过这个源把数据库的事物交给他处理 -->
<property name="dataSource" ref="datasoure"></property>
</bean>
<!-- 声明事物通知 -->
<tx:advice id="tran" transaction-manager="trancsaction">
<tx:attributes>
<!-- 告诉他拦截这个方法 -->
<tx:method name="insert*" />
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<!-- *代表了除了 上面配置的方法都不使用事务 -->
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 声明的事物通知方法 -->
<aop:config>
<!-- 配置一个切入点 -->
<aop:pointcut expression="execution(* cn.et.day20170606.service.*Service.*(..))" id="money"/>
<!-- 把通知和切入点引进来 -->
<aop:advisor advice-ref="tran" pointcut-ref="money"/>
</aop:config>
</beans>
springmvc.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
">
<!-- 配置扫描 -->
<context:component-scan base-package="cn.et.day20170606">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
<!-- 配置json消息转换器-->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!--
设置响应的支持的响应类型
-->
<value>text/html</value>
<value>text/html;charset=utf-8</value>
<value>application/json;charset=utf8</value>
</list>
</property>
</bean>
<!-- 交给tomcat处理 才可以访问静态资源 -->
<mvc:default-servlet-handler/>
<!-- 配置视图解析器
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsps/" p:suffix=".jsp">
</bean>
-->
<mvc:annotation-driven/>
</beans>
mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- Mybatis在使用resultMap来映射查询结果中的列,如果查询结果中包含空值的列(不是null),
则Mybatis在映射的时候,不会映射这个字段,例如 查询 name,sex,age
,数据库中的age字段没有值,Mybatis返回的map中只映射了 name和sex字段,而age字段则没有包含 -->
<settings>
<setting name="callSettersOnNulls" value="true"/>
</settings>
</configuration>
Controller
package cn.et.day20170606.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.et.day20170606.entity.EmpEntity;
import cn.et.day20170606.service.EmpJaxaService;
import cn.et.day20170606.utils.PagingEntity;
/**
*
* @author Administrator
*http://localhost:8080/springmvc/day0606/queryEmp
*/
@Controller
@RequestMapping(value="/day0609")
public class EmpJaxaAction {
@Autowired
private EmpJaxaService empService;
/**
*查询数据库的分页数据方法
*/
@RequestMapping(value="/queryPaginEmp")
@ResponseBody
public PagingEntity queryPagingEmp(Integer pagin,String ename){
return empService.queryPaginEmp(ename, pagin);
}
/**
*查询数据库的数据方法
*/
@RequestMapping(value="/queryEmp")
@ResponseBody
public List queryEmp(String ename){
return empService.queryEmp(ename);
}
/**
*新增数据库的数据方法
*成功返回1 失败返回0
* @throws IOException
*/
@ResponseBody
@RequestMapping(value="/insertEmp")
public void insertEmp(String ename,
String job,
String mgr,
String hiredate,
String sal,
String comm,
String deptno,OutputStream os) throws IOException{
EmpEntity emp=new EmpEntity();
emp.setComm(comm);
emp.setEname(ename);
emp.setHiredate(hiredate);
emp.setDeptno(deptno);
emp.setJob(job);
emp.setMgr(mgr);
emp.setSal(sal);
try{
empService.insertEmp(emp);
os.write("1".getBytes());
}catch (Exception e) {
os.write("0".getBytes());
}
}
/**
*更新数据库的数据方法
* @throws IOException
*/
@ResponseBody
@RequestMapping(value="/updateEmp")
public void updateEmp(String ename,String empno,
String job,
String mgr,
String hiredate,
String sal,
String comm,
String deptno,OutputStream os) throws IOException{
EmpEntity emp=new EmpEntity();
emp.setComm(comm);
emp.setEname(ename);
emp.setHiredate(hiredate);
emp.setDeptno(deptno);
emp.setJob(job);
emp.setMgr(mgr);
emp.setSal(sal);
emp.setDeptno(deptno);
emp.setEmpno(empno);
try{
empService.updateEmp(emp);
os.write("1".getBytes());
}catch (Exception e) {
os.write("0".getBytes());
}
}
/**
* 删除数据库数据的方法
* @throws IOException
*/
@ResponseBody
@RequestMapping(value="/deleteEmp")
public void deleteEmp(String empno,OutputStream os) throws IOException{
try{
empService.deleteEmp(empno);
os.write("1".getBytes());
}catch (Exception e) {
os.write("0".getBytes());
}
}
}
Service
package cn.et.day20170606.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.et.day20170606.dao.EmpJaxaDao;
import cn.et.day20170606.entity.EmpEntity;
import cn.et.day20170606.service.EmpJaxaService;
import cn.et.day20170606.utils.Calculate;
import cn.et.day20170606.utils.PagingEntity;
@Service
public class EmpJaxaServiceImpl implements EmpJaxaService {
@Autowired
private EmpJaxaDao empDao;
/**
*调用查询数据库的数据方法
*/
public List<Map<String,Object>> queryEmp(String ename){
return empDao.queryEmp("%"+ename+"%");
}
/**
*调用新增数据库的数据方法
*/
public void insertEmp(EmpEntity emp){
empDao.insertEmp(emp);
}
/**
*调用更新数据库的数据方法
*/
public void updateEmp(EmpEntity emp){
empDao.updateEmp(emp);
}
/**
* 调用删除数据库数据的方法
*/
public void deleteEmp(String empno){
empDao.deleteEmp(empno);
}
/**
*查询数据库的分页数据方法
*/
public PagingEntity queryPaginEmp(String ename,Integer current) {
if(ename==null){
ename="";
}
int sum=empDao.queryTotalEmp(ename);
PagingEntity p=Calculate.calculate(current, 5, sum);
List list=empDao.queryPaginEmp(ename,p.getStart(),p.getEnd());
p.setList(list);
return p;
}
}
Repository
package cn.et.day20170606.dao.impl;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cn.et.day20170606.dao.EmpJaxaDao;
import cn.et.day20170606.dao.mapper.EmpMybatiesMapper;
import cn.et.day20170606.entity.EmpEntity;
@Repository
public class EmpJaxaDaoImpl implements EmpJaxaDao{
@Autowired
private EmpMybatiesMapper empMybatiesMapper;
/**
*查询数据库的数据方法
* @throws IOException
* @throws IOException
*/
public List<Map<String,Object>> queryEmp(String ename){
return empMybatiesMapper.queryEmp(ename);
}
/**
*新增数据库的数据方法
* @throws IOException
*/
public void insertEmp(EmpEntity emp){
empMybatiesMapper.insertEmp(emp);
}
/**
*更新数据库的数据方法
* @throws IOException
*/
public void updateEmp(EmpEntity emp){
empMybatiesMapper.updateEmp(emp);
}
/**
* 删除数据库数据的方法
* @throws IOException
* @throws IOException
*/
public void deleteEmp(String empno){
empMybatiesMapper.deleteEmp(empno);
}
/**
*查询数据库的分页数据方法
*注意结束位置再前面 开始位置再后面
* @throws IOException
*/
public List<Map<String,Object>> queryPaginEmp(String ename, int start,
int end){
return empMybatiesMapper.queryPaginEmp(ename, end, start);
}
/**
*查询数据库的总数方法
* @throws IOException
*/
public int queryTotalEmp(String ename){
return empMybatiesMapper.queryTotalEmp(ename);
}
}
mybatis的注解接口
package cn.et.day20170606.dao.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import cn.et.day20170606.entity.EmpEntity;
public interface EmpMybatiesMapper {
1 max(列)+1 只允许单线程 不建议在开发坏境中用 开发测试可以用
2 序列 只允许单数据库的情况 next 开发坏境
3 uuid 分布式应用程序 (select sys_guid from dual)
/**
*查询数据库的数据方法
*/
@Select(value="select empno,ename,job,mgr,to_char(hiredate,'yyyy-mm-dd') as hiredate,sal,comm,deptno from emp where nvl(ename,' ') like '%'||#{ename}||'%'")
public List<Map<String,Object>> queryEmp(@Param(value="ename")String ename);
/**
*查询数据库的分页数据方法
*/
@Select(value="select * from (select empno,ename,job,mgr,to_char(hiredate,'yyyy-mm-dd') as hiredate,sal,comm,deptno,rownum rn from emp where nvl(ename,' ') like '%'||#{ename}||'%') where rn<=#{start} and rn>=#{end}")
public List<Map<String,Object>> queryPaginEmp(@Param(value="ename")String ename,@Param(value="start")int start,@Param(value="end")int end);
/**
*查询数据库的总数方法
*/
@Select("select count(rowid) as CT from emp where nvl(ename,' ') like '%'||#{ename}||'%'")
public int queryTotalEmp(@Param(value="ename")String ename);
/**
*新增数据库的数据方法
*/
@Insert(value="insert into emp values((select nvl(max(empno),0)+10 from emp),#{emp.ename},#{emp.job},#{emp.mgr},to_date(#{emp.hiredate},'yyyy-mm-dd'),#{emp.sal},#{emp.comm},#{emp.deptno})")
public void insertEmp(@Param(value="emp")EmpEntity emp);
/**
*更新数据库的数据方法
*/
@Update(value="update emp set ename=#{emp.ename},job=#{emp.job},mgr=#{emp.mgr},hiredate=to_date(#{emp.hiredate},'yyyy-mm-dd'),sal=#{emp.sal},comm=#{emp.comm},deptno=#{emp.deptno} where empno=#{emp.empno}")
public void updateEmp(@Param(value="emp")EmpEntity emp);
/**
* 删除数据库数据的方法
*/
@Delete(value="delete from emp where empno=#{empno}")
public void deleteEmp(@Param(value = "empno") String empno);
}
entity
package cn.et.day20170606.entity;
/**
* 数据库的数据类 (一个对象就是数据库的一行)
* @author Administrator
*
*/
public class EmpEntity {
private String empno;
private String ename;
private String job;
private String mgr;
private String hiredate;
private String sal;
private String comm;
private String deptno;
public String getEmpno() {
return empno;
}
public void setEmpno(String empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getMgr() {
return mgr;
}
public void setMgr(String mgr) {
this.mgr = mgr;
}
public String getHiredate() {
return hiredate;
}
public void setHiredate(String hiredate) {
this.hiredate = hiredate;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getComm() {
return comm;
}
public void setComm(String comm) {
this.comm = comm;
}
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
}
分页的工具类
package cn.et.day20170606.utils;
import java.util.List;
/**
* 分页的一些参数
* @author
*
* 编写时间:2017-4-19 下午03:45:42
*/
public class PagingEntity {
/**
* 当前页数
*/
private int current;
/**
* 一页显示的条数
*/
private int quantity;
/**
* 数据库的总条数
*/
private int sum;
/**
* 首页
*/
private int first=1;
/**
* 尾页
*/
private int trail;
/**
* 上一页
*/
private int last;
/**
* 下一页
*/
private int next;
/**
* 开始的位置
*/
private int start;
/**
* 结束的位置
*/
private int end;
private List list;
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
this.current = current;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
public int getLast() {
return last;
}
public void setLast(int last) {
this.last = last;
}
public int getNext() {
return next;
}
public void setNext(int next) {
this.next = next;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getFirst() {
return first;
}
public void setFirst(int first) {
this.first = first;
}
public int getTrail() {
return trail;
}
public void setTrail(int trail) {
this.trail = trail;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
给分页bean赋值
package cn.et.day20170606.utils;
/**
* 用来计算分页的参数
* @author 周芳园
*
* 编写时间:2017-4-19 下午04:01:33
*/
public class Calculate {
/**
* 设置他的参数
* @param current
* @param quantity
* @param sum
* @return
*/
public static PagingEntity calculate(int current,int quantity,int sum){
PagingEntity pa=new PagingEntity();
pa.setCurrent(current);
pa.setQuantity(quantity);
pa.setSum(sum);
int last=(current==1?1:current-1);
int start=(current-1)*quantity+1;
int end=current*quantity;
int trail=(sum%quantity==0?sum/quantity:sum/quantity+1);
int next=(current==trail?trail:current+1);
pa.setLast(last);
pa.setNext(next);
pa.setStart(start);
pa.setEnd(end);
pa.setTrail(trail);
return pa;
}
/**
* 测试逻辑对不对
*/
public static void main(String[] args) {
Calculate ca=new Calculate();
PagingEntity pa=ca.calculate(2, 5, 16);
System.out.print("当前页"+pa.getCurrent());
System.out.print("总页"+pa.getTrail());
System.out.println("上一页"+pa.getLast());
System.out.println("开始位置"+pa.getStart());
System.out.println("结束位置"+pa.getEnd());
}
}
jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var path="${pageContext.request.contextPath}/day0609";
//根据id获取对象
function $(id){
return document.getElementById(id);
}
//和div赋值
function toUpdate(empno,ename,job,mgr,hiredate,sal,comm,deptno){
$('updateDiv').style.display='block';
$('empNoId').value=empno;
$('updateEname').value=(ename=='null'?'':ename);
$('updateJob').value=(job=='null'?'':job);
$('updateMgr').value=mgr;
$('updateHiredate').value=hiredate;
$('updateSal').value=sal;
$('updateComm').value=comm;
$('updateDeptno').value=deptno;
}
/**
封装ajax
**/
function sendAjax(method,url,callback,param){
var xmlHttp=new XMLHttpRequest();
//向服务器发出请求
//规定请求的类型、URL 以及是否异步处理请求。
//method:请求的类型;GET 或 POST
//url:文件在服务器上的位置
//async:true(异步)或 false(同步)
xmlHttp.open(method,url,true);
//设置响应的回调 当后台的json返回后 自动调用xhr.onreadystatechange指定的函数
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
//成功后调用第三个函数
callback(xmlHttp.responseText);
}
}
//post 在send里面带参数 get直接带 post一定要设置setRequestHeader
if(method=="POST"){
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send(param);
}else{
xmlHttp.send();
}
}
//和action交互的方法 用于更新
function toUpdate1(){
document.getElementById('updateDiv').style.display='none'
var empno=$('empNoId').value;
var ename=$('updateEname').value;
var job=$('updateJob').value;
var mgr=$('updateMgr').value;
var hiredate=$('updateHiredate').value;
var sal=$('updateSal').value;
var comm=$('updateComm').value;
var deptno=$('updateDeptno').value;
//参数
var param="ename="+ename+"&job="+job+"&mgr="+mgr+"&hiredate="+hiredate+"&sal="+sal+"&comm="+comm+"&deptno="+deptno+"&empno="+empno
//调用ajax好action交互
sendAjax("POST",path+"/updateEmp",function(message){
if(message==1){
alert("操作成功");
toQuery(current);
}else{
alert("操作失败");
}
},param)
}
//和action交互的方法 用于新增
function toAdd(){
document.getElementById('addDiv').style.display='none'
var xmlHttp=new XMLHttpRequest();
var ename=$('a1').value;
var job=$('a2').value;
var mgr=$('a3').value;
var hiredate=$('a4').value;
var sal=$('a5').value;
var comm=$('a6').value;
var deptno=$('a7').value;
var param="ename="+ename+"&job="+job+"&mgr="+mgr+"&hiredate="+hiredate+"&sal="+sal+"&comm="+comm+"&deptno="+deptno;
sendAjax("POST",path+"/insertEmp",function(message){
if(message==1){
alert("操作成功");
toQuery(current);
}else{
alert("操作失败");
}
},param)
}
//和action交互的方法 用于删除
function toDelete(empno){
var param="empno="+empno;
sendAjax("POST",path+"/deleteEmp",function(message){
if(message==1){
alert("操作成功");
toQuery(current);
}else{
alert("操作失败");
}
},param)
}
//分页的一些参数
var current=1;
var sum=0;
var trail=0;
var last=0;
var next=0;
和action交互的方法 用于查询
function toQuery(pagin){
var xmlHttp=new XMLHttpRequest();
var tb=$("tb");
var td=$("td");
var ename=$("ename").value;
xmlHttp.open("GET",path+"/queryPaginEmp?ename="+ename+"&pagin="+pagin,true);
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
//获取action响应的内容
var json=xmlHttp.responseText;
//把它转成json对象
var jsonall=JSON.parse(json);
//给分页的一些参数赋值
current=jsonall.current;
sum=jsonall.sum;
trail=jsonall.trail;
last=jsonall.last;
next=jsonall.next;
$("p1").innerHTML=current;
$("p2").innerHTML=trail;
$("p3").innerHTML=sum;
var jsonObj=jsonall.list;
//无刷新在此查询的时候把整个tbody删除
tb.removeChild(td);
var tdRow=document.createElement("tbody");
tdRow.setAttribute("id","td");
//把tbody加到table里面去
tb.appendChild(tdRow);
for ( var i = 0; i < jsonObj.length; i++) {
var el = jsonObj[i];
//创建节点
var trRow=document.createElement("tr");
var tdRow1=document.createElement("td");
var tdRow2=document.createElement("td");
var tdRow3=document.createElement("td");
var tdRow4=document.createElement("td");
var tdRow5=document.createElement("td");
var tdRow6=document.createElement("td");
var tdRow7=document.createElement("td");
var tdRow8=document.createElement("td");
var tdRow9=document.createElement("td");
tdRow1.innerHTML=el.EMPNO;
tdRow2.innerHTML=el.ENAME;
tdRow3.innerText=el.JOB;
tdRow4.innerText=el.MGR;
tdRow5.innerHTML=el.HIREDATE;
tdRow6.innerHTML=el.SAL;
tdRow7.innerHTML=el.COMM;
tdRow8.innerHTML=el.DEPTNO;
tdRow9.innerHTML="<button οnclick='toDelete("+el.EMPNO+")'>删除</button><button οnclick=toUpdate("+el.EMPNO+",'"+el.ENAME+"','"+el.JOB+"',"+
el.MGR+",'"+el.HIREDATE+"',"+el.SAL+","+el.COMM+","+el.DEPTNO+")>更新</button>";
//把节点tdRow1加到trRow
trRow.appendChild(tdRow1);
trRow.appendChild(tdRow2);
trRow.appendChild(tdRow3);
trRow.appendChild(tdRow4);
trRow.appendChild(tdRow5);
trRow.appendChild(tdRow6);
trRow.appendChild(tdRow7);
trRow.appendChild(tdRow8);
trRow.appendChild(tdRow9);
tdRow.appendChild(trRow);
}
}
}
xmlHttp.send();
}
</script>
</head>
<body οnlοad="toQuery(1)">
<!-- http://localhost:8080/simb/day20170609/emp.jsp -->
ename<input type="text" name="ename" id="ename"/>
<input type="button" value="查询" οnclick="toQuery(current)"/>
<input type="button" value="新增" οnclick="document.getElementById('addDiv').style.display='block'"/><br/>
<table id="tb">
<thead>
<tr>
<td>empno</td>
<td>ename</td>
<td>job</td>
<td>mgr</td>
<td>hiredate</td>
<td>sal</td>
<td>comm</td>
<td>deptno</td>
<td>操作</td>
</tr>
</thead >
<tbody id="td">
</tbody>
</table>
<input type="image" src="${pageContext.request.contextPath}/day20170609/image/18.gif" οnclick="toQuery(1)"/>
<input type="image" src="${pageContext.request.contextPath}/day20170609/image/20.gif" οnclick="toQuery(last)"/>
当前<span id="p1"></span>页 总<span id="p2"></span>页 总:<span id="p3"></span>
<input type="image" src="${pageContext.request.contextPath}/day20170609/image/16.gif" οnclick="toQuery(next)"/>
<input type="image" src="${pageContext.request.contextPath}/day20170609/image/14.gif" οnclick="toQuery(trail)"/>
<!-- 新增的div-->
<div id="addDiv" style="display:none;position: absolute;left: 65%;top: 14%;width: 300px;height:200px;background:linear-gradient(to bottom,skyblue,gray);border: 1px solid black;">
ENAME:<input type='text' name='ename' id='a1'>
<br/>
JOB:<input type='text' name='job' id='a2'>
<br/>
MGR:<input type='text' name='mgr' id='a3'>
<br/>
HIREDATE:<input type='text' name='hiredate' id='a4'>
<br/>
SAL:<input type='text' name='sal' id='a5'>
<br/>
COMM:<input type='text' name='comm' id='a6'>
<br/>
DEPTNO:<input type='text' name='deptno' id='a7'>
<br/>
<input type='button' value="新增" οnclick="toAdd()">
<input type='button' value="关闭" οnclick="document.getElementById('addDiv').style.display='none'">
</div>
<!-- 修改的div-->
<div id="updateDiv" style="display:none;position: absolute;left: 65%;top: 14%;width: 300px;height:200px;background:linear-gradient(to bottom,skyblue,gray);border: 1px solid black;">
<input type='hidden' name='empno' id='empNoId'>
ENAME: <input type='text' id="updateEname" name='ename'>
<br/>
JOB: <input type='text' id="updateJob" name='job'>
<br/>
MGR: <input type='text' id="updateMgr" name='mgr'>
<br/>
HIREDATE: <input type='text' id="updateHiredate" name='hiredate'>
<br/>
SAL: <input type='text' id="updateSal" name='sal'>
<br/>
COMM: <input type='text' id="updateComm" name='comm'>
<br/>
DEPTNO: <input type='text' id="updateDeptno" name='deptno'>
<br/>
<input type='button' value='修改' οnclick="toUpdate1()">
<input type='button' value="关闭" οnclick="document.getElementById('updateDiv').style.display='none'">
</div>
</body>
</html>