JAVA参数TRUE/FALSE值

在应用中添加一个关闭音量的按钮,实现功能是,当用户调节框时判断true还是false,然后设置为相反。我觉得只要简单改变SharedPreference的truefalse。

最开始的框架代码如下:

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean cmute = getPrefs.getBoolean("mute", defValue);
if (cmute == true){                     

}
if (cmute == false){

}

后来找到的方法都不够简单:

我改成:

if (cmute == false){


                Editor editor = getPrefs.edit();
                editor.putBoolean("mute", true);
                editor.commit();
                Editor editor2 = getPrefs.edit();
                editor.putBoolean("notice", true);
                editor.commit();



            }
            if (cmute == true){

                Editor editor = getPrefs.edit();
                editor.putBoolean("mute", false);
                editor.commit();
                Editor editor2 = getPrefs.edit();
                editor.putBoolean("notice", false);
                editor.commit();

            }

1个回答

Editor接口

接口可以改变SharedPreference对象的值。

试试下面的代码:

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean cmute = getPrefs.getBoolean("mute", defValue);
Editor editor = getPrefs.edit();
editor.putBoolean("mute", !cmute);
editor.commit();
bluetooth99
bluetooth99 谢了
7 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
bootstrap table怎么想java传参数
这是js ``` function load1() { var state=parent.$("input[name='state']:checked").val(); alert(state) $('#exampleTable') .bootstrapTable( { method : 'get', // 服务器数据的请求方式 get or post url : prefix + "/list", // 服务器数据的加载地址 queryParams:function(params){//向后台传值 return{ offset:params.offset, limit:params.limit, state:parent.$("input[name='state']:checked").val() } }, // showRefresh : true, // showToggle : true, // showColumns : true, iconSize : 'outline', toolbar : '#exampleToolbar', striped : true, // 设置为true会有隔行变色效果 dataType : "json", // 服务器返回的数据类型 pagination : true, // 设置为true会在底部显示分页条 // queryParamsType : "limit", // //设置为limit则会发送符合RESTFull格式的参数 singleSelect : false, // 设置为true将禁止多选 // contentType : "application/x-www-form-urlencoded", // //发送到服务器的数据编码类型 pageSize : 10, // 如果设置了分页,每页数据条数 pageNumber : 1, // 如果设置了分布,首页页码 //search : true, // 是否显示搜索框 showColumns : false, // 是否显示内容下拉框(选择显示的列) sidePagination : "server", // 设置在哪里进行分页,可选值为"client" 或者 "server" queryParams : function(params) { return { //说明:传入后台的参数包括offset开始索引,limit步长,sort排序列,order:desc或者,以及所有列的键值对 limit: params.limit, offset:params.offset, name:$('#searchName').val() // username:$('#searchName').val() }; }, // //请求服务器数据时,你可以通过重写参数的方式添加一些额外的参数,例如 toolbar 中的参数 如果 // queryParamsType = 'limit' ,返回参数必须包含 // limit, offset, search, sort, order 否则, 需要包含: // pageSize, pageNumber, searchText, sortName, // sortOrder. // 返回false将会终止请求 } ``` 这是java ``` @ResponseBody @RequestMapping("/list") public PageUtils list(@RequestParam Map<String, Object> params,String state){ System.out.println(state); //查询列表数据 Query query = new Query(params); List<WagesDO> wagesList = wagesService.list(query); int total = wagesService.count(query); PageUtils pageUtils = new PageUtils(wagesList, total); return pageUtils; } ``` 这样写在java接受到的是state为null,这是为什么y
Java 运行时异常,java.lang.NullPointerException
最近在刚刚学Java,刚刚学完继承和多态,现在在做一个作业遇到了困难。 我简单的说一下,父类Vegetable,子类Tomato继承父类,子类有构造方法Tomato(String name,boolean isProtected,Date d) 这是父类Vegetable的定义: ``` package Pixel; import java.util.Date; public class Vegetable { String name; public int SerialNumber;//每个植物的序列号 public int productivity; static int id=0; Date WhentoGrow; public Vegetable(String name) { this.name=name; id++; } } ``` 子类: ``` package Pixel; import java.text.SimpleDateFormat; import java.text.DecimalFormat; import java.util.Date; public class Tomato extends Vegetable { boolean isProtected=true; public Tomato(String name,boolean Protected,Date d) { super(name); this.WhentoGrow=d; this.SerialNumber=super.id; isProtected=Protected; if(isProtected)productivity=10; else productivity=5; } private long GrowCycle=6*3600*1000 ;//一个番茄长6小时长出 SimpleDateFormat When = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final long millis=WhentoGrow.getTime(); final long harvestmillis=millis+GrowCycle; } ``` 在另一个class中做测试: ``` package Pixel; import java.util.Date; public class test { @SuppressWarnings("deprecation") public static void main(String []args) { Date t1=new Date(120,4,3,19,30,00); Date t2=new Date(120,4,3,19,30,00); //System.out.println(t1.getTime()); Tomato fanqie=new Tomato("fanqie",true,t1); Tomato fanqie2=new Tomato("fanqie",false,t2); } } ``` 通过t1t2做参数d来构造番茄1,番茄二,编辑器此时没有报错,但是当我运行的时候他就报错了,错误信息是java.lang.NullPointerException,并提示问题语句在于Tomato 文件里面的this.WhentoGrow=d这句话。 上网查过了,基本上就是说某个类没有具体实例化,但是我这里的t1,t2都应new过了啊 真的很苦恼,求大神指教啊!
java对象属性的默认值影响sql查询语句的拼接,该如何处理。
1、问题描述: 想做一个通用的sql查询语句,通过传入对象的属性赋值情况,拼接查询语句。比如Admin类,有int id,String name,int age,boolean isLeader 4个属性,如果给Admin的对象的某几个属性赋值,比如:setAge(32);setName(“张”)。那么语句拼接为select * from admin where age=32 and name like '%张%'。我在拼接时本来想通过属性是否为null,或者是否为空字符来判断是否作为查询条件,但是由于默认值的存在,导致拼接错误。 2、代码 ``` /*** * 约定: * 1、类名与表名对应,表名全小写。 * 2、类属性与列名一致。 * 3、ID列的类属性和列名为=表名(第一个字母小写)+“Id” * * 4、暂不支持联表查询。 *类名:BaseDao * ***/ public <T> List<T> query(T t) throws IllegalArgumentException, IllegalAccessException, SQLException{ StringBuilder sql=new StringBuilder(); StringBuilder whereString=new StringBuilder(); List<Object> parameters=new ArrayList<Object>(); Class clazz=t.getClass(); //获取类名 String classSimpleName=clazz.getSimpleName(); //获取表名 String tableName=classSimpleName.toLowerCase(); //拼接select语句前半部分 sql.append("select * from "+tableName); //获取所有类属性 Field[] fields=clazz.getDeclaredFields(); //遍历所有属性 for(Field field:fields) { field.setAccessible(true); //得到属性值 Object fieldValue=field.get(t); if(fieldValue!=null) { //如果属性值不为null,获取属性名(字段名)。 String fieldName=field.getName(); //判断是否为String类型 if(fieldValue instanceof String) { // 如果是String,判断是否为空字符 if(!("".equals(((String)fieldValue).trim()))) { //不是空字符串,作为where条件,并将参数加入列表。 whereString.append(fieldName+" like ? and "); parameters.add("%"+(String)fieldValue+"%"); } }else if("Integer".equals(fieldValue.getClass().getSimpleName())){ /***判断是否为int,如果int>0,认为参数有效---这个也是为了处理默认值为0的情况,想的办法,但是有时候表里面字段值可能<=0,所以我觉得处理得不**好*/ if((int)fieldValue>0) { whereString.append(fieldName+"=? and "); parameters.add(fieldValue); } }else{ /*其他情况直接作为where查询条件,但是运行发现boolean值默认false,也会直接当成是有效条件,影响条件设置*/ whereString.append(fieldName+"=? and "); parameters.add(fieldValue); } } } //判断是否有有效条件,有的话拼接where语句。 if(parameters.size()>0) { whereString.delete(whereString.length()-5, whereString.length()-1); sql.append(" where "); sql.append(whereString); } System.out.println(sql.toString()); System.out.println(parameters); //连接数据库,查询。 QueryRunner qr=JdbcPool.getQueryRunner(); // return null; return qr.query(sql.toString(), new BeanListHandler<T>(clazz), parameters.toArray()); } ``` 3、测试代码 ``` @Test public void BaseDao() throws Exception, IllegalAccessException { IpAddress ipObj=new IpAddress(); //只设置了一个条件。 ipObj.setIpAddress("192.168.1"); BaseDao bd=new BaseDao(); List<IpAddress> list=bd.query(ipObj); for(IpAddress ip:list) { System.out.println(ip); } System.out.println(list.size()); } ``` 4、结果 ``` //在只设置了一个条件的情况下,拼接出两个查询条件。 select * from ipaddress where ipAddress like ? and isReachable=? [%192.168.1%, false] ``` 5、问题: 请问如何处理这种由于对象基本类型默认值,导致的拼接错误的问题?
ajax的xmlhttp就绪码和响应问题
ajax.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax</title> <script> //原生js实现ajax function fun() { //XMLHttpRequest 是 AJAX 的基础。 //1.创建核心对象(根据不同的浏览器版本) var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //2.建立连接 /** * 参数: * 1.请求参数:Get,Post * 2.请求URL * 3.同步或异步,async:true(异步)或 false(同步) */ xmlhttp.open("GET","ajaxServlet?username=tom",true); //get请求参数写在请求URL的后头,xmlhttp.send();空参传递 //3. 发送请求 xmlhttp.send(); //xmlhttp.send("username=tom"); 传递的是post请求所携带的参数 //4.接收处理服务器点的响应 //获取方式xmlhttp.responseText;当xmlhttp就绪状态发生变化时,触发onreadystatechange xmlhttp.onreadystatechange=function() { /** (1)有 XMLHttpRequest 的状态。从 0 到 4 发生变化。 * 0: 请求未初始化 * 1: 服务器连接已建立 * 2: 请求已接收 * 3: 请求处理中 * 4: 请求已完成,且响应已就绪 (2)xmlhttp.status *200: "OK" * 404: 未找到页面 */ if (xmlhttp.readyState==4 && xmlhttp.status==200) { var responseText = xmlhttp.responseText; alert(responseText); } } } </script> </head> <body> <input type="button" value="发送异步请求" onclick="fun()"> <input type="text"> </body> </html> ``` 请求发送到ajaxServlet并携带请求参数, ``` package servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/ajaxServlet") public class AjaxServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取ajax的请求参数 String username = request.getParameter("username"); //处理业务逻辑 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } //2.打印username System.out.println(username); //3.相应 response.getWriter().write("hello : "+username); } } ``` 这里的问题是,ajaxServlet设置了response,为什么ajax.html的alert(responseText);在 xmlhttp.open("GET","ajaxServlet?username=tom",true); //异步 可以弹出 xmlhttp.open("GET","ajaxServlet?username=tom",false); //同步 不可以弹出, F12都可以获取到服务器的响应信息,
java I/O流的问题,请大神指点
源代码如下: package com.Sixping.Ncre07; import java.io.*; import java.util.*; public class RandomFileTest { public static void main(String[] args) { Employee[] staff = new Employee[3]; staff[0] = new Employee("王海", 75000, 1987, 12, 15); staff[1] = new Employee("王明", 50000, 1989, 10, 1); staff[2] = new Employee("周晓", 40000, 1990, 3, 15); try { DataOutputStream out = // 字节文件流。实现了DataOutput接口。以二进制文件输出流为参数 new DataOutputStream(new FileOutputStream("employee.dat")); for (Employee e : staff) e.writeData(out); out.close(); // 以二级制文件为参数,建立RandomAccessFile对象。“r”为“只读” RandomAccessFile in = new RandomAccessFile("employee.dat", "r"); int n = (int) (in.length() / Employee.RECODE_SIZE); Employee[] newStaff = new Employee[n]; for (int i = n - 1; i >= 0; i--) { newStaff[i] = new Employee(); in.seek(i * Employee.RECODE_SIZE); newStaff[i].readData(in); } in.close(); for (Employee e : newStaff) { System.out.println(e); } } catch (Exception e) { e.printStackTrace(); } } } class Employee { public Employee() { } public Employee(String n, double s, int year, int mouth, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, mouth - 1, day); hireDay = calendar.getTime(); } public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } public String toString() { return getClass().getName() + "[name+" + name + ",salary" + salary + ",hireDay=" + hireDay + "]"; } public void writeData(DataOutput out) throws IOException { DataIO.writeFixedString(name, NAME_SIZE, out); out.writeDouble(salary); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(hireDay); out.writeInt(calendar.get(calendar.YEAR)); out.writeInt(calendar.get(calendar.MONTH + 1)); out.writeInt(calendar.get(calendar.DAY_OF_MONTH)); } public void readData(DataInput in) throws IOException { name = DataIO.readFixedString(NAME_SIZE, in); salary = in.readDouble(); int y = in.readInt(); int m = in.readInt(); int d = in.readInt(); GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d); hireDay = calendar.getTime(); } public static final int NAME_SIZE = 40;// 姓名按照40個字符設計 public static final int RECODE_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4; private String name; private double salary; private Date hireDay; } class DataIO { public static String readFixedString(int size, DataInput in) throws IOException { StringBuffer b = new StringBuffer(size);// 较StringBuffer效率更高,但是不支持多线程 int i = 0; boolean more = true; while (more && i < size) { char ch = in.readChar();//将二进制数据转换成字符读出 i++; if (ch == 0) { more = false; } else { b.append(ch); } } in.skipBytes(2 * (size - 1));//跳过无效字符 return b.toString();//将StringBulider对象中的字符串显示出来 } public static void writeFixedString(String s, int size, DataOutput out)throws IOException { for (int i = 0; i < size; i++) { char ch = 0; if (i < s.length()) { ch = s.charAt(i); } out.writeChar(ch); } } } 控制台现实信息如下: java.io.EOFException at java.io.RandomAccessFile.readInt(RandomAccessFile.java:725) at com.Sixping.Ncre07.Employee.readData(RandomFileTest.java:85) at com.Sixping.Ncre07.RandomFileTest.main(RandomFileTest.java:25) 能不能请大神告诉我这是为什么? 请大神介绍介绍经验。
get请求,参数拼接,时间字符串拼接报错,然后大佬们说的我好想不太清楚咋弄,就新添了请求方法,和调用
java.io.IOException: Server returned HTTP response code: 400 for URL: http://api.baidu.com/getsyncusers?code=02&date=2019-10-10 10:16:00.0 at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) at com.dunan.zzjg.util.ApiGateToken.getResponseContext(ApiGateToken.java:115) at com.dunan.zzjg.service.impl.SysUserServiceImpl.setSyncUsers(SysUserServiceImpl.java:82) at com.dunan.zzjg.controller.DAapiController.userDate(DAapiController.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) /** * 根据请求地址及请求参数,获取服务器的相应信息 * * @param requestURL 请求地址 * @param requestParam 请求参数 * @param requestMethod "POST" or "GET" * @return */ public static String getResponseContext(String requestURL, String requestParam, String requestMethod,String token) { StringBuffer responseContext = new StringBuffer(); try { URL url = new URL(requestURL); // 此处的urlConnection对象实际上是根据URL的 URLConnection urlConn = url.openConnection(); urlConn.setConnectTimeout(30000); urlConn.setReadTimeout(30000); // 请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection,故此处最好将其转化 // 为HttpURLConnection类型的对象,以便用到 HttpURLConnection更多的API.如下: HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConn; // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true, 默认情况下是false; httpUrlConnection.setDoOutput(true); // 设置是否从httpUrlConnection读入,默认情况下是true; httpUrlConnection.setDoInput(true); // Post 请求不能使用缓存 httpUrlConnection.setUseCaches(false); // 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type","application/json"); // 设置 HttpURLConnection的字符编码 httpUrlConnection.setRequestProperty("Accept-Charset", "UTF-8"); if(StringUtils.isNotBlank(token)){ httpUrlConnection.setRequestProperty("Access-Token", token); } // 设定请求的方法为"POST",默认是GET httpUrlConnection.setRequestMethod(requestMethod); // 连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成, // // 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, // // 所以在开发中不调用上述的connect()也可以)。 if("POST".equals(requestMethod)){ OutputStream outStrm = httpUrlConnection.getOutputStream(); outStrm.write(requestParam.getBytes("UTF-8")); // // 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream) outStrm.flush(); // 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中, // 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器 outStrm.close(); } // 调用HttpURLConnection连接对象的getInputStream()函数, // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。 InputStream inStrm = httpUrlConnection.getInputStream(); // 读取文件流程 BufferedReader rd = new BufferedReader( new InputStreamReader(inStrm,"UTF-8")); // 采取行的方式进行读取 String tempLine = rd.readLine(); // 循环获取每一行数据 while (tempLine != null) { responseContext.append(tempLine); tempLine = rd.readLine(); } rd.close(); inStrm.close(); httpUrlConnection.disconnect(); httpUrlConnection = null; urlConn = null; url = null; } catch (Exception e) { e.printStackTrace(); } return responseContext.toString(); } /*获取上次更新的时间*/ TurnoverTime lastTime = timeMapper.selectTime(); String lastUpdateTime = lastTime.getLastUpdateTime(); System.out.println(lastUpdateTime); String url = "http://api.baidu.com/getsyncusers"; String param = "?code="+"02"+"&date="+lastUpdateTime; String requestMethod = "GET"; String token = ApiGateToken.getToken(); String responseContext = ApiGateToken.getResponseContext(url+param, param, requestMethod, token);
为什么我的zuul配置的拦截器没有生效?
``` public class LoginFilter extends ZuulFilter { @Override // 过滤器的类型 pre route post error public String filterType() { return "pre"; } @Override // 执行顺序,返回值越小,优先级越高,为防止以后有更优先的过滤器,可以先写10 public int filterOrder() { return 0; } @Override // 是否执行该过滤器 public boolean shouldFilter() { return true; } @Override // 编写过滤器的业务逻辑 public Object run() throws ZuulException { // 初始化context上下文对象, 不像以前的 servlet spring RequestContext context = RequestContext.getCurrentContext(); // 获取request对象 HttpServletRequest request = context.getRequest(); // 获取参数 String token = request.getParameter("token"); System.out.println("token="+token); if(StringUtils.isBlank(token)){ // 为空,拦截,不转发请求 context.setSendZuulResponse(false); // 返回状态 成功/失败 context.setResponseStatusCode(401); // 设置响应提示 context.setResponseBody("requset error!"); } return null; // 返回值为null,代表该过滤器什么都不做 } } ``` ++++++++++ yml配置文件 ``` server: port: 10010 spring: application: name: my-zuul zuul: routes: service-provider: # 路由名称,随便写,一般是服务名 path: /service-provider/** # 包含这个路径的,跳转到下面的链接 # url: http://localhost:8086 serviceId: service-provider service-consumer: /c/** host: connect-timeout-millis: 3000 socket-timeout-millis: 3000 prefix: /api # 路由前缀 eureka: client: register-with-eureka: true fetch-registry: true # 这两句, 写成true error:Cannot execute request on any known server # 写成false error:Load balancer does not have available server for client service-url: defaultZone: http://localhost:10086/eureka ribbon: ReadTimeout: 12000 ConnectTimeout: 12000 eureka: enabled: true ``` ![图片说明](https://img-ask.csdn.net/upload/202001/05/1578194627_957484.png) ++++++++ ![图片说明](https://img-ask.csdn.net/upload/202001/05/1578194683_29110.png)
使用java的Http请求里的Url对象调用第三方接口返回的数据中文乱码
URL url = new URL("http://apis.5118.com/morerank/baidupc"); // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接) // 此时cnnection只是为一个连接对象,待连接中 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数) connection.setDoOutput(true); // 设置连接输入流为true connection.setDoInput(true); // 设置请求方式为post connection.setRequestMethod("POST"); connection.setRequestProperty("Charsert", "UTF-8"); //设置请求编码 // post请求缓存设为false connection.setUseCaches(false); // 设置该HttpURLConnection实例是否自动执行重定向 connection.setInstanceFollowRedirects(true); // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数) // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据 // ;charset=utf-8 必须要,不然妙兜那边会出现乱码【★★★★★】 //addRequestProperty添加相同的key不会覆盖,如果相同,内容会以{name1,name2} connection.addRequestProperty("from", "sfzh"); //来源哪个系统 //setRequestProperty添加相同的key会覆盖value信息 //setRequestProperty方法,如果key存在,则覆盖;不存在,直接添加。 //addRequestProperty方法,不管key存在不存在,直接添加。 connection.setRequestProperty("Authorization", " APIKEY D9FD7C014E8E4367B2891EF5B4B493"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行) connection.connect(); // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容) DataOutputStream dataout = new DataOutputStream(connection.getOutputStream()); // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444 String parm = "taskid="+taskid; System.out.println("传递参数:" + parm); // 将参数输出到连接 dataout.writeBytes(parm); // 输出完成后刷新并关闭流 dataout.flush(); dataout.close(); // 重要且易忽略步骤 (关闭流,切记!) //System.out.println(connection.getResponseCode()); // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader) BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; StringBuilder sb = new StringBuilder(); // 用来存储响应数据 // 循环读取流,若不到结尾处 while ((line = bf.readLine()) != null) { //sb.append(bf.readLine()); String lin=new String(line.getBytes(), "utf-8"); sb.append(lin); } bf.close(); // 重要且易忽略步骤 (关闭流,切记!) connection.disconnect(); // 销毁连接 return sb.toString(); 返回的数据中文乱码使用java的Http请求里的Url对象调用第三方接口返回的数据中文乱码
Ext 不同的2个window里的元素重叠
2个Ext的window,代码如下: 第一个 [code="java"] queryWin1 = new Ext.Window({ closeAction: 'hide',// 关闭窗口是销毁窗口,为'hide'则隐藏,close销毁 closable: true,//是否可关闭 maximizable : false,//是否可最大化 minimizable : false,//是否可最小化 draggable:false,//拖动 resizable:false, //变大小 constrainHeader:true,//窗口顶部不能超出浏览器边界 id:'thisID2', modal: true,//为模式窗口,后面的内容都不能操作(屏蔽) title:'批量设置', width:300, height:220, layout:'fit', items:fsf1, buttonAlign:'center', [/code] 第二个 [code="java"] queryWin = new Ext.Window({ closeAction: 'hide',// 关闭窗口是销毁窗口,为'hide'则隐藏,close销毁 closable: true,//是否可关闭 id:'thisID1', maximizable : false,//是否可最大化 minimizable : false,//是否可最小化 draggable: true,//拖动 resizable: true, //变大小 constrainHeader:true,//窗口顶部不能超出浏览器边界 modal: true,//为模式窗口,后面的内容都不能操作(屏蔽) title:'查询参数', width:370, height:390, layout:'fit', items:fsf, buttonAlign:'center', buttons:[{ [/code] 加载时候2个都打开一下,没有问题, 但是之后再打开就会出现如图的情况。 求各位大大指教~
java的类型转换报错,显示类型不匹配
``` package com.example.weather; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import java.util.jar.Attributes; /** * 网络访问工具类 * @author silk * */ public class PostGet { /** * get方法直接调用post方法 * @param url 网络地址 * @return 返回网络数据 */ public static String get(String url){ return post(url,null); } /** * 设定post方法获取网络资源,如果参数为null,实际上设定为get方法 * @param url 网络地址 * @param param 请求参数键值对 * @return 返回读取数据 */ public static String post(String url,Map param){ HttpURLConnection conn=null; try { URL u=new URL(url); conn=(HttpURLConnection) u.openConnection(); //返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。 StringBuffer sb = null; if(param!=null){//如果请求参数不为空 sb=new StringBuffer(); /*A URL connection can be used for input and/or output. Set the DoOutput * flag to true if you intend to use the URL connection for output, * false if not. The default is false.*/ //默认为false,post方法需要写入参数,设定true conn.setDoOutput(true); //URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出, //则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。 //设定post方法,默认get conn.setRequestMethod("POST"); //获得输出流 OutputStream out=conn.getOutputStream(); //对输出流封装成高级输出流 BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out)); //将参数封装成键值对的形式 for(Map.Entry s:param.entrySet()){ sb.append(s.getKey()).append("=").append(s.getValue()).append("&"); } //将参数通过输出流写入 writer.write(sb.deleteCharAt(sb.toString().length()-1).toString()); writer.close();//一定要关闭,不然可能出现参数不全的错误 sb=null; } conn.connect();//建立连接 sb=new StringBuffer(); //获取连接状态码 int recode=conn.getResponseCode(); BufferedReader reader=null; if(recode==200){ //Returns an input stream that reads from this open connection //从连接中获取输入流 InputStream in=conn.getInputStream(); //对输入流进行封装 reader=new BufferedReader(new InputStreamReader(in)); String str=null; sb=new StringBuffer(); //从输入流中读取数据 while((str=reader.readLine())!=null){ sb.append(str).append(System.getProperty("line.separator")); } //关闭输入流 reader.close(); if (sb.toString().length() == 0) { return null; } return sb.toString().substring(0, sb.toString().length() - System.getProperty("line.separator").length()); } } catch (Exception e) { e.printStackTrace(); return null; }finally{ if(conn!=null)//关闭连接 conn.disconnect(); } return null; } } ``` 隔空的for循环行报错:类型不匹配:不能从元素类型 Object 转换为 Map.Entry 不知如何解决 以及为何会报错。望解惑 万分感谢!
配置shiro后,启动时出现 is not eligible for getting processed by all BeanPostProcessors
想要学习一下shiro权限管理,在网上一边学习一边实操,但配好之后认证登录没问题,但拦截和授权却不见作用。并在启动时出现如下: >INFO 11364 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'shiroConfig' of type [com.bdg.go.config.ShiroConfig$$EnhancerBySpringCGLIB$$de04983d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) >…… 在启动项目时,shiroConfig下的所有bean都出现了以上提示: ![图片说明](https://img-ask.csdn.net/upload/202004/03/1585894947_634084.png) 在网上查了很多,基本意思就是说Bean的提前注入造成的,但我研究半天依然不知道如何解决。所以跪求大神教学。 项目是spring boot 2.0+ shiroConfig如下: ``` java @Configuration @Slf4j public class ShiroConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.password}") private String password; @Bean public FilterRegistrationBean delegatingFilterProxy(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); DelegatingFilterProxy proxy = new DelegatingFilterProxy(); proxy.setTargetFilterLifecycle(true); proxy.setTargetBeanName("shiroFilter"); filterRegistrationBean.setFilter(proxy); return filterRegistrationBean; } /* * 创建ShrioFilterFactoryBean */ @Bean("shiroFilter") public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); log.info("经过过滤器"); // 过滤器 // 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 Map<String, String> filterMap = new LinkedHashMap<>(); /* * Shiro内置过滤器,可以实现权限相关的拦截器,常用的有: * anon:无需认证(登录)即可访问 * authc:必须认证才可以访问 * user:如果使用rememberme的功能可以直接访问 * perms:该资源必须得到资源权限才能访问 * role:该资源必须得到角色资源才能访问 */ //放过登录请求 filterMap.put("/login", "anon"); filterMap.put("/**", "authc");//其他资源全部拦截 filterMap.put("/logout", "logout"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap); shiroFilterFactoryBean.setLoginUrl("/login"); return shiroFilterFactoryBean; } @Bean("securityManager") public DefaultWebSecurityManager securityManager( @Qualifier("cookieRememberMeManager")CookieRememberMeManager cookieRememberMeManager, @Qualifier("redisCacheManager")RedisCacheManager redisCacheManager, @Qualifier("sessionManager")SessionManager sessionManager, @Qualifier("userRealm")UserRealm userRealm){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //注入rememberme对象 securityManager.setRememberMeManager(cookieRememberMeManager); //注入session securityManager.setSessionManager(sessionManager); //注入缓存管理对象 securityManager.setCacheManager(redisCacheManager); //将Realm注入SecurityManager securityManager.setRealm(userRealm); return securityManager; } @Bean("userRealm") public UserRealm userRealm(@Qualifier("hashedCredentialsMatcher")HashedCredentialsMatcher hashedCredentialsMatcher){ UserRealm userRealm = new UserRealm(); //设置解密规则 userRealm.setCredentialsMatcher(hashedCredentialsMatcher); userRealm.setCachingEnabled(false); return userRealm; } @Bean("hashedCredentialsMatcher") public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5"); hashedCredentialsMatcher.setHashIterations(1); return hashedCredentialsMatcher; } @Bean("sessionManager") public SessionManager sessionManager(@Qualifier("redisSessionDAO")RedisSessionDAO redisSessionDAO){ MySessionManager mySessionManager = new MySessionManager(); mySessionManager.setSessionIdUrlRewritingEnabled(false); //取消登陆跳转URL后面的jsessionid参数 mySessionManager.setSessionDAO(redisSessionDAO); mySessionManager.setGlobalSessionTimeout(-1);//不过期 return mySessionManager; } @Bean("redisManager") public RedisManager redisManager(){ RedisManager redisManager = new RedisManager(); redisManager.setHost(host+":"+port); redisManager.setTimeout(timeout); redisManager.setPassword(password); return redisManager; } @Bean("redisCacheManager") public RedisCacheManager redisCacheManager(@Qualifier("redisManager")RedisManager redisManager){ RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager); return redisCacheManager; } @Bean("redisSessionDAO") public RedisSessionDAO redisSessionDAO(){ RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); return redisSessionDAO; @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } @Bean("rememberMeCookie") public SimpleCookie rememberMeCookie() { log.info("ShiroConfiguration.rememberMeCookie()============="); SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); simpleCookie.setMaxAge(259200); return simpleCookie; } @Bean("cookieRememberMeManager") public CookieRememberMeManager cookieRememberMeManager(@Qualifier("rememberMeCookie")SimpleCookie rememberMeCookie) { log.info("ShiroConfiguration.rememberMeManager()========"); CookieRememberMeManager manager = new CookieRememberMeManager(); manager.setCookie(rememberMeCookie); return manager; } } ``` UserRealm: ``` @Slf4j public class UserRealm extends AuthorizingRealm { @Autowired private UserService userService; @Autowired private RoleService roleService; @Autowired private PrivilegeService privilegeService; /** * 前置处理非空对象 * shiroFilter在Spring自动装配bean之前实例化 * 相关联的Bean都被初始化完成且没有被代理(包括BeanPostProcessor也会无效)导致事务失效等...... * 使用动态获取代理对象即可解决 */ protected void preHandleNull() { if (userService == null) { userService = SpringContextUtils.getContext().getBean(UserService.class); } if (roleService == null) { roleService = SpringContextUtils.getContext().getBean(RoleService.class); } if (privilegeService == null) { privilegeService = SpringContextUtils.getContext().getBean(PrivilegeService.class); } } /* * 执行授权逻辑:因为设计每个用户只有一个角色,所以roleMapper.getRoleByUserName(user)返回值只有一个实体。 * @author Innocence */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { preHandleNull(); log.info("自定义UserRealm执行授权逻辑开始=================="); User user = (User) principalCollection.getPrimaryPrincipal(); if (null != user) { List<String> roleLists = new ArrayList<>(); List<String> privilegeLists = new ArrayList<>(); Role role = (Role) roleService.findRoleByUserName(user.getUsername()).getData(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); roleLists.add(role.getName()); info.addRoles(roleLists); List<Privilege> privilegeByRoleId = (List<Privilege>) privilegeService.getPrivilegeByRoleId(role).getData(); for (Privilege privilege : privilegeByRoleId) { privilegeLists.add(privilege.getPrivilegeName()); } info.addStringPermissions(privilegeLists); return info; } return null; } /* * 执行认证逻辑 * @author Innocence */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { preHandleNull(); log.info("自定义UserRealm执行认证逻辑开始=================="); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = token.getUsername(); User userInfo = (User) userService.findUserInfoByUserName(username).getData(); if (userInfo == null) { return null; } log.info("通过用户名查到的用户信息userInfo:[" + userInfo.toString() + "]"); return new SimpleAuthenticationInfo( userInfo, userInfo.getPassword(), getName() ); } } ```
tomcat启动 c3p0死锁 ,测试,预发布没问题,生产环境启动c3p0死锁
2020-02-11 18:55:50.449  WARN c     : com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6a749e11 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks! 2020-02-11 18:55:50.452  WARN [C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-AdminTaskTimer] c.m.v.a.ThreadPoolAsynchronousRunner     : com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6a749e11 -- APPARENT DEADLOCK!!! Complete Status:      Managed Threads: 3     Active Threads: 3     Active Tasks:          com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@258e6714             on thread: C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#0         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@6bc4e1a2             on thread: C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#1         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@146123e0             on thread: C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#2     Pending Tasks:          com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@13c1fbf0         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@45a1985b         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@924a8bc         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@1447f45b         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@8c59358         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@41efa15b         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@6da29092 Pool thread stack traces:     Thread[C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#1,5,main]         java.net.SocketInputStream.socketRead0(Native Method)         java.net.SocketInputStream.socketRead(SocketInputStream.java:116)         java.net.SocketInputStream.read(SocketInputStream.java:170)         java.net.SocketInputStream.read(SocketInputStream.java:141)         com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:100)         com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:143)         com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:173)         com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2954)         com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:560)         com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1014)         com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2255)         com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2106)         com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2090)         com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)         com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)         sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)         sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)         sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)         java.lang.reflect.Constructor.newInstance(Constructor.java:423)         com.mysql.jdbc.Util.handleNewInstance(Util.java:404)         com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)         com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)         com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175)         com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220)         com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206)         com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203)         com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1176)         com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1163)         com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44)         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1908)         com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696)     Thread[C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#0,5,main] <?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:context="http://www.springframework.org/schema/context" 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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <context:property-override location="classpath:config/properties/connection.properties" /> <!-- ================================= 数据源配置 ============================================= --> <bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource"/> <bean id="dataSource101" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--preparedStatement 不会在数据库被 cached导致 连接数的被占用,checkoutOut的时候超时--> <property name="maxStatements" value="0"/> </bean> <bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource"/> <bean id="dataSource3" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--preparedStatement 不会在数据库被 cached导致 连接数的被占用,checkoutOut的时候超时--> <property name="maxStatements" value="0"/> </bean> <!-- define the SqlSessionFactory --> <bean id="sessionFactory1" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource1"/> <property name="configLocation" value="classpath:config/mybatis/mybatis-Configuration.xml"/> <property name="mapperLocations"> <array> <value>classpath*:mapper/*Mapper.xml</value> </array> </property> </bean> <bean id="sessionFactory101" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource101"/> <property name="configLocation" value="classpath:config/mybatis/mybatis-Configuration.xml"/> <property name="mapperLocations"> <array> <value>classpath*:mapper/*Mapper.xml</value> </array> </property> </bean> <bean id="sessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource2"/> <property name="configLocation" value="classpath:config/mybatis/mybatis-Configuration.xml"/> <property name="mapperLocations"> <array> <value>classpath*:mapper/*Mapper.xml</value> </array> </property> </bean> <bean name="transactionManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource1"/> </bean> <bean name="transactionManager101" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource101"/> </bean> <bean name="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource2"/> </bean> <tx:annotation-driven transaction-manager="transactionManager1" /> <tx:annotation-driven transaction-manager="transactionManager101" /> <tx:annotation-driven transaction-manager="transactionManager2" /> <!-- 开启AOP 如果pointcut指向 controller则需要在springmvc的配置文件中配置 --> <aop:aspectj-autoproxy/> <tx:advice id="txAdvice" transaction-manager="transactionManager1"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config expose-proxy="true"> <!-- 第一个*代表所有的返回值类型 第一个.代表子包 第二个*代表所有的类 第三个*代表类所有方法 第一个..代表所有的参数 --> <aop:pointcut id="txPointcut" expression="execution(* app.service..*.*(..))" /> <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice --> <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/> </aop:config> </beans> ##DB config dataSource1.driverClass=com.mysql.jdbc.Driver dataSource1.jdbcUrl=url dataSource1.user= dataSource1.password= dataSource1.testConnectionOnCheckout=true dataSource1.maxPoolSize=200 dataSource1.minPoolSize=10 dataSource1.initialPoolSize=10 dataSource1.checkoutTimeout=30000 dataSource1.maxIdleTime=30 dataSource1.maxStatements=0 dataSource1.maxStatementsPerConnection=0 dataSource101.driverClass=com.mysql.jdbc.Driver dataSource101.jdbcUrl=url dataSource101.user= dataSource101.password= dataSource101.testConnectionOnCheckout=true dataSource101.maxPoolSize=200 dataSource101.minPoolSize=10 dataSource101.initialPoolSize=10 dataSource101.checkoutTimeout=30000 dataSource101.maxIdleTime=30 dataSource101.maxStatements=0 dataSource101.maxStatementsPerConnection=0 dataSource2.driverClass=com.mysql.jdbc.Driver dataSource2.jdbcUrl=jdbc:mysql://localhost:3306/aaa?useSSL=true&useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false dataSource2.user= dataSource2.password= dataSource2.testConnectionOnCheckout=true dataSource2.maxPoolSize=200 dataSource2.minPoolSize=10 dataSource2.initialPoolSize=10 dataSource2.checkoutTimeout=30000 dataSource2.maxIdleTime=30 dataSource2.maxStatements=0 dataSource2.maxStatementsPerConnection=0 dataSource3.driverClass=com.mysql.jdbc.Driver dataSource3.jdbcUrl=jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false dataSource3.user= dataSource3.password= dataSource3.testConnectionOnCheckout=true dataSource3.maxPoolSize=10 dataSource3.minPoolSize=5 dataSource3.initialPoolSize=5 dataSource3.checkoutTimeout=30000 dataSource3.maxIdleTime=30 dataSource3.maxStatements=0 dataSource3.maxStatementsPerConnection=0
jsvalidation用法,小白提问!!
1、使用jsvalidation没效果,点击表单提交没验证直接到了下一页,按F12显示 HTTP404: 找不到 - 服务器尚未找到与请求的 URI (统一资源标识符)匹配的任何内容。 GET - http://localhost:8081/js/validation-framework.js 不知道啥原因,jsvalidation的三个dtd xml 和js代码是老师给的,说是要写一个什么正则表达式,不会改 求解答 2 查过资料 web。xml中没有设置那个什么过滤那个 3下面是framework。js的代码,看不懂 ``/* * JavaScript Validation Framework * * Author: Michael Chen(mechiland) on 2004/03 * This software is on the http://www.cosoft.org.cn/projects/jsvalidation * for update, bugfix, etc, you can goto the homepage and submit your request * and question. * Apache License 2.0 * You should use this software under the terms. * * Please, please keep above words. At least ,please make a note that such as * "This software developed by Michael Chen(http://www.jzchen.net)" . * $Id: validation-framework.js,v 1.7 2004/04/30 05:33:29 jzchen Exp $ */ /** Config Section, Config these fields to make this framework work. **/ // If there is only one config file in your system, use this property. otherwise, use // ValidationFramework.init("configfile") // instead. var ValidationRoot = "/LoginServletProjectFour/js/"; // the field style when validation fails. it aim to provide more beautiful UI and more good // experience to the end-user. // NOTE: this will be buggy. Please report the error to me. var ValidationFailCssStyle = "border:2px solid #FFCC88;"; //Validation function. The entry point of the framework. function doValidate(formRef) { try { var formId = formRef; if (typeof (formRef) == "string") { formId = formRef; } else if (typeof (formRef) == "object") { formId = formRef.getAttribute("id"); } var form = FormFactory.getFormFromId(formId); if (form != null) { return ValidationFramework.validateForm(form); } else { return false; } } catch (e) { ValidationFramework.exception(e.name+":" +e.description); return false; } } /**===================================================================**/ /* * JSValidation Framework Code Started * * Please do not modify the code unless you are very familiar with JavaScript. * The best way to solve problem is report the problem to our project page. * url: http://cosoft.org.cn/projects/jsvalidation */ // The Xml document. To process cross-browser. Thanks Eric. function XmlDocument() {} XmlDocument.create = function () { if (document.implementation && document.implementation.createDocument) { return document.implementation.createDocument("", "", null); } else if (window.ActiveXObject) { try { var prefix = ["MSXML2", "MSXML", "Microsoft", "MSXML3"]; for (var i = 0; i < prefix.length; i++) { //return new ActiveXObject(prefix[i] + ".DomDocument"); var obj = new ActiveXObject(prefix[i] + ".DomDocument"); if (obj == null || typeof(obj) == 'undefined') { continue; } else { return obj; } } } catch (e) { //^_^ throw new Error("My God, What version of IE are you using? IE5&+ is requiered."); } } else throw new Error("Cannot create DOM Document!"); } function ValidationFramework() {} ValidationFramework._validationCache = null; ValidationFramework._currentForm = null; ValidationFramework._userLanguage="auto"; /** * Validate a form. * NOTE: the form is Framework virture form, not the HTML Form. * Html Form can be transform to Virture form by * FormFactory.getFormFromId(htmlFormId); * See the doc for more information. * @param form the virtual form. */ ValidationFramework.validateForm = function(fform) { ValidationFramework._currentForm = fform; var failFields = []; var id = fform.getId(); var showError = fform.getShowError(); var showType = fform.getShowType(); var br = null; if (showError != "alert") { br = "<br />"; } else { br = "\n"; } var errorStrArray = []; var ret = false; var formObj = document.getElementById(id); var fields = fform.getFields(); var rightnum = 0; for (var i = 0; i < fields.length; i++) { var retVal = ValidationFramework.validateField(fields[i]); var fo=formObj[fields[i].getName()]; if (typeof (fo) !='undefined' && fo != null && typeof(fo.type) != "undefined") { fo.style.cssText = ""; } if (retVal != "OK") { errorStrArray[errorStrArray.length] = retVal; failFields[failFields.length] = formObj[fields[i].getName()]; } else { rightnum ++; } } if (rightnum == fields.length) { ret = true; } if (errorStrArray.length > 0) { if (showError == "alert") { if (showType == "first") { alert(errorStrArray[0]); } else { alert(errorStrArray.join(br)); } } else { var errObj = document.getElementById(showError); if (showType == "first") { errObj.innerHTML = errorStrArray[0]; } else { errObj.innerHTML = errorStrArray.join(br); } } if (typeof (failFields[0]) !='undefined' && failFields[0] != null && typeof(failFields[0].type) != "undefined") { failFields[0].focus(); } for (var i = 0; i < failFields.length; i++) { var o = failFields[i]; if ( typeof (o) !='undefined' && o != null && typeof(o.type) != "undefined") { o.style.cssText = ValidationFailCssStyle; } } } return ret; } /** * Validation the field * @param filed the field you want to validate. */ ValidationFramework.validateField = function(field) { var depends = field.getDepends(); var retStr = "OK"; for (var i = 0; i < depends.length; i++) { if (!ValidationFramework.validateDepend(field, depends[i])) { retStr = ValidationFramework.getErrorString(field, depends[i]); return retStr; //Break; } } return retStr; } /** * Validate the field depend. * This function dispatch the various depends into ValidateMethodFactory.validateXXX */ ValidationFramework.validateDepend = function(field, depend) { if (depend.getName() == "required") { return ValidateMethodFactory.validateRequired(field, depend.getParams()); } else if (depend.getName() == "integer") { return ValidateMethodFactory.validateInteger(field, depend.getParams()); } else if (depend.getName() == "double") { return ValidateMethodFactory.validateDouble(field, depend.getParams()); } else if (depend.getName() == "commonChar") { return ValidateMethodFactory.validateCommonChar(field, depend.getParams()); } else if (depend.getName() == "chineseChar") { return ValidateMethodFactory.validateChineseChar(field, depend.getParams()); } else if (depend.getName() == "minLength") { return ValidateMethodFactory.validateMinLength(field, depend.getParams()); } else if (depend.getName() == "maxLength") { return ValidateMethodFactory.validateMaxLength(field, depend.getParams()); } else if (depend.getName() == "email") { return ValidateMethodFactory.validateEmail(field, depend.getParams()); } else if (depend.getName() == "date") { return ValidateMethodFactory.validateDate(field, depend.getParams()); } else if (depend.getName() == "time") { return ValidateMethodFactory.validateTime(field, depend.getParams()); } else if (depend.getName() == "mask") { return ValidateMethodFactory.validateMask(field, depend.getParams()); } else if (depend.getName() == "integerRange") { return ValidateMethodFactory.validateIntegerRange(field, depend.getParams()); } else if (depend.getName() == "doubleRange") { return ValidateMethodFactory.validateDoubleRange(field, depend.getParams()); } else if (depend.getName() == "equalsField") { return ValidateMethodFactory.validateEqualsField(field, depend.getParams()); } else { ValidationFramework.exception("还未实现该依赖: " + depend.getName()); return false; } } // hold the current config file var _validationConfigFile = ""; ValidationFramework.getDocumentElement = function() { if (ValidationFramework._validationCache != null) { return ValidationFramework._validationCache; } var file = ""; if (_validationConfigFile != "") { file = _validationConfigFile; } else { file = ValidationRoot + "validation-config.xml"; } var xmlDoc = XmlDocument.create(); xmlDoc.async = false; // Damn!!! it cost me half an hour to fix it! xmlDoc.load(file); if (xmlDoc.documentElement == null) { ValidationFramework.exception("配置文件读取错误,请检查。"); return null; } // TODO: parse the document if it's a valid document. ValidationFramework._validationCache = xmlDoc.documentElement; var lang=ValidationFramework._validationCache.getAttribute("lang"); ValidationFramework._userLanguage = (lang==null) ? "auto" : lang; return ValidationFramework._validationCache; } ValidationFramework.init = function(configFile) { _validationConfigFile = configFile; ValidationFramework.getDocumentElement(); } ValidationFramework.getAllForms = function() { var vforms = []; var root = ValidationFramework.getDocumentElement(); if (root != null) { var fs = root.childNodes; for (var i = 0;i < fs.length ;i++ ) { vforms[i] = new ValidationForm(fs.item(i)); } } return vforms; } ValidationFramework.getErrorString = function(field, depend) { var stringResource = null; var lang = ValidationFramework._userLanguage.toLowerCase(); //if lang == auto, get the user's browser language. if (lang == "auto") { // different browser has the different method the get the // user's language. so this is a stupid way to detect the // most common browser IE and Mozilla. if (typeof navigator.userLanguage == 'undefined') lang = navigator.language.toLowerCase(); else lang = navigator.userLanguage.toLowerCase(); } // get the language if (typeof ValidationErrorString[lang] != 'object') { stringResource = ValidationErrorString['zh-cn']; } else { stringResource = ValidationErrorString[lang]; } var dep = depend.getName().toLowerCase(); var retStr = stringResource[dep]; //If the specified depend not defined, use the default error string. if (typeof retStr != 'string') { retStr = stringResource["default"]; retStr = retStr.replace("{0}", field.getDisplayName()); return retStr; } retStr = retStr.replace("{0}", field.getDisplayName()); if (dep == "minlength" || dep == "maxlength" || dep == "date" ) { retStr = retStr.replace("{1}", depend.getParams()[0]); } else if ( dep == "equalsfield") { var eqField = field.getForm().findField(depend.getParams()[0]); if (eqField == null) { ValidationFramework.exception("找不到名称为[" + depend.getParams()[0]+"]的域,请检查xml配置文件。"); retStr = "<<配置错误>>"; } else { retStr = retStr.replace("{1}", field.getForm().findField(depend.getParams()[0]).getDisplayName()); } } else if (dep == "integerrange" || dep == "doublerange") { retStr = retStr.replace("{1}", depend.getParams()[0]); retStr = retStr.replace("{2}", depend.getParams()[1]); } return retStr; } ValidationFramework.getWebFormFieldObj = function(field) { var obj = null; if (ValidationFramework._currentForm != null) { var formObj = document.getElementById(ValidationFramework._currentForm.getId()); obj = formObj[field.getName()]; if (typeof(obj) == 'undefined') { obj = null; } } if (obj == null) { ValidationFramework.exception("在配置文件中有需要验证的域,但在实际网页表单中不存在:[name=" + field.getName() + "]。"); } return obj; } ValidationFramework.exception = function(str) { var ex = "JavaScript Validation Framework 运行时错误:\n\n"; ex += str; ex += "\n\n\n任何运行错误都会导致该域验证失败。"; alert(ex); } ValidationFramework.getIntegerValue = function(val) { var intvalue = parseInt(val); if (isNaN(intvalue)) { ValidationFramework.exception("期待一个整型参数。"); } return intvalue; } ValidationFramework.getFloatValue = function(val) { var floatvalue = parseFloat(val); if (isNaN(floatvalue)) { ValidationFramework.exception("期待一个浮点型参数。"); } return floatvalue; } /** * FormFactory * Build virture form from Html Form. */ function FormFactory() {} FormFactory.getFormFromDOM = function(dom) { var form = new ValidationForm(); form.setId(dom.getAttribute("id")); form.setShowError(dom.getAttribute("show-error")); form.setOnFail(dom.getAttribute("onfail")); form.setShowType(dom.getAttribute("show-type")); if (dom.hasChildNodes()) { var f = dom.childNodes; for (var i = 0; i < f.length; i++) { if (f.item(i) == null||typeof(f.item(i).tagName) == 'undefined' || f.item(i).tagName != 'field') { continue; } var field = FieldFactory.getFieldFromDOM(f.item(i)); if (field != null) { form.addField(field); } } } return form; } /// Get the Form from ID FormFactory.getFormFromId = function(id) { var root = ValidationFramework.getDocumentElement(); if ( root == null || (!root.hasChildNodes()) ) return null; var vforms = root.childNodes; for (var i = 0; i < vforms.length; i++) { var f = vforms.item(i); if (typeof(f.tagName) != 'undefined' && f.tagName == 'form' && f.getAttribute("id") == id) { return FormFactory.getFormFromDOM(f); } } return null; } /** * A validation form object. */ function ValidationForm() { this._fields = []; this._id = null; this._showError = null; this._onFail = null; this._showType = null; this.getFields = function() { return this._fields; } this.setFields = function(p0) { this._fields = p0; } this.getId = function() { return this._id; } this.setId = function(p0) { this._id = p0; } this.getShowError = function() { return this._showError; } this.setShowError = function(p0) { this._showError = p0; } this.getShowType = function() { return this._showType; } this.setShowType = function(p0) { this._showType = p0; } this.getOnFail = function() { return this._onFail; } this.setOnFail = function(p0) { this._onFail = p0; } // find field by it's name this.findField = function(p0) { for (var i = 0; i < this._fields.length; i++) { if (this._fields[i].getName() == p0) { return this._fields[i]; } } return null; } this.addField = function(p0) { this._fields[this._fields.length] = p0; p0.setForm(this); } } /** * A form filed. virtual. */ function ValidationField() { this._name = null; this._depends = []; this._displayName = null; this._onFail = null; this._form = null; this.getName = function() { return this._name; } this.setName = function(p0) { this._name = p0; } this.getDepends = function() { return this._depends; } this.setDepends = function(p0) { this._depends = p0; } this.getDisplayName = function() { return this._displayName; } this.setDisplayName = function(p0) { this._displayName = p0; } this.getOnFail = function() { return this._onFail; } this.setOnFail = function(p0) { this._onFail = p0; } this.getForm = function() { return this._form; } this.setForm = function(p0) { this._form = p0; } this.addDepend = function(p0) { this._depends[this._depends.length] = p0; } } ///Factory methods for create Field function FieldFactory() {} FieldFactory.getFieldFromDOM = function(dom) { var field = new ValidationField(); field.setName(dom.getAttribute("name")); field.setDisplayName(dom.getAttribute("display-name")); field.setOnFail(dom.getAttribute("onfail")); if (dom.hasChildNodes()) { var depends = dom.childNodes; for (var i = 0; i < depends.length; i++) { var item = depends.item(i); if (typeof(item.tagName) == 'undefined' || item.tagName != 'depend') { continue; } var dp = new ValidationDepend(); dp.setName(item.getAttribute("name")); dp.addParam(item.getAttribute("param0")); dp.addParam(item.getAttribute("param1")); dp.addParam(item.getAttribute("param2")); dp.addParam(item.getAttribute("param3")); dp.addParam(item.getAttribute("param4")); field.addDepend(dp); } } return field; } function FormFieldUtils() {} FormFieldUtils.findField = function(formName, fieldName) { var formArr = ValidationFramework.getAllForms(); var theForm = null; for (var i = 0; i < formArr.length; i++) { if (formArr[i].getName() == formName) { theForm = formArr[i]; } } if (theForm != null) { return theForm.findField(fieldName); } else { return null; } } /** * A validaton depend. */ function ValidationDepend() { this._name = null; this._params = []; this.getName = function() { return this._name; } this.setName = function(p0) { this._name = p0; } this.getParams = function() { return this._params; } this.setParams = function(p0) { this.params = p0; } this.addParam = function(p0) { this._params[this._params.length] = p0; } } function ValidateMethodFactory() {} ValidateMethodFactory._methods = []; ValidateMethodFactory.validateRequired = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (typeof(obj.type) == "undefined") { var tmp = 0; for (var i = 0; i < obj.length; i++) { if (obj[i].checked) { return true; } } return false; } if (obj.type == "checkbox" || obj.type == "radio") { return (obj.checked); } else { return !(obj.value == ""); } } ValidateMethodFactory.validateInteger = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^-?\\d+$"); return exp.test(obj.value); } ValidateMethodFactory.validateDouble = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^-?\\d+\.\\d+$"); return exp.test(obj.value); } ValidateMethodFactory.validateCommonChar = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^[A-Za-z0-9_]*$"); return exp.test(obj.value); } ValidateMethodFactory.validateChineseChar = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^[\u4E00-\u9FA5\uF900-\uFA2D]*$"); return exp.test(obj.value); } ValidateMethodFactory.validateMinLength = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var v = ValidationFramework.getIntegerValue(params[0]); return (obj.value.length >= v); } ValidateMethodFactory.validateMaxLength = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var v = ValidationFramework.getIntegerValue(params[0]); return (obj.value.length <= v); } ValidateMethodFactory.validateEmail = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; return ValidateMethodFactory.__checkEmail(obj.value); } ValidateMethodFactory.validateDate = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var value = obj.value; var datePattern = params[0]; var MONTH = "mm"; var DAY = "dd"; var YEAR = "yyyy"; var orderMonth = datePattern.indexOf(MONTH); var orderDay = datePattern.indexOf(DAY); var orderYear = datePattern.indexOf(YEAR); var bValid = true; var dateRegexp = null; if ((orderDay < orderYear && orderDay > orderMonth)) { var iDelim1 = orderMonth + MONTH.length; var iDelim2 = orderDay + DAY.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderDay && iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$"); } else if (iDelim1 == orderDay) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$"); } else if (iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$"); } else { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[2], matched[1], matched[3])) { bValid = false; } } else { bValid = false; } } else if ((orderMonth < orderYear && orderMonth > orderDay)) { var iDelim1 = orderDay + DAY.length; var iDelim2 = orderMonth + MONTH.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderMonth && iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$"); } else if (iDelim1 == orderMonth) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$"); } else if (iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$"); } else { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[1], matched[2], matched[3])) { bValid = false; } } else { bValid = false; } } else if ((orderMonth > orderYear && orderMonth < orderDay)) { var iDelim1 = orderYear + YEAR.length; var iDelim2 = orderMonth + MONTH.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderMonth && iDelim2 == orderDay) { dateRegexp = new RegExp("^(\\d{4})(\\d{2})(\\d{2})$"); } else if (iDelim1 == orderMonth) { dateRegexp = new RegExp("^(\\d{4})(\\d{2})[" + delim2 + "](\\d{2})$"); } else if (iDelim2 == orderDay) { dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})(\\d{2})$"); } else { dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{2})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[3], matched[2], matched[1])) { bValid = false; } } else { bValid = false; } } else { bValid = false; } return bValid; } ValidateMethodFactory.validateTime = function(field, params) { ////NOT IMPLEMENT YET SINCE IT'S NOT USEFUL. return true; } ValidateMethodFactory.validateMask = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp(params[0]); //FIXME: this method may be buggy, need more test. return exp.test(obj.value); } ValidateMethodFactory.validateIntegerRange = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var p0 = ValidationFramework.getIntegerValue(params[0]); var p1 = ValidationFramework.getIntegerValue(params[1]); if (ValidateMethodFactory.validateInteger(field)) { var v = parseInt(obj.value); return (v >= p0 && v <= p1); } else { return false; } return true; } ValidateMethodFactory.validateDoubleRange = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var p0 = ValidationFramework.getFloatValue(params[0]); var p1 = ValidationFramework.getFloatValue(params[1]); if (ValidateMethodFactory.validateInteger(field) || ValidateMethodFactory.validateDouble(field)) { var v = parseFloat(obj.value); return (v >= p0 && v <= p1); } else { return false; } return true; } ValidateMethodFactory.validateEqualsField = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var formObj = document.getElementById(ValidationFramework._currentForm.getId()); var eqField = formObj[params[0]]; if (eqField != null) { return (obj.value == eqField.value) } else { return false; } } ValidateMethodFactory.__isValidDate = function(day, month, year) { if (month < 1 || month > 12) return false; if (day < 1 || day > 31) return false; if ((month == 4 || month == 6 || month == 9 || month == 11) &&(day == 31)) return false; if (month == 2) { var leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day>29 || (day == 29 && !leap)) return false; } return true; } /** * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com), * http://javascript.internet.com */ ValidateMethodFactory.__checkEmail = function(emailStr) { if (emailStr.length == 0) { return true; } var emailPat=/^(.+)@(.+)$/; var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"; var validChars="\[^\\s" + specialChars + "\]"; var quotedUser="(\"[^\"]*\")"; var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/; var atom=validChars + '+'; var word="(" + atom + "|" + quotedUser + ")"; var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$"); var matchArray=emailStr.match(emailPat); if (matchArray == null) { return false; } var user=matchArray[1]; var domain=matchArray[2]; if (user.match(userPat) == null) { return false; } var IPArray = domain.match(ipDomainPat); if (IPArray != null) { for (var i = 1; i <= 4; i++) { if (IPArray[i] > 255) { return false; } } return true; } var domainArray=domain.match(domainPat); if (domainArray == null) { return false; } var atomPat=new RegExp(atom,"g"); var domArr=domain.match(atomPat); var len=domArr.length; if ((domArr[domArr.length-1].length < 2) || (domArr[domArr.length-1].length > 3)) { return false; } if (len < 2) { return false; } return true; } ////Language Definitions var ValidationErrorString = new Object(); ////Simplified Chinese(zh-ch) ValidationErrorString["zh-cn"] = new Object(); ValidationErrorString["zh-cn"]["default"]="域{0}校验失败。"; ValidationErrorString["zh-cn"]["required"]="{0}不能为空。<br/>"; ValidationErrorString["zh-cn"]["integer"]="{0}必须是一个整数。"; ValidationErrorString["zh-cn"]["double"]="{0}必须是一个浮点数(带小数点)。"; ValidationErrorString["zh-cn"]["commonchar"] = "{0}必须是普通英文字符:字母,数字和下划线。<br/>"; ValidationErrorString["zh-cn"]["chinesechar"] = "{0}必须是中文字符。"; ValidationErrorString["zh-cn"]["minlength"]="{0}长度不能小于{1}个字符。"; ValidationErrorString["zh-cn"]["maxlength"]="{0}长度不能大于{1}个字符。" ; ValidationErrorString["zh-cn"]["invalid"]="{0}无效。"; ValidationErrorString["zh-cn"]["date"]="{0}不是一个有效日期,期待格式:{1}。"; ValidationErrorString["zh-cn"]["integerrange"]="{0}必须在整数{1}和{2}之间。"; ValidationErrorString["zh-cn"]["doublerange"]="{0}必须在浮点数{1}和{2}之间。"; ValidationErrorString["zh-cn"]["pid"]="{0}不是一个有效身份证号。"; ValidationErrorString["zh-cn"]["email"]="{0}不是一个有效的Email。"; ValidationErrorString["zh-cn"]["equalsfield"]="{0}必须和{1}一致。"; ////English(en-us) ValidationErrorString["en-us"] = new Object(); ValidationErrorString["en-us"]["default"]="Failed when validating filed {0}."; ValidationErrorString["en-us"]["required"]="{0} is required."; ValidationErrorString["en-us"]["integer"]="{0} must be a integer."; ValidationErrorString["en-us"]["double"]="{0} must be a double value. "; ValidationErrorString["en-us"]["commonchar"] = "{0} should be common ascii characters, A-Z,a-z and undercore. "; ValidationErrorString["en-us"]["chinesechar"] = "{0} must be chinese characters. "; ValidationErrorString["en-us"]["minlength"]="{0} cannot be less then {1}. "; ValidationErrorString["en-us"]["maxlength"]="{0} cannot be more then {1}. "; ValidationErrorString["en-us"]["invalid"]="{0} in invalid. "; ValidationErrorString["en-us"]["date"]="{0} is not an invalid date format: {1}. "; ValidationErrorString["en-us"]["integerrange"]="{0} should be between number {1} and {2}. "; ValidationErrorString["en-us"]["doublerange"]="{0} should be between double {1} and {2}. "; ValidationErrorString["en-us"]["pid"]="{0} is not an valid pid. "; ValidationErrorString["en-us"]["email"]="{0} is not an valid email address. "; ValidationErrorString["en-us"]["equalsfield"]="{0} should be agree with field {1}. "; // preload the validation file. //ValidationFramework.getDocumentElement();` 4xml代码 ``` <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE validation-config SYSTEM "validation-config.dtd"> <validation-config lang="auto"> <form id="form1" show-error="alert" show-type="all"> <field name="name" display-name="姓名" onfail=""> <depend name="required" /> <depend name="commonChar" /> <depend name="minLength" param0="3" /> <depend name="maxLength" param0="20" /> </field> <field name="email" display-name="email邮箱"> <depend name="required" /> <depend name="email" /> </field> <field name="age" display-name="年龄"> <depend name="required" /> </field> <field name="protime" display-name="编程时间"> <depend name="required" /> </field> <field name="os" display-name="使用的操作系统"> <depend name="required" /> </field> <field name="lang" display-name="使用的编程语言"> <depend name="required" /> </field> <field name="editor1" display-name="建议"> <depend name="required" /> </field> </form> </validation-config> ``` 5jsp代码 ``` <%@ 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 'Login.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='ckeditor/ckeditor.js'></script> <script type='text/javascript' src='/js/validation-framework.js'></script> <body> <h1>潜在用户网络调查</h1> <form action='LoginServlet' name='form1' id='form1' method='post' onSubmit="return doValidate(this)"> 姓名:<input type='text' name='name' value='' /><br/> EMAIL:<input type='text' name='email' value=''/><br/> 年纪:<input type='radio' name='age' value='小于18' />小于18 <input type='radio' name='age' value='18-25'/>18-25 <input type='radio' name='age' value='26-40'/>26-40 <input type='radio' name='age' value='大于40'/>大于40<br/> 编程时间:<select name='protime'> <option value='6-12月' >6-12月</option> <option value='12-24月'>12-24月</option> <option value='24月以上'>24月以上</option> </select><br/> 使用操作系统:<select name='os' multiple='multiple' size='6'> <option value='Win XP'>Win XP</option> <option value='Win 2000/2003'>Win 2000/2003</option> <option value='Linux'>Linux</option> <option value='FreeBSD'>FreeBSD</option> <option value='Mac OS'>Mac OS</option> <option value='Other'>Other</option> </select><br/> 使用的编程语言:<input type='checkbox' name='lang' value='C'/>C <input type='checkbox' name='lang' value='C++'/>C++ <input type='checkbox' name='lang' value='C#'/>C# <input type='checkbox' name='lang' value='PYTHON'/>PYTHON <input type='checkbox' name='lang' value='JAVA'/>JAVA <input type='checkbox' name='lang' value='VB'/>VB <input type='checkbox' name='lang' value='DEPHI'/>DEPHI<br/> 建议:<textarea class='ckeditor' cols='50' id='editor1' name='editor1' rows='10'></textarea><br/> <input type='submit' value='提交'> <input type='reset' value='重置'> <input type='hidden' name='ring' value='normal'><br/> <% HttpSession hs=request.getSession(true); hs.setAttribute("write", "yes"); %> </form> </body> </html> ```
bootstrap table export 导出选项出现问题
表中属性是这样的当exportDataType是basic或者为空时候可以导出当前页面,但是只要改成all或者selected就会报错 说 nested exception is java.lang.IllegalStateException: Optional int parameter 'limit' is not present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type分页的功能也变没了,这个limit是之前传到后台每页的数量。发现问题了 似乎点击导出table按钮后 会根据url地址对后台再进行一次查询 然而我做的是真分页 查询的只有一页 所以导致limit和offset都为空 只能说这个导出excel不能用咯 ``` url : '/tagq_web/order/showorder.do', //请求后台的URL(*) method : 'get', //请求方式(*) toolbar : '#toolbar', //工具按钮用哪个容器 striped : true, //是否显示行间隔色 cache : false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination : true, //是否显示分页(*) sortable : true, //是否启用排序 sortName : "order_id", //默认排序字段 sortOrder : "desc", //排序方式 queryParams : queryParams, //传递参数(*) sidePagination : "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber : 1, //初始化加载第一页,默认第一页 pageSize : 5, //每页的记录行数(*) pageList : [ 5, 10, 25, 50, 100 ], //可供选择的每页的行数(*) search : false, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大 strictSearch : true, showColumns : true, //是否显示所有的列 showRefresh : false, //是否显示刷新按钮 minimumCountColumns : 2, //最少允许的列数 clickToSelect : true, //是否启用点击选中行 height : 400, //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId : "order_id", //每一行的唯一标识,一般为主键列 showToggle : false, //是否显示详细视图和列表视图的切换按钮 showExport : true, exportDataType : "all", cardView : false, //是否显示详细视图 detailView : false, //是否显示父子表 responseHandler : responseHandler, ```
easyui页面显示,就是在主页面显示另一个页面,那个页面没有完整的显示出来,但是在地址栏上输入那个页面的地址,那个页面就完整的显示,这怎么农
使用easyui做的main.jsp和busCarsManager.jsp 在main.jsp点击车辆管理即busCarsManager.jsp,显示成了这样 如下图 ![图片说明](https://img-ask.csdn.net/upload/202003/04/1583329850_48245.png) 在地址栏输入该页面url地址 ![图片说明](https://img-ask.csdn.net/upload/202003/04/1583329898_132483.png) 怎么弄好?? 以下是main.jsp代码 <title>Basic Form - jQuery EasyUI Demo</title> <link rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="easyui/themes/icon.css"> <link rel="stylesheet" type="text/css" href="easyui/themes/demo.css"> <script type="text/javascript" src="easyui/jquery.min.js"></script> <script type="text/javascript" src="easyui/jquery.easyui.min.js"></script> <script type="text/javascript"> $(function() { $('#tt').tree({ //点击菜单事件 onClick: function(node){ //如果选项的url为空,null,直接退出,在页面不变 if(node.url==""||node.url==null){ return; } //如果选项卡存在 var flag=$('#tab').tabs('exists',node.text); //存在的条件下,选中,显示其内容 if(flag){ $('#tab').tabs('select',node.text); }else{ $('#tab').tabs('add',{ title: node.text, href:node.url, closable:true }); } } }); }); </script> <title>汽车租赁系统</title> </head> <body class="easyui-layout"> <div data-options="region:'north',split:true" style="height:100px;background: url('images/绿色.jpg')"> <div style="margin-left: 120px;margin-top: 30px;float:left;"> <span style="font-size: 32px;color:orange;font-weight:bold;">汽车租赁系统</span> </div> <div style="float: right ;margin-top: 60px;margin-right: 30px"> <span style="font-size: 18px;color: red;">欢迎admin用户登录</span> <a style="font-size: 18px;color: red;text-decoration: none">注销</a> </div> </div> <div data-options="region:'south',title:'版权信息',split:true" style="height:200px;background: url('images/版权信息.png'); background-repeat: no-repeat;background-color: silver;background-position: center;"></div> <div data-options="region:'east',title:'East',split:true" style="width:200px;"> <div id="date" class="easyui-calendar" style="width:180px;height:200px;"></div> </div> <div data-options="region:'west',title:'West',split:true" style="width:150px;"> <div id="menu" class="easyui-accordion" data-options="fit:true,border:false"> <div title="类别一"> <ul id="tt" class="easyui-tree" url="SysMenusController/findMoreMenus"></ul> </div> <div title="类别二"></div> <div title="类别三"></div> </div> </div> <div data-options="region:'center'" style="background:#eee;"> <div id="tab" class="easyui-tabs" data-options="fit:true"> <div title="默认页"> <img src="images/默认页.jpeg" width="90%" height="90%"> </div> </div> </div> </body> 以下是busCarsManager.jsp代码 <body data-options="fit:true"> <table id="busCarsManger_dg" title="My Cars" class="easyui-datagrid" style="width:600px;height:250px" url="/busCarsController/findAllBusCars" toolbar="#busCarsManger_toolbar" pagination="true" rownumbers="true" fitColumns="true" singleSelect="true"> <thead> <tr> <th field="carnumber" width="50">汽车牌号</th> <th field="lastname" width="50">汽车类型</th> <th field="pice" width="50">汽车价格</th> <th field="description" width="50">汽车描述</th> <th data-options="field:'carimg',formatter:showImage" width="50">汽车图片</th> </tr> </thead> </table> <div id="busCarsManger_toolbar"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newCars()">新增汽车</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editCars()">修改汽车信息</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyCars()">移除</a> </div> <div id="busCarsManger_dlg" class="easyui-dialog" style="width:500px" data-options="closed:true,modal:true,border:'thin',buttons:'#busCarsManger_dlg-buttons'"> <form id="busCarsManger_fm" method="post" novalidate style="margin:0;padding:20px 50px"> <h3>汽车信息</h3> <div style="margin-bottom:10px"> <input name="carnumber" class="easyui-textbox" required="true" label="汽车牌号:" style="width:100%"> </div> <div style="margin-bottom:10px"> <input name="cartype" class="easyui-textbox" required="true" label="汽车类型:" style="width:100%"> </div> <div style="margin-bottom:10px"> <input name="color" class="easyui-textbox" required="true" label="汽车颜色" style="width:100%"> </div> <div style="margin-bottom:10px"> <input name="price" class="easyui-textbox" required="true" label="汽车价格" style="width:100%"> </div> <div style="margin-bottom:10px"> <input name="rentprice" class="easyui-textbox" required="true" label="汽车租金" style="width:100%"> </div> <div style="margin-bottom:10px"> <input name="deposit" class="easyui-textbox" required="true" label="汽车押金" style="width:100%"> </div> <div style="margin-bottom:10px"> <input name="description" class="easyui-textbox" required="true" label="汽车描述" style="width:100%"> </div> <input type="text" name="carimg" id="carimg"> </form> <form id="fm2" method="post" enctype="multipart/form-data" style="margin:0;padding:20px 50px"> <div style="margin-bottom:10px"> <input name="fil" class="easyui-filebox" label="汽车图片" style="width:70%"> <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="fileUpload()" style="width:100px">上传图片</a> </div> <span id="sp1"></span> </form> </div> <div id="busCarsManger_dlg-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveCars()" style="width:90px">Save</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')" style="width:90px">Cancel</a> </div> <script type="text/javascript"> //全局参数地址 var url; //删除车辆系信息操作 function destroyCars(){ //当表格信息被选中 var row= $('#busCarsManger_dg').datagrid('getSelected'); if(row){ //提示是否删除 $.messager.confirm("提示","是否删除该车辆信息",function(flag){ if(flag){ //发送Ajax请求,通过控制器执行删除车辆操作 $.post("busCarsController/removeBusCars",{'carnumber':row.carnumber},function(result){ if(result>0){ //删除成功重新加载表格数据 $("#busCarsManger_dg").datagrid("reload"); }else{ $.messager.alert("警告","删除失败","error"); } }) } }) }else //提示请选中至少一行 $.messager.alert("提示","请选中当前信息表的一行数据","info"); } //修改车辆信息 function editCars(){ //当数据表格被选中 var row= $('#busCarsManger_dg').datagrid('getSelected'); if(row){ //执行修改操作,打开修改对话框 $("#busCarsManger_dlg").dialog("open").dialog("center").dialog("setTitle","修改汽车信息") //加载当前选中信息行的数据,在表单一中回显 $("busCarsManger_fm").form("load",row); //表单二中图片的回显,不是用append方法,是因为每次点击修改就会加一个图片,故只用文本显示方法html $("#sp1").html("<img src='images/"+result.url+"'width='80px'/>") //点击保存时,实现修改操作,跳转到当前车辆信息表 url:"busCarsController/changeBusCars"; }else{ $.messager.alert("提示","请选中当前信息表的一行数据","info"); } } //文件上传的操作 function fileUpload(){ //提交form表单 $('#fm2').form('submit',{ url: "busCarsController/fileUpload", success: function(result){ var result=eval('('+result+')'); if(result.url){ //防止在执行修改车辆信息操作,上传图片时,需要清空表单二的图片,防止出现两个图片 $("#sp1").empty(); //显示图片 $("#sp1").append("<img src='images/"+result.url+"'width='80px'/>") //将图片名字赋值给隐藏域 $("#carimg").val("result.url"); }else{ $.messager.alert("提示","图片上传失败","error"); } } }); } //保存车辆信息 function saveCars(){ //获得表单的所有内容 var val =$("busCarsManger_fm").serialize(); $.post(url,val,function(result){ if(result>0){ //关闭当前的对话框 $("#busCarsManger_dlg").dialog("close") //刷新后面的表格 $("#busCarsManger_dg").datagrid("reload"); } }) } 添加车辆信息 function newCars(){ //添加新增对话框信息 $("#busCarsManger_dlg").dialog("open").dialog("center").dialog("setTitle","新增汽车") //清除表单之前的内容 $("busCarsManger_fm").form("clear") //清除图片表单项,要不然下次打开还在 $("#fm2").form("clear") //清除图片显示 $("#sp1").empty(); url="busCarsController/saveBusCars"; } function showImage(val){ return "<img src='images/"+val+"' width='80px'/>"; } </script> </body>
调用java虚拟机打印将ceb转换为pdf时参数问题,求大神指导
ActiveXComponent doc=new ActiveXComponent("word.Application"); //设置是否显示打开 Dispatch.put(doc, "Visible", new Variant(true)); //打开具体的工作簿 Dispatch documents = doc.getProperty("Documents").toDispatch(); Dispatch word = Dispatch.call(documents,"Open",path).toDispatch(); //设置打印属性并打印 Dispatch.callN(word,"PrintOut",new Object[]{ Variant.VT_MISSING, Variant.VT_MISSING, new Integer(1), new Boolean(false),PRINT_NAME, new Boolean(true),Variant.VT_MISSING, "" }); //关闭文档 Dispatch.call(word, "Close", new Variant(false)); 调用java虚拟机打印将word转换为pdf时 ActiveXComponent doc=new ActiveXComponent("word.Application"),那么ceb转pdf时应该new ActiveXComponent("“)参数写什么呢?求大神知道,十分感谢。
java Post请求接收body里的参数
try { URL url = new URL(strURL);// 创建连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST");// 设置请求方式 connection.setRequestProperty("Accept","application/json");// 设置接收数据的格式 connection.setRequestProperty("Content-Type","application/json");// 设置发送数据的格式 connection.connect(); OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream(),"UTF-8");// utf-8编码 out.append(params); out.flush(); out.close(); // 读取响应 int length = (int) connection.getContentLength();// 获取长度 InputStream is = connection.getInputStream(); if (length != -1){ byte[] data = new byte[length]; byte[] temp = new byte[512]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0){ System.arraycopy(temp, 0, data, destPos, readLen); destPos += readLen; } String result = new String(data, "UTF-8"); System.out.println(result); return result; } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } --接收方法 @RequestMapping(value="/test", method = RequestMethod.POST) @ResponseBody public String test(HttpServletRequest request,HttpServletResponse response,@RequestBody String str){ System.out.println(str); return "DetailedRules"; }
Junit对premium()方法测试
某保险公司用premium()方法计算汽车驾驶员应支付的保险金额。该方法接收三个参数age,gender,married,分别表示驾驶员的年龄、性别和婚姻状态。其中,age是整型参数,代表驾驶员的年龄。gender是字符型参数,取值'M'表示男性,取值'F'表示女性。married是布尔型变量,取值true表示已婚,取值false表示未婚。该保险公司保险金计算规则如下: ² 年龄低于16岁或高于65岁不允许参保。 ² 保险金基线为500美元。 ² 如果驾驶员是25岁以下单身男性,则增加100美元。否则, l 如果驾驶员已婚或为女性,则保险金减200美元。 l 如果驾驶员年龄在45岁至65岁之间(包括45岁和65岁),则保险金减100美元。 对于参数无效的情况(age不在16至65之间,或者gender取值不为'M'和'F'),premium()方法返回0。对于其他情况,返回计算获得的保险金额。
idea配置mybits generate时报错,请问是哪配错了吗?
报错说找不到driver-class-name核对了很多次都没问题啊 报错: ``` D:\jdk1.8.0_121\bin\java.exe -Dmaven.multiModuleProjectDirectory=D:\mycode\demo_mybits\demo "-Dmaven.home=D:\software\idea\IntelliJ IDEA 2018.2.6\plugins\maven\lib\maven3" "-Dclassworlds.conf=D:\software\idea\IntelliJ IDEA 2018.2.6\plugins\maven\lib\maven3\bin\m2.conf" "-javaagent:D:\software\idea\IntelliJ IDEA 2018.2.6\lib\idea_rt.jar=7115:D:\software\idea\IntelliJ IDEA 2018.2.6\bin" -Dfile.encoding=UTF-8 -classpath "D:\software\idea\IntelliJ IDEA 2018.2.6\plugins\maven\lib\maven3\boot\plexus-classworlds-2.5.2.jar" org.codehaus.classworlds.Launcher -Didea.version=2018.2.6 mybatis-generator:generate -e [INFO] Error stacktraces are turned on. [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building demo 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ demo --- [INFO] Connecting to the Database [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.637 s [INFO] Finished at: 2019-11-11T09:52:35+08:00 [INFO] Final Memory: 14M/245M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate (default-cli) on project demo: Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate failed: Exception getting JDBC Driver: {spring.datasource.driver-class-name} -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate (default-cli) on project demo: Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate failed: Exception getting JDBC Driver at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) at org.codehaus.classworlds.Launcher.main(Launcher.java:47) Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate failed: Exception getting JDBC Driver at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207) ... 21 more Caused by: java.lang.RuntimeException: Exception getting JDBC Driver at org.mybatis.generator.internal.db.ConnectionFactory.getDriver(ConnectionFactory.java:85) at org.mybatis.generator.internal.db.ConnectionFactory.getConnection(ConnectionFactory.java:54) at org.mybatis.generator.config.Context.getConnection(Context.java:526) at org.mybatis.generator.config.Context.introspectTables(Context.java:436) at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.java:222) at org.mybatis.generator.maven.MyBatisGeneratorMojo.execute(MyBatisGeneratorMojo.java:203) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134) ... 22 more Caused by: java.lang.ClassNotFoundException: {spring.datasource.driver-class-name} at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50) at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at org.mybatis.generator.internal.ObjectFactory.internalClassForName(ObjectFactory.java:150) at org.mybatis.generator.internal.ObjectFactory.externalClassForName(ObjectFactory.java:121) at org.mybatis.generator.internal.db.ConnectionFactory.getDriver(ConnectionFactory.java:82) ... 28 more [ERROR] [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException Process finished with exit code 1 ``` application.properties ``` ## 服务器端口,如果不配置默认是8080端口 server.port=9090 ## 数据库设置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/boot_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=x5 ## mybatis配置 # 参数类型的包别名设置 mybatis.typeAliasesPackage=com.example.demo.model # 指向映射xml文件目录 mybatis.mapperLocations=classpath:mapper/*.xml pagehelper.helperDialect=mysql pagehelper.reasonable=true pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql ``` pom.xml ``` <?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.10</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> <scope>runtime</scope> </dependency> </dependencies> </plugin> </plugins> </build> </project> ``` generatorConfig.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--导入配置文件--> <properties resource="application.properties"></properties> <!-- 一个数据库一个context --> <context id="default"> <!-- 注释生成设置 --> <commentGenerator> <!-- 是否生成注释代时间戳--> <property name="suppressDate" value="true" /> <!-- 是否取消注释 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--jdbc的数据库连接--> <jdbcConnection driverClass="{spring.datasource.driver-class-name}" connectionURL="{spring.datasource.url}" userId="{spring.datasource.username}" password="{spring.datasource.password}"> <property name="nullCatalogMeansCurrent" value="true" /> </jdbcConnection> <!-- 类型转换 --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetPackage:生成的实体类所在的包 --> <!-- targetProject:生成的实体类所在的硬盘位置 --> <javaModelGenerator targetPackage="com.example.demo.model" targetProject="src/main/java"> <!-- 是否允许子包 --> <property name="enableSubPackages" value="false" /> <!-- 是否对modal添加构造函数 --> <property name="constructorBased" value="true" /> <!-- 是否清理从数据库中查询出的字符串左右两边的空白字符 --> <property name="trimStrings" value="true" /> <!-- 建立modal对象是否不可改变 即生成的modal对象不会有setter方法,只有构造方法 --> <property name="immutable" value="false" /> </javaModelGenerator> <!-- targetPackage 和 targetProject:生成的 mapper xml 文件的包和位置 --> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <!-- 是否在当前路径下新加一层schema,ex:false路径com.qikegu.demo.model, com.qikegu.demo.model.[schemaName] --> <property name="enableSubPackages" value="false" /> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <property name="trimStrings" value="true"/> </sqlMapGenerator> <!-- targetPackage 和 targetProject:生成的 java interface 文件的包和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.repository" targetProject="src/main/java"> <!-- 是否在当前路径下新加一层schema,ex:false路径com.qikegu.demo.model, com.qikegu.demo.model.[schemaName] --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 配置表信息 --> <!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample, 是否生成 example类 --> <!-- 不同的表,修改tableName和domainObjectName就可以 --> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration> ```
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
深析Synchronized关键字(小白慎入,深入jvm源码,两万字长文)
目录一、synchronized基础1.1synchronized的使用1.1示例1.2验证1.2.1 普通方法和代码块中使用this是同一个监视器(锁),即某个具体调用该代码的对象1.2.2 静态方法和代码块中使用该类的class对象是同一个监视器,任何该类的对象调用该段代码时都是在争夺同一个监视器的锁定1.2、synchronized的特点二、synchronized进阶2.1对象头2.2sy
GitHub 总星 4w+!删库?女装?表情包?这些沙雕中文项目真是我每天快乐的源泉!
大家好,我是 Rocky0429,一个喜欢在 GitHub 上瞎逛的蒟蒻… 好看的皮囊千篇一律,有趣的灵魂没有底线。作为全球最大的同性交友网站,GayHub GitHub 上不止有鲜活的代码,秃头的算法,还有很多拥有有(sha)趣(diao)灵魂的宝藏。 还记得我之前给大家介绍的 Sorry 项目嘛,一个可以自己做表情包的项目,这个的沙雕程度在下面这些项目面前只能算弟弟。虽然说沙雕不分国...
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
20道你必须要背会的微服务面试题,面试一定会被问到
这篇博客总结了面试中最常见的微服务面试题,相信对你有所帮助。
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
2020 年,大火的 Python 和 JavaScript 是否会被取而代之?
Python 和 JavaScript 是目前最火的两大编程语言,但是2020 年,什么编程语言将会取而代之呢? 作者 |Richard Kenneth Eng 译者 |明明如月,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: Python 和 JavaScript 是目前最火的两大编程语言。然而,他们不可能永远屹立不倒。最终,必将像其他编程语言一...
C语言数字图像处理---1.4直方图拉伸和直方图均衡化
本篇将延续上一篇的内容,对直方图进行扩展,讲述直方图拉伸和直方图均衡化两个内容,并通过简单的C语言来实现这两个基础功能,让初学者通俗易懂。
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
没用过这些 IDEA 插件?怪不得写代码头疼
使用插件,可以提高开发效率。对于开发人员很有帮助。这篇博客介绍了IDEA中最常用的一些插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
推荐一些有趣的在线编程游戏
1.Robocode 让坦克们互相博弈的游戏,你可以看到它们飞奔,碾碎一切挡道的东西。机器人配有雷达与火炮,选手在躲避对手进攻的同时攻击对手,以此来较量得分的多少。这个游戏很有意思,曾经令我沉迷… 你可以用Java、Scala、C#等编程语言,编写人工智能程序,驱动机器人。 2.Code Combat Code Combat是一款学习编程的角色扮演游戏。每一关都用任务的形式设立目标,用实时的反馈...
工作十年的数据分析师被炒,没有方向,你根本躲不过中年危机
2020年刚刚开始,就意味着离职潮高峰的到来,我身边就有不少人拿着年终奖离职了,而最让我感到意外的,是一位工作十年的数据分析师也离职了,不同于别人的主动辞职,他是被公司炒掉的。 很多人都说数据分析是个好饭碗,工作不累薪资高、入门简单又好学。然而今年34的他,却真正尝到了中年危机的滋味,平时也有不少人都会私信问我: 数据分析师也有中年危机吗?跟程序员一样是吃青春饭的吗?该怎么保证自己不被公司淘汰...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
张朝阳回应迟到 1 分钟罚 500:资本家就得剥削员工
loonggg读完需要2分钟速读仅需 1 分钟大家我,我是你们的校长。前几天,搜狐的董事局主席兼 CEO 张朝阳和搜狐都上热搜了。原因很简单,就是搜狐出了“考勤新规”。一封搜狐对员工发布...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
那个在阿里养猪的工程师,5年了……
简介: 在阿里,走过1825天,没有趴下,依旧斗志满满,被称为“五年陈”。他们会被授予一枚戒指,过程就叫做“授戒仪式”。今天,咱们听听阿里的那些“五年陈”们的故事。 下一个五年,猪圈见! 我就是那个在养猪场里敲代码的工程师,一年多前我和20位工程师去了四川的猪场,出发前总架构师慷慨激昂的说:同学们,中国的养猪产业将因为我们而改变。但到了猪场,发现根本不是那么回事:要个WIFI,没有;...
为什么程序猿都不愿意去外包?
分享外包的组织架构,盈利模式,亲身经历,以及根据一些外包朋友的反馈,写了这篇文章 ,希望对正在找工作的老铁有所帮助
Java校招入职华为,半年后我跑路了
何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...
立即提问