
能力说明:
了解变量作用域、Java类的结构,能够创建带main方法可执行的java应用,从命令行运行java程序;能够使用Java基本数据类型、运算符和控制结构、数组、循环结构书写和运行简单的Java程序。
暂时未有相关云产品技术能力~
阿里云技能认证
详细说明AOP的几种通知类型: 1,前置通知(Before advice):在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行 配置文件中使用 <aop:before>进行声明 注解使用 @Before 进行声明 2,后置通知(After advice):当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。 配置文件中使用<aop:after>进行声明 注解使用 @After 进行声明 3,返回后通知(After return advice):在某连接点正常完成后执行的通知,不包括抛出异常的情况。 配置文件中使用<after-returning>进行声明 注解使用 @AfterReturning 进行声明 4,环绕通知(Around advice):包围一个连接点的通知,类似Web中Servlet规范中的Filter的doFilter方法。 可以在方法的调用前后完成自定义的行为,也可以选择不执行。 配置文件中使用<aop:around>进行声明 注解使用 @Around 进行声明 5,抛出异常后通知(After throwing advice):在方法抛出异常退出时执行的通知。 配置文件中使用<aop:after-throwing>进行声明 注解使用 @AfterThrowing 进行声明 需要先引入相关jar包, 如果用Maven则在pom文件中加入下面配置,此时Maven会自动导入相关jar包 <!-- 引入AOP所需要的jar包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.2</version> </dependency> Spring的applicationContext.xml 文件中的配置 这三个是aop的 xmlns:aop=”http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!---注解配置开始 如果使用注解配置Aop则需要配置这两个参数 --> <!-- 激活组件扫描功能,在包cn.ysh.studio.spring.aop及其子包下面自动扫描通过注解配置的组件 --> <!-- <context:component-scan base-package="cn.ysh.studio.spring.aop"/> --> <!-- 激活自动代理功能 --> <!-- <aop:aspectj-autoproxy proxy-target-class="true"/> --> <!---注解配置结束 --> <aop:config> <!-- 声明一个切面,并注入切面Bean,相当于@Aspect --> <aop:aspect id="myAop" ref="auditLogAop"> <!--配置一个切点,相当于@Pointcut * 表示通配所有类型返回值或则没有返回值都可以 com.unionpay.techjoin.common.service..*.*(..) 表示com.unionpay.techjoin.common.service包下所以类 (..)表示所有参数类型 --> <aop:pointcut id="myAuditLog" expression="execution(* com.unionpay.techjoin.common.service..*.*(..))" /> <!--配置环绕通知 相当于@Around--> <aop:around method="addAuditLog" pointcut-ref="myAuditLog"/> </aop:aspect> </aop:config> 如果需要通知中获取Request对象,则需要在web.xml中加入如下配置 <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> 日志实体类 package com.unionpay.techjoin.common.domain; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * 审计日志实体类 * @author mszhou * */ @Entity @Table(name = "tbl_tjmgm_audit_log") public class AuditLog implements Serializable { /** * */ private static final long serialVersionUID = 1L; /**主键id*/ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; /**类别 01表示产品 02表示解决方案 03表示API 04表示FAQ 05表示文档*/ @Column(name = "target_type") private String targetType; /**关联id */ @Column(name = "target_id") private Integer targetId; /**该操作简单的简单描述 如 “admin修改产品” */ @Column(name = "operate_content") private String operateContent; /**操作类别 01表示新增 02表示修改 03表示删除*/ @Column(name = "operate_type") private String operateType; /**操作人Id*/ @Column(name = "operator_id") private String operatorId; /** 操作时间 */ @Column(name = "operate_ts") private Timestamp operateTs; /**操作人的IP*/ @Column(name = "operator_ip") private String operatorIp; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTargetType() { return targetType; } public void setTargetType(String targetType) { this.targetType = targetType; } public Integer getTargetId() { return targetId; } public void setTargetId(Integer targetId) { this.targetId = targetId; } public String getOperateContent() { return operateContent; } public void setOperateContent(String operateContent) { this.operateContent = operateContent; } public String getOperateType() { return operateType; } public void setOperateType(String operateType) { this.operateType = operateType; } public String getOperatorId() { return operatorId; } public void setOperatorId(String operatorId) { this.operatorId = operatorId; } public Timestamp getOperateTs() { return operateTs; } public void setOperateTs(Timestamp operateTs) { this.operateTs = operateTs; } public String getOperatorIp() { return operatorIp; } public void setOperatorIp(String operatorIp) { this.operatorIp = operatorIp; } } 日志Dao类 package com.unionpay.techjoin.common.dao; import java.io.Serializable; import org.springframework.stereotype.Repository; import com.unionpay.techjoin.common.domain.AuditLog; /** * 审计日志Dao * @author mszhou */ @Repository public class AuditLogDao extends HibernateBaseDao<AuditLog,Serializable> { } 日志业务类 package com.unionpay.techjoin.common.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.unionpay.techjoin.common.dao.AuditLogDao; import com.unionpay.techjoin.common.domain.AuditLog; @Service @Transactional public class AuditLogService { @Autowired private AuditLogDao auditLogDao; /** * 新增 * @param auditLog * @author mszhou */ public void add(AuditLog auditLog){ auditLogDao.save(auditLog); } } 切面类 package com.unionpay.techjoin.admin.controller; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Timestamp; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.unionpay.common.authorization.user.UserDetail; import com.unionpay.techjoin.admin.utils.UserInfoUtil; import com.unionpay.techjoin.common.domain.AuditLog; import com.unionpay.techjoin.common.service.AuditLogService; @Component(value="auditLogAop")//实例化注解 public class AuditLogAop { @Autowired private AuditLogService auditLogService; /* *(环绕通知) -日志切点 * 参数 JoinPoint joinPoint * ProceedingJoinPoint是JoinPoint的子类,在环绕通知中用到 * 其它通知则直接用JoinPoint类型参数 * * 环绕通知也可以这样写 * ((ProceedingJoinPoint) joinPoint).proceed(); */ @SuppressWarnings("finally") public Object addAuditLog(ProceedingJoinPoint pjp) throws Throwable{ Object obj=pjp.proceed();//执行方法 //========生成日志开姿============ try{ //得到Request对象 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); if(request!=null){ //pjp.getTarget().getClass().getName()得到请求的Service类全名(包名.类名) //调用方法getTargetType得到类型01表示产品 02表示解决方案 03表示API 04表示FAQ 05表示文档 String targetType =getTargetType(pjp.getTarget().getClass().getName()); //pjp.getSignature().getName()得到请求的方法名 //调用getOperateType方法得到操作类型 01表示新增 02表示修改 03表示删除 String operateType=getOperateType(pjp.getSignature().getName());//方法 if(targetType!=null&&!"".equals(targetType)&&operateType!=null&&!"".equals(operateType)){ //获取当前用户,这里调用了UserInfoUtil工具类 UserDetail user= UserInfoUtil.getUserInfo(request); AuditLog auditLog=new AuditLog();//创建审计日志对象 auditLog.setTargetType(targetType);//设置请求类别 //设置关联Id,这里调用了下面getpArgs方法得到id auditLog.setTargetId(getpArgs(pjp,operateType)); //设置简单操作描述,这里调用了下面getOperateContent方法获得 auditLog.setOperateContent(getOperateContent(user.getUserId(),targetType,operateType)); auditLog.setOperateType(operateType);//设置操作类别 auditLog.setOperatorId(user.getUserId());//设置操作人id auditLog.setOperateTs(new Timestamp(new Date().getTime()));//设置操作时间 //获取请求ip String ip = request.getRemoteAddr(); auditLog.setOperatorIp(ip);//设置操作人ip auditLogService.add(auditLog);//保存审计日志 } } }catch(Exception e){ e.printStackTrace(); }finally{ return obj; } //=======生成日志结束========== } /** * 转换请求类型 01表示产品 02表示解决方案 03表示API 04表示FAQ 05表示文档 * @param className * @return */ private String getTargetType(String className){ String returnType=null; if(className!=null){ String name=className.substring(className.lastIndexOf(".")+1); if(name!=null){ if("ProductService".equals(name)){//01 产品 returnType="01"; }else if("SolutionService".equals(name)){//02 解决方案 returnType="02"; }else if("APIInfoService".equals(name)){//03 API returnType="03"; }else if("FaqService".equals(name)){//04 FAQ returnType="04"; }else if("FileInfoService".equals(name)){//05 文档 returnType="05"; } } } return returnType; } /** * 转换操作类别 01表示新增 02表示修改 03表示删除 * @param methodName * @return */ private String getOperateType(String methodName){ String returnType=null; if(methodName!=null){ if(methodName.startsWith("add")||methodName.startsWith("save")){//01 新增 returnType="01"; }else if(methodName.startsWith("upd")||methodName.startsWith("modify")){//02 修改 returnType="02"; }else if(methodName.startsWith("del")){//03 删除 returnType="03"; } } return returnType; } /** * 获取所有请求参敿 * @param pjp * @return * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ private Integer getpArgs(ProceedingJoinPoint pjp,String operateType) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{ Integer id=0; Object[] objs=pjp.getArgs();//得到所有参数 if(objs==null||objs.length<=0){ return id; } //判断如果是删除,则直接取参数中的第一个参数表示id, //否则通过反射判断对象中是否有getId方法, //如果有则通过反射调用该方法得到对应的id //例如 是新增产品,则得到的是产品id if("03".equals(operateType)){//是删除 Object obj = objs[0];//获取第一个参数 if(obj!=null){//判断不为空 String strNum=obj.toString();//转String if(strNum!=null&&!"".equals(strNum)){ //将id转换成Integer类型 id=new Integer(strNum); } } }else{//不是删除,是增加或修改 for (Object info : objs) {//遍历参数对象 //获取该参数对象的所有方法 Method[] methods = info.getClass().getDeclaredMethods(); //遍历所有方法 for (Method method : methods){ //得到方法名称 String methodName = method.getName(); //判断是否为getId方法 if (methodName!=null&&methodName.endsWith("getId")) { //调用该方法 Object obj = method.invoke(info); //返回值不能空 if(obj!=null){ //转String String strNum=obj.toString(); if(strNum!=null&&!"".equals(strNum)){ //将id转换成Integer类型 id=new Integer(strNum); } } } } } } return id;//返回id } /** * 转换简单的操作描述 * @param targetType * @param operateType * @return */ private String getOperateContent(String userName,String targetType,String operateType){ String result=userName; if("01".equals(operateType)){//01 新增 result+="新增"; }else if("02".equals(operateType)){//02 修改 result+="修改"; }else if("03".equals(operateType)){//03 删除 result+="删除"; } if("01".equals(targetType)){ result+="产品"; }else if("02".equals(targetType)){//02 result+="解决方案"; }else if("03".equals(targetType)){//03 result+="API"; }else if("04".equals(targetType)){//04 result+="FAQ"; }else if("05".equals(targetType)){//05 result+="文档"; } return result; } } 注解方式配置切面类 package com.unionpay.techjoin.admin.controller; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Timestamp; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.unionpay.common.authorization.user.UserDetail; import com.unionpay.techjoin.admin.utils.UserInfoUtil; import com.unionpay.techjoin.common.domain.AuditLog; import com.unionpay.techjoin.common.service.AuditLogService; import org.aspectj.lang.annotation.Aspect @Component(value="auditLogAop")//实例化注解 @Aspect//声明这是一个切面Bean public class AuditLogAop { @Autowired private AuditLogService auditLogService; //配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点 //aspect 该方法名自己取的 @Pointcut("execution(* com.unionpay.techjoin.common.service..*.*(..))") public void aspect(){ } /* * (环绕通知) -日志切点 * 参数 JoinPoint joinPoint * ProceedingJoinPoint是JoinPoint的子类,在环绕通知中用到 * 其它通知则直接用JoinPoint类型参数 * * 环绕通知也可以这样写 * ((ProceedingJoinPoint) joinPoint).proceed(); */ @SuppressWarnings("finally") @Around("aspect()")//配置环绕通知,使用在方法aspect()上注册的切入点 public Object addAuditLog(ProceedingJoinPoint pjp) throws Throwable{ Object obj=pjp.proceed();//执行方法 //========生成日志开姿============ try{ //得到Request对象 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); if(request!=null){ //pjp.getTarget().getClass().getName()得到请求的Service类全名(包名.类名) //调用方法getTargetType得到类型01表示产品 02表示解决方案 03表示API 04表示FAQ 05表示文档 String targetType =getTargetType(pjp.getTarget().getClass().getName()); //pjp.getSignature().getName()得到请求的方法名 //调用getOperateType方法得到操作类型 01表示新增 02表示修改 03表示删除 String operateType=getOperateType(pjp.getSignature().getName());//方法 if(targetType!=null&&!"".equals(targetType)&&operateType!=null&&!"".equals(operateType)){ //获取当前用户,这里调用了UserInfoUtil工具类 UserDetail user= UserInfoUtil.getUserInfo(request); AuditLog auditLog=new AuditLog();//创建审计日志对象 auditLog.setTargetType(targetType);//设置请求类别 //设置关联Id,这里调用了下面getpArgs方法得到id auditLog.setTargetId(getpArgs(pjp,operateType)); //设置简单操作描述,这里调用了下面getOperateContent方法获得 auditLog.setOperateContent(getOperateContent(user.getUserId(),targetType,operateType)); auditLog.setOperateType(operateType);//设置操作类别 auditLog.setOperatorId(user.getUserId());//设置操作人id auditLog.setOperateTs(new Timestamp(new Date().getTime()));//设置操作时间 //获取请求ip String ip = request.getRemoteAddr(); auditLog.setOperatorIp(ip);//设置操作人ip auditLogService.add(auditLog);//保存审计日志 } } }catch(Exception e){ e.printStackTrace(); }finally{ return obj; } //=======生成日志结束========== } /** * 转换请求类型 01表示产品 02表示解决方案 03表示API 04表示FAQ 05表示文档 * @param className * @return */ private String getTargetType(String className){ String returnType=null; if(className!=null){ String name=className.substring(className.lastIndexOf(".")+1); if(name!=null){ if("ProductService".equals(name)){//01 产品 returnType="01"; }else if("SolutionService".equals(name)){//02 解决方案 returnType="02"; }else if("APIInfoService".equals(name)){//03 API returnType="03"; }else if("FaqService".equals(name)){//04 FAQ returnType="04"; }else if("FileInfoService".equals(name)){//05 文档 returnType="05"; } } } return returnType; } /** * 转换操作类别 01表示新增 02表示修改 03表示删除 * @param methodName * @return */ private String getOperateType(String methodName){ String returnType=null; if(methodName!=null){ if(methodName.startsWith("add")||methodName.startsWith("save")){//01 新增 returnType="01"; }else if(methodName.startsWith("upd")||methodName.startsWith("modify")){//02 修改 returnType="02"; }else if(methodName.startsWith("del")){//03 删除 returnType="03"; } } return returnType; } /** * 获取所有请求参敿 * @param pjp * @return * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ private Integer getpArgs(ProceedingJoinPoint pjp,String operateType) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{ Integer id=0; Object[] objs=pjp.getArgs();//得到所有参数 if(objs==null||objs.length<=0){ return id; } //判断如果是删除,则直接取参数中的第一个参数表示id, //否则通过反射判断对象中是否有getId方法, //如果有则通过反射调用该方法得到对应的id //例如 是新增产品,则得到的是产品id if("03".equals(operateType)){//是删除 Object obj = objs[0];//获取第一个参数 if(obj!=null){//判断不为空 String strNum=obj.toString();//转String if(strNum!=null&&!"".equals(strNum)){ //将id转换成Integer类型 id=new Integer(strNum); } } }else{//不是删除,是增加或修改 for (Object info : objs) {//遍历参数对象 //获取该参数对象的所有方法 Method[] methods = info.getClass().getDeclaredMethods(); //遍历所有方法 for (Method method : methods){ //得到方法名称 String methodName = method.getName(); //判断是否为getId方法 if (methodName!=null&&methodName.endsWith("getId")) { //调用该方法 Object obj = method.invoke(info); //返回值不能空 if(obj!=null){ //转String String strNum=obj.toString(); if(strNum!=null&&!"".equals(strNum)){ //将id转换成Integer类型 id=new Integer(strNum); } } } } } } return id;//返回id } /** * 转换简单的操作描述 * @param targetType * @param operateType * @return */ private String getOperateContent(String userName,String targetType,String operateType){ String result=userName; if("01".equals(operateType)){//01 新增 result+="新增"; }else if("02".equals(operateType)){//02 修改 result+="修改"; }else if("03".equals(operateType)){//03 删除 result+="删除"; } if("01".equals(targetType)){ result+="产品"; }else if("02".equals(targetType)){//02 result+="解决方案"; }else if("03".equals(targetType)){//03 result+="API"; }else if("04".equals(targetType)){//04 result+="FAQ"; }else if("05".equals(targetType)){//05 result+="文档"; } return result; } }
写个简单的自动补全,供学习的朋友参考,希望对大家所有帮助 需要先引入jquery,注意自己的引入路径 <script type="text/javascript" src="js/jquery.min.js"></script> <input id="chooseCity" type="text" placeholder="输入城市查询"> 页面初始化时调用下下面方法即可,传两个参数,一个元素id跟数据 $(function(){ var data = ['七里香','站长素材','HTML5特效','wshlfx.com',47,'你在哪','去哪啊'];//所有数据 searchCityLoad("chooseCity",data);//调用初始化方法 chooseCity是input元素id, data是数据, }); 这里是初始化元素的方法,用时只需要调用改方法即可, 参数一 eleId 表示元素id 参数二 arr表示数据 这里的值只有一个,有些需要几个值的,比如显示值跟选择值等,不同需求的话也可根据修改 //========初始化开始======== function searchCityLoad(eleId,arr){ //如果需要动态改变的话, //每次执行前可以先移除事件 //$("#"+eleId).unbind(); //绑定事件 $("#"+eleId).bind('input propertychange',function(){ $("#"+eleId).after('<div style="position:absolute;z-index:9;overflow:hidden;border: 1px solid #cccccc;border-bottom:0;border-top:0;" ></div>'); $("#"+eleId).next('div').width($("#"+eleId).outerWidth()-2);//设置元素宽度 $("#"+eleId).next('div').css({"margin-left":$("#"+eleId).css("margin-left")});//设置元素边距 var arrNew = []; var i; for(i=0;i<arr.length;i++){ var arrItems=arr[i]; //判断元素是否存在于arrNew中, //如果不存在则插入到arrNew的最后 if($.inArray(arrItems,arrNew)==-1) { arrNew.push(arrItems); } } //这是将input中输入的数据有关联的全部加入新生成的div中显示出来 for(i=0;i<arrNew.length;i++){ var arrWord = arrNew[i].toString(); if(((arrWord.indexOf($("#"+eleId).val())) > -1) && ($("#"+eleId).val().length > 0)){ var addArrWord = '<div class="auto-screening-zms" style="cursor:pointer;width:100%;height:30px;line-height:30px;border-bottom:1px solid #cccccc;background:#ffffff;padding: 0 10px;">' + arrWord + "</div>"; $("#"+eleId).next('div').append(addArrWord); } } /*将显示出来的div的内容去重复,input内容变动时去重复*/ $(".auto-screening-zms").each(function(){ if($(this).text().indexOf($("#"+eleId).val()) < 0){ $(this).remove(); }else if($("#"+eleId).val().length == 0){ $("#"+eleId).next('div').addClass("auto-hidden"); $(".auto-screening-zms").remove(); } }); /*弹出的提示div去重复*/ $(".auto-screening-zms").each(function(i, iText){ var iTextHtml = iText.innerHTML; $(".auto-screening-zms").each(function(j, jText){ var jTextHtml = jText.innerHTML; if (i < j && iTextHtml == jTextHtml) { $(this).remove(); } }); }); //元素悬停事件,设置悬停样式 $(".auto-screening-zms").hover(function(){ $(this).css("background","#cccccc"); },function(){ $(this).css("background","#ffffff"); }); /*点击下拉元素传值*/ $(".auto-screening-zms").on("click",function(){ $("#"+eleId).val($(this).text()); $(".auto-screening-zms").remove(); }) }) } //========初始化结束========
首先去下载百度编辑器 引入百度编辑器 <script type="text/javascript" charset="utf-8" src="ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="ueditor.all.min.js"> </script> <!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败--> <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文--> <script type="text/javascript" charset="utf-8" src="lang/zh-cn/zh-cn.js"></script> 可以在这里设置高度及宽度 <script type="text/plain" id="myEditor" style="width:500px;height:500px"></script> 实例化编辑器时,可以不在给定宽高 var ue= UE.getEditor('myEditor'); 也可以给定高度及宽度 var ue = UE.getEditor('myEditor',{ initialFrameWidth :800,//设置编辑器宽度 initialFrameHeight:250,//设置编辑器高度 scaleEnabled:true //scaleEnabled {Boolean} [默认值:false] //是否可以拉伸长高,默认true(当开启时,自动长高失效) }); 还有一种就是直接修改ueditor.config.js 注意:给定initialFrameWidth的优先级比给容器的style优先级要高。
在这写一下JDBC的案例,将JDBC的一些功能演示下,供参考,至于实体类在此我就不写出来了,大家根据需求不同记得导入对应的驱动包到项目中,我这里演示的是以mysql为例,其实区别都不大,如有不对的地方欢迎纠正。 import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import com.mysql.jdbc.PreparedStatement; import java.sql.ResultSet; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Clob; import java.sql.DatabaseMetaData; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Savepoint; public class JDBCDemo { // 数据库地址 localhost表示本地, //3306是mysql默认的端口,db_bank是要链接的数据库 private static String dbUrl="jdbc:mysql://localhost:3306/db_bank"; // 用户名 private static String dbUserName="root"; // 密码 private static String dbPassword="123456"; // 驱动名称 这里是mysql驱动 private static String jdbcName="com.mysql.jdbc.Driver"; //静态块,最优先执行 static{ try{ Class.forName(jdbcName);//加载驱动 }catch(Exception e){ e.printStackTrace();//打印错误信息 } } /** * 获取数据库连接 * @return * @throws Exception */ public static Connection getCon()throws Exception{ //获取数据库链接 Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword); return con; } /** * 关闭数据库连接 * @param con * @param sta * @param rs * @throws Exception */ public static void close(Connection conn,Statement sta,ResultSet rs){ try{ if(rs!=null){ rs.close();//关闭ResultSet } if(sta!=null){ sta.close();//关闭Statement } if(conn!=null){ conn.close();//关闭Connection } }catch(Exception e){ e.printStackTrace();//打印异常信息 } } /** * 新增演示[添加图书] * @param book 要新增的图书对象 * @return 返回受影响的行数 * @throws Exception */ private int addBook(Book book)throws Exception{ Connection con=getCon();//得到数据库链接 //得到PreparedStatement对象 PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, book.getBookName()); // 设置图书名称 pstmt.setFloat(2, book.getPrice()); // 设置图书价格 pstmt.setString(3, book.getAuthor()); // 设置图书作者 pstmt.setInt(4, book.getBookTypeId()); // 设置图书类型Id //--------- 大数据字符集 -------------- InputStream inputStream=new FileInputStream(new File("c:/hello.text"));//得到输入流 //大数据类型,设置图书内容, //这里演示mysql数据库类型是longtext pstmt.setAsciiStream(5,inputStream,context.length()); //----大数据二进制,一般存储图片,视频,音频等 ---- //将图片转为输入流 InputStream inputStream2=new FileInputStream(new File("c:/a.jpg")); //大数据类型,设置封面图片, //这里演示mysql数据库类型是longblod pstmt.setBinaryStream(6, inputStream2, pic.length()); //执行并返回受影响的行数 int result=pstmt.executeUpdate(); if(result>0){//大于0表示新增成功 //获取生成器 ResultSet rs=pstmt.getGeneratedKeys(); if(rs.next()){//判断是否有值 //得到新增数据后的主键值 int key=rs.getInt(1); } } close(con,pstmt,null);//关闭连接 return result; } /** * 修改演示[更新图书] * @param book 要修改的图书对象 * @return 返回受影响的行数 * @throws Exception */ private int updateBook(Book book)throws Exception{ Connection con=getCon();//得到数据库链接 //新增语句 String sql="update t_book set bookName=?,price=?,author=?,bookTypeId=? where id=?"; //得到PreparedStatement对象 PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, book.getBookName());//设置图书名称 pstmt.setFloat(2, book.getPrice());//设置图书价格 pstmt.setString(3, book.getAuthor());//设置图书作者 pstmt.setInt(4, book.getBookTypeId());//设置图书类型Id pstmt.setInt(5, book.getId());//设置要修改的图书id //执行修改并返回受影响的行数 int result=pstmt.executeUpdate(); close(con,pstmt,null);//关闭连接 return result; } /** * 删除演示[删除图书] * @param id 要删除的图书id * @return 返回受影响的行数 * @throws Exception */ private int deleteBook(int id)throws Exception{ Connection con=getCon();//得到数据库链接 String sql="delete from t_book where id=?";//删除语句 //得到PreparedStatement对象 PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setInt(1, id);//设置要删除的图书id //执行删除并返回受影响的行数 int result=pstmt.executeUpdate(); close(con,pstmt,null);//关闭连接 return result; } /** * 查询演示[查询所有图书] * @return 返回list集合 * @throws Exception */ private List<Book> listBook()throws Exception{ List<Book> bookList=new ArrayList<Book>(); Connection con = getCon(); //得到数据库链接 String sql = "select * from t_book";//查询语句 //得到PreparedStatement对象 PreparedStatement pstmt = con.prepareStatement(sql); //执行并返回结果集ResultSet ResultSet rs = pstmt.executeQuery(); while (rs.next()) {//遍历结果集rs.next()返回true表示有数据 int id = rs.getInt("id"); // 获取编号id String bookName = rs.getString("bookName"); // 获取图书名称 bookName float price = rs.getFloat("price"); // 获取图书价格 price String author = rs.getString("author"); // 获取图书作者 author int bookTypeId = rs.getInt("bookTypeId"); // 获取图书类别id //---- 大数据字符集,一般存储大文本等内容 ---- //大数据类型,获取图书内容, //这里演示mysql数据库类型是longtext Clob c=rs.getClob("context"); //转为字符串 String context=c.getSubString(1, (int)c.length()); //---大数据二进制,一般存储图片,视频,音频等 ------- //创建一个输出流, //将数据库中的封面图片保存到该路径中c:/pic.jpg FileOutputStream out=new FileOutputStream(new File("c:/pic.jpg")); //大数据类型,获取封面图片, //这里演示mysql数据库类型是longblod out.write(b.getBytes(1,(int)b.length())); Book book=new Book(id,bookName,price, author,bookTypeId);//封装图书对象 bookList.add(book);//将图书对象保存集合中 } close(con,pstmt,rs);//关闭连接 return bookList; } /** * JDBC调用存储过程演示 * 数据库中有一个存储过程为 pro_getBookNameById * 该存储过程功能是通过编号(id)查询图书名称(bookName) * 该存储过程中有分别有一个输入参数 * 跟一个输出参数(输出参数名称为 bN ) * @param id 图书编号 * @return 返回图书名称 * @throws Exception */ private String getBookNameById(int id) throws Exception{ Connection con=getCon();// 获取数据库连接 //调用存储过程语句,第一个为输入参数, //第二个是输出参数,输出参数名称是bN String sql="{CALL pro_getBookNameById(?,?)}"; //得到CallableStatement对象 CallableStatement cstmt=con.prepareCall(sql); cstmt.setInt(1, id);//设置第一个参数(即输入参数) //设置返回类型(即输出参数类型),指的是数据库中的数据类型 cstmt.registerOutParameter(2, Types.VARCHAR); cstmt.execute();//执行 //获取返回值(即输出参数 bN ) String bookName=cstmt.getString("bN"); close(con,cstmt,null);//关闭连接 return bookName; } /** *元数据演示 */ public void demo () throws Exception { Connection con=getCon();//获取数据库链接对象 //---------- 元数据 ---------------- //获取DatabaseMetaData对象 DatabaseMetaData dmd=con.getMetaData(); //dmd.getDatabaseProductName()获取数据库名称 System.out.println("数据库名称:"+dmd.getDatabaseProductName()); //getDriverMajorVersion()得到数据库大版本号, //dmd.getDriverMinorVersion()得到数据库小版本号 System.out.println("数据库版本:"+dmd.getDriverMajorVersion()+"."+dmd.getDriverMinorVersion()); String sql="select * from t_book";//查询语句 //得到PreparedStatement对象 PreparedStatement pstmt=con.prepareStatement(sql); // 获取元数据列的总数(即有多少列(字段)) int num=rsmd.getColumnCount(); System.out.println("共有"+num+"列"); for(int i=1;i<=num;i++){ //rsmd.getColumnName(i)获取第i列的列名称(即字段名称), //rsmd.getColumnTypeName(i)获取第i列的数据类型 System.out.println(rsmd.getColumnName(i)+"," +rsmd.getColumnTypeName(i)); } } /** * *事务演示 **/ public static void main(String[] args) throws Exception { Connection con=null; Savepoint sp=null; try { con=getCon();//得到数据库连接 //取消自动提交(将事务设置为手动提交) con.setAutoCommit(false); System.out.println("张三开始向李四转账!"); int account=500; outCount(con, "张三", account);//此处假设转出账操作 //演示:设置一个保存点(即数据库的备份点) //sp=con.setSavepoint(); inCount(con, "李四", account);//此处假设转入账操作 System.out.println("转账成功!"); con.commit(); //提交事务 } catch (Exception e) { con.rollback(); //回滚事务 //con.rollback(sp);//回滚事务到sp保存点 e.printStackTrace();//打印错误信息 }finally{ con.close();//关闭连接 } } /** * 假设转出操作 * @param con 数据库连接 * @param accountName 账户 * @param account 金额 * @throws Exception */ private static void outCount(Connection con,String accountName,int account)throws Exception{ String sql="update t_account set accountBalance=accountBalance-account? where accountName=?";// PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setInt(1, account); pstmt.setString(2, accountName); pstmt.executeUpdate(); } /** * 假设转入操作 * @param con 数据库连接 * @param accountName 账户 * @param account 金额 * @throws Exception */ private static void inCount(Connection con,String accountName,int account)throws Exception{ String sql="update t_account set account=accountBalance+account? where accountName=?"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setInt(1, account); pstmt.setString(2, accountName); pstmt.executeUpdate(); } }
写个简单的三级联动案例,以地区来演示,供参考,大家注意下自己的jquery导入路径,如有不对的地方欢迎大家纠正。 <html> <head> <!--导入jquery--> <script type="text/javascript"src="jquery1.7.1.js"> </script> </head> <script type="text/javascript"> $(function(){//页面加载 //页面加载时调用方法,加载所有国家 //查询所有国家,并加载到国家下拉框中 loaddata('gj','查询国家请求的url','查所有id可以给空','省份','国家'); //国家下拉框的值改变事件 $("#gj").change(function(){ //查询当前国家下的所有省份,并加载到省份下拉框中 loaddata('sf','查询省份请求的url','国家id','省份'); } //省份下拉框的值改变事件 $("#sf").change(function(){ //查询当前省份下的所有市,并加载到市下拉框中 loaddata('sj','省份的请求url','省份id','市级'); } }); //数据请求加载方法 //eleid 元素id,url 请求地址,id 父级,type 类型 function loaddata(eleid,url,id,type){ $.ajax({ type:'get', //请求类型,这里是get请求 url:url, //请求地址 data:{id:id}//请求参数 success:function(data){ //请求成功的回调方法 if(type=='国家'){//如果是国家 $("#"+eleid).html("");//先清空国家 $("#sf").html("");//再清空省份 $("#sj").html("");//最后清空市 }else if(type=='省份'){//如果是省 $("#"+eleid).html("");//先清空省份 $("#sj").html("");//再后清空市 }else if(type=='市级'){//如果是市级 $("#"+eleid).html("");//清空市 } $("#"+eleid).append('<option>请选择</option>'); //需要注意的是如果后台传来的data数据不一致, //需先转换成对象再遍历 for(var i=0;i<data.length;i++){ var va=data.选择的值;//获取值 var vashow=data.显示的值;//获取值 var str='<option value="'+va+'">' +vashow+'</option>'; //将数据追加到对应的下拉框中 $("#"+eleid).append(str); } },error:function(){//请求失败回调方法 //请求出错处理 }); } </script> <body> <!--国家下拉框--> <select id="gj"> <option>请选择</option> </select> <!--省份下拉框--> <select id="sf"> <option>请选择</option> </select> <!--市级下拉框--> <select id="sj"> <option>请选择</option> </select> </body> </html>