1、導出excel文件,文件名的中文問題
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
final String userAgent = request.getHeader("USER-AGENT");
try {
String finalFileName = null;
if(StringUtils.contains(userAgent, "MSIE")){//IE瀏覽器
finalFileName = URLEncoder.encode(fileName,"UTF8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器
finalFileName = new String(fileName.getBytes(), "ISO8859-1");
}else{
finalFileName = URLEncoder.encode(fileName,"UTF8");
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");
} catch (UnsupportedEncodingException e) {
}
}
使用方法:
HSSFWorkbook workbook = getHssfWorkbook(forms, "中文名.xls", headers);
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("octets/stream");
setFileDownloadHeader(httpRequest,response,"中文文件名.xls");
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/vnd.ms-excel");
2、生成一個隨機的字符串,可以作爲主鍵:
UUID uuid = UUID.randomUUID();
UUID.randomUUID().toString().replace("-","")
3、json解析工具,jackson的json工具方法:
//得到對象的json串
private String getJsonStr(Object obj){
try {
return JSONMapper.getInstance().writeValueAsString(obj);
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return null;
}
//解析字符串爲簡單java對象
JSONMapper.getInstance().readValue(json,Oper.class);
//解析字符串爲複雜的java對象
String str = FileUtils.readFileToString(new File("/opt/hotel.json"),"GBK");
ObjectMapper objectMapper = JSONMapper.getInstance();
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
returnT = objectMapper.readValue(str, new TypeReference<ResultHandleT<RouteProductVo>>() {});
//jackson的配置屬性:
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);//是否允許解析使用Java/C++ 樣式的註釋(包括'/'+'*' 和'//' 變量)
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);//是否將允許使用非雙引號屬性名字, (這種形式在Javascript中被允許,但是JSON標準說明書中沒有)
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);//是否允許單引號來包住屬性名稱和字符串值
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);//是否允許JSON字符串包含非引號控制字符(值小於32的ASCII字符,包含製表符和換行符)。 如果該屬性關閉,則如果遇到這些字符,則會拋出異常。
objectMapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true);//決定JSON對象屬性名稱是否可以被String#intern 規範化表示。,如果允許,則JSON所有的屬性名將會 intern() ;如果不設置,則不會規範化,
objectMapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true);// 默認下,該屬性是開放的。此外,必須設置CANONICALIZE_FIELD_NAMES爲true
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);//該特性決定了當遇到未知屬性(沒有映射到屬性,沒有任何setter或者任何可以處理它的handler),是否應該拋出一個JsonMappingException異常。這個特性一般式所有其他處理方法對未知屬性處理都無效後才被嘗試,屬性保留未處理狀態。
4、讀取文本內容,轉換爲字符串:
import org.apache.commons.io.FileUtils;
String str = FileUtils.readFileToString(new File("d:\\酒店分組數據.txt"),"GBK");
5、freemark中,進行select的默認選擇:
<#list min..max as x>
<#if fangxing.roomCount==x >
<option value="${x}" selected>${x}</option>
<#else>
<option value="${x}">${x}</option>
</#if>
</#list>
6、頁面加載完畢之後執行的js,沒有生效,改成添加一個時間之後定時執行就可以了。setTimeOut
7、freemark小技巧
${(fangxing.internet)!'-'} 如果字段爲空就默認爲後面的‘-’
假設前提:user.name爲null
${user.name},異常
${user.name!},顯示空白
${user.name!'vakin'},若user.name不爲空則顯示本身的值,否則顯示vakin
${user.name?default('vakin')},同上
${user.name???string(user.name,'vakin')},同上
判斷是否存在,通過exists關鍵字或者"??"運算符。都將返回一個布爾值
user.name?exists
user.name??
顯示日期類型字符串:
${(base.createTime?string("yyyy-MM-dd HH:mm:ss"))!'無數據 '}
8、對list裏面的自定義對象進行排序:
Collections.sort(depFlightInfos,new Comparator<FlightSearchFlightInfoDto>(){
@Override
public int compare(FlightSearchFlightInfoDto dto1, FlightSearchFlightInfoDto dto2) {
if("departureTime".equals(req.getSortStr())){//比較當地起飛時間
try {
String departureTime1 = dto1.getDepartureTime();
String departureTime2 = dto2.getDepartureTime();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt1= format.parse(departureTime1);
Date dt2= format.parse(departureTime2);
if("ASC".equals(req.getSortType().toUpperCase())){
return dt1.compareTo(dt2);
}else{
return dt2.compareTo(dt1);
}
} catch (ParseException e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
}else if("differentPrice".equals(req.getSortStr())){//比較差價
if(CollectionUtils.isNotEmpty(dto1.getSeats())&& CollectionUtils.isNotEmpty(dto2.getSeats())){
BigDecimal diffPrice1 = dto1.getSeats().get(0).getDifferentPrice();
BigDecimal diffPrice2 = dto2.getSeats().get(0).getDifferentPrice();
if("ASC".equals(req.getSortType().toUpperCase())){
return diffPrice1.compareTo(diffPrice2);
}else{
return diffPrice2.compareTo(diffPrice1);
}
}
return 0;
}
return 0;
}
});
return depFlightInfos;
9、使用bigDecimal進行小數點的轉化,四捨五入等:
錯誤原因可能是請求頭不符合協議標準,一般都是由於cookie過長導致。
An http 400 bad request error means the server thinks your web browser is not obeying all the HTTP protocol rules.
直接在cmd中執行下面的命令 ----------紅色替換爲對應的文件夾
for /r D:\test %i in (.svn) do rd /s /q %i
$(document).ready(function() { $('input[valid]').each(function(){ var $this = $(this); var valid = $this.attr('valid'); if(valid=='email'){ $this.blur(function(){ mailValid($this); }); }else if(valid=='num'){ $this.keyup(function(){ onlyNum($this[0]); }); } else if(valid=='decimal'){ $this.keyup(function(){ onlyDecimal($this[0]); }); } }); }); function onlyNum(obj){ obj.value=obj.value.replace(/\D/gi,""); } function onlyDecimal(obj){ obj.value=obj.value.replace(/[^\.0-9_]/gi,""); }14、關於mysql的查詢小陷阱:
SELECT INTERFACE_KEY,
COUNT(CASE
WHEN RESULT IS NULL OR RESULT = '' OR RESULT = 'SUCCESS' THEN
1
END) SUCC_COUNT,
COUNT(CASE
WHEN RESULT = 'FAIL' THEN
2
END) FAIL_COUNT,
COUNT(*) TOTAL
FROM T_FAPI_FLOW
where SEARCH_TIME >=
to_date('2017-03-01 00:00:00', 'yyyy-MM-dd hh24:mi:ss')
and INTERFACE_KEY = 'ACTUALTIME_TRAFFIC_UNION_QUERY_INFO'
GROUP BY INTERFACE_KEY
ORDER BY TOTAL DESC
17、jquery UI中的常用代碼,包括表格,以及彈出框,dialog:列的格式化: { name : 'cityStatus',//有效性 index : 'cityStatus',formatter:formatValid, align : 'center', sortable:false } function formatValid(cellvalue, options, rowObject) { return "INVALID"==cellvalue?"無效":"有效"; } 多選列表: multiselect : true, 得到多選的列的id集合: var ids = ""; if(id==null || id==""){ ids = $("#vasTransferCityList").jqGrid('getGridParam','selarrrow'); if(ids.length == 0){ alert("請選擇接送機城市!") return false; } }else{ ids = id; } 彈出框: <div id="configAddLayer" class="content content1" style="display:none; width: 400px; height: 380px;"> 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 。。。。。。。。。。。。。。。。。。。。。。。。 </div> 顯示彈出框: $('#configEditLayer').dialog({ title:'修改城市', width:600, height:400, modal:'true' }); 關閉彈出框: $("#configAddLayer").dialog('close') ;
long查詢對應日期:new Date(1493201002146) 字符串查long:new Date("2017-05-8").getTime()
$.ajax({ url : payUrl, type : 'post', dataType : "json", contentType : "application/json;", data : JSON.stringify({ orderId : orderIdVal, flightOrderNo : orderNoObj, orderMainId : orderMainIdVal, payerId : paymentIdVal, payerName : paymentNameVal }), success : function(data) { }, error : function(data) { } });20、tomcat的遠程調試
啓動tomcat之後,設置java代碼裏面的斷點就可以了。
23、oracle數據庫查看數據庫版本:select * from v$version;
24、使用mybatis自動生成mapper的工具生成mapper文件命令:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml
25、java後臺收到中文亂碼,一種解決方法:
temp = new String(temp.getBytes("ISO-8859-1"), "UTF-8") ;
還有可能是因爲,頁面編碼,服務器編碼,eclipse設置編碼,jsp請求ajax編碼等等原因。
26、window.open居中顯示:
var openUrl = "";//彈出窗口的url var iWidth=800; //彈出窗口的寬度; var iHeight=600; //彈出窗口的高度; var iTop = (window.screen.availHeight-30-iHeight)/2; //獲得窗口的垂直位置; var iLeft = (window.screen.availWidth-10-iWidth)/2; //獲得窗口的水平位置; window.open('http://www.baidu.com',"","height="+iHeight+", width="+iWidth+", top="+iTop+", left="+iLeft);
27、得到一個java文件在服務器上面的路徑:
System.out.println(ConnectionUtil.class.getResource("/resource/jchem.properties").getPath() );
28、oracle強大的導出工具expdp:
expdp scott/tiger@orcl directory=dpdata1 dumpfile=expdp.dmp Tables=emp query='WHERE deptno=20';
exp scott/tiger@orcl file=expdp.dmp Tables=emp
29、遞歸創建文件夾:
public static void mkDir(File file){
if(file.getParentFile().exists()){
file.mkdir();
}else{
mkDir(file.getParentFile());
file.mkdir();
}
}
public static void main(String[] args) {
File file = new File("c:/2/1/s/e");
mkDir(file);
}
30、jsp中使用struts標籤,選擇下拉菜單:
<select name="object.hintType" value='${object.hintType}'>
<option value="0" <c:if test="${object.hintType==0}">selected</c:if>>
不再提醒
</option>
<option value="1" <c:if test="${object.hintType==1}">selected</c:if>>
繼續提醒
</option>
</select>
31、文本出現下劃線:
style="text-decoration:underline"
32、工具包進行反射的調用:
BeanUtils.setProperty(hotelForm,propertyName, img);
33、把class文件夾下面的class生成jar包:
直接在classes文件夾裏面cmd命令:::
jar -cvf aaaaaa.jar com/*
34、讀取java屬性文件:
static {
PropertyResourceBundle config = (PropertyResourceBundle) PropertyResourceBundle
.getBundle("SystemConfig");
ACCOUNT = config.getString("zhongtai_account");
PASSWORD = config.getString("zhongtai_password");
IP = config.getString("zhongtai_ip");
}
35、查詢oracle數據庫中全部表名:
select * from all_tab_comments t where t.OWNER = 'HOLIDAYBAK'
36、金額大寫的js函數:
$(function(){ $('input[isMoney]').each(function(){ var $this = $(this); $this.next().html(numToCny($this.val())); }); $('input[isMoney]').keyup(function(){ var $this = $(this); $this.next().html(numToCny($this.val())); }); }); function numToCny(num) { if (isNaN(num) || num > Math.pow(10, 12)) return "" var cn = "零壹貳叄肆伍陸柒捌玖" var unit = new Array("拾百千", "分角") var unit1 = new Array("萬億", "") var numArray = num.toString().split(".") var start = new Array(numArray[0].length - 1, 2) function toChinese(num, index) { var num = num.replace(/\d/g, function($1) { return cn.charAt($1) + unit[index].charAt(start-- % 4 ? start % 4 : -1) }) return num } for (var i = 0; i < numArray.length; i++) { var tmp = "" for (var j = 0; j * 4 < numArray[i].length; j++) { var strIndex = numArray[i].length - (j + 1) * 4 var str = numArray[i].substring(strIndex, strIndex + 4) var start = i ? 2 : str.length - 1 var tmp1 = toChinese(str, i) tmp1 = tmp1.replace(/(零.)+/g, "零").replace(/零+$/, "") tmp1 = tmp1.replace(/^壹拾/, "拾") tmp = (tmp1 + unit1[i].charAt(j - 1)) + tmp } numArray[i] = tmp } numArray[1] = numArray[1] ? numArray[1] : "" numArray[0] = numArray[0] ? numArray[0] + "元" : numArray[0], numArray[1] = numArray[1].replace(/^零+/, "") numArray[1] = numArray[1].match(/分/) ? numArray[1] : numArray[1] + "整" return numArray[0] + numArray[1] }37、struts的循環list,然後再做判斷標籤:
<s:iterator value="list" var="stu" status=“aaa”>
<s:property value="#stu.hasImg" />
<s:if test="#stu.hasImg==1"> //注意這裏,沒有大括號
</s:if>
<s:else>無圖片</s:else>
</s:iterator>
關於status屬性:
#status.odd 是否奇數行
#status.count 當前行數
#status.index 當前行的序號,從0開始『#status.count=#status.index+1』
#status.first 是否第一行
#status.last 是否最後一行
#status.modules(int) 當前行數取模
判斷方法是:
<s:iterator value="list" status="st">
<s:if test="#status.last">
........
</s:if>
</s:iterator>
38、關於oracle的行列轉,10g中換有一個函數: wmsys.wm_concat
38、poi中合併單元格
CellRangeAddress region = new CellRangeAddress((short)start, (short) (start+i-1), cols[ii], (cols[ii]));
sheet.addMergedRegion(region);
在用poi在EXECL報表設計的時候,遇到單元格合併問題,用到一個重要的函數:
CellRangeAddress(int, int, int, int)
參數:起始行號,終止行號, 起始列號,終止列號
39、oracle中的job,以及創建一個執行job的存儲過程:
variable update_order_job number;
begin
dbms_job.submit(:update_order_job, 'PROCE_UPDATE_ORDER;', sysdate, 'sysdate+1/1440');--每1執行PROCE_UPDATE_ORDER存儲過程
end;
創建JOB執行存儲過程:
#1,--創建Job
variable update_order_job number;
begin
dbms_job.submit(:update_order_job, 'PROCE_UPDATE_ORDER;', sysdate, 'sysdate+1/1440');--每1執行PROCE_UPDATE_ORDER存儲過程
end;
#2,--創建Job或:
declare update_order_job number;
begin
dbms_job.submit(update_order_job, 'PROCE_UPDATE_ORDER;', sysdate, 'sysdate+1/1440');--每1執行PROCE_UPDATE_ORDER存儲過程
end;
#3,刪除Job
begin
dbms_job.remove(23);--和select * from user_jobs; 中的job值對應,看what對應的過程
end;
#4,執行Job
begin
dbms_job.run(24);
end;
#5,查看Job
select * from user_jobs;
40、導出oracle中的全部的序列的sql語句:
select 'CREATE SEQUENCE '||t.sequence_name||' minvalue '||t.min_value||' maxvalue'||' '||t.max_value||' increment by '||t.increment_by ||' start with '||(t.last_number)||' nocache order nocycle;' from user_sequences t
41、在js裏面上傳一個富文本編輯器中的含有特殊轉義字符,post到後臺要進行字符串的轉義:
function replace(str) { return str.replace(/&nbsp;/g, '').replace(/&/g, '').replace( / /g, ''); } return replace(encodeURI(vals));
42、log4j的寫法:很多很多的logger import不要寫錯:
import org.apache.log4j.Logger;
private static Logger logger = Logger.getLogger(ToBigOrderServiceImpl.class);
43、mybatis中執行存儲過程:
<select id="copyProduct" statementType="CALLABLE">
<![CDATA[
{call PROCE_COPY_PRODUCT (#{productId,mode=IN,jdbcType=VARCHAR})}
]]>
</select>
對應的Mapper接口文件:
void copyProduct(String productId);
44、linux中設置java環境變量:export JAVA_HOME=/usr/share/jdk1.6.0_14
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
45、設置tomcat使用的java內存: JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1024m -Xmx1024m -XX:NewSize=512m -XX:MaxNewSize=256m -XX:PermSize=512m -XX:MaxPermSize=512m"
46、通過wsdl2java.bat生成的webservice客戶端,然後調用方法示例如下:MobileCodeWS mobileCodeWS = new MobileCodeWSLocator();
MobileCodeWSSoap mobileCodeWSSoap;
try {
mobileCodeWSSoap = mobileCodeWS.getMobileCodeWSSoap();
String mobileCodeInfo = mobileCodeWSSoap.getMobileCodeInfo(
"18721266529", null);
System.out.println(mobileCodeInfo);
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
47、修改oracle數據庫的用戶名密碼:alter user muhol_psm2 identified by eholiday_psm2 48、在spring容器加載完畢之後,執行一段代碼:
public class InstantiationCaches implements
ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
System.out.println("初始化緩存容器.");
new Thread(new Runnable() {
@Override
public void run() {
ICacheInit tfProductCache = (ICacheInit) SpringContextUtil
.getBean("tfProductDetailInfoCache");
tfProductCache.initCache();
}
}).start();
}
}
}
在spring配置文件中添加:
<bean class="com.atoz.util.InstantiationCaches">
</bean>
49、spring的自動加載註解:@Autowired
在spring的註解注入中,可以使用@Autowired
如果要修改對應的註解不是默認使用名稱,就:
@Autowired
@Qualifier("tfProductDetailInfoCache")
private ITfProductDetailInfoService tfProductDetailInfoService;
50、異步上傳圖片的js:ajaxfileupload.js
51、oracle中關於用戶的一些強大的sql語句:
--刪除用戶之後 先鎖定用戶
alter user muholb2c_psm3 account lock;
--找到當前用戶全部的會話id
SELECT * FROM V$SESSION WHERE USERNAME='MUHOLB2C_PSM3'
--殺掉全部的會話
alter system kill session '211,35901'
--刪除用戶
drop user muholb2c_psm3 cascade
--在指定表空間上面創建用戶
create user muholb2c_psm3
identified by muholb2c_psm3
default tablespace TBS_PSM_B2C
quota 10M on TBS_PSM_B2C ;
--對用戶授權
grant DBA to muholb2c_psm3;
52、Md5密碼加鹽處理:一般是密碼直接md5處理,但是如果在密碼前面加上一個變化的值,例如(用戶名+密碼)然後在進行md5加密,就安全多了。因爲即使密碼一樣的情況,也不會被加密成爲一樣的數據(因爲用戶名不一樣。。)
53、tomcat7啓動報錯:
java.lang.NoSuchMethodException: org.apache.catalina.deploy.WebXml addFilter
解決方法爲:在Tomacat7的context.xml文件裏的<Context>中加上<Loader delegate="true" />
True,表示tomcat將遵循JVM的delegate機制,即一個WebAppClassLoader在加載類文件時,會先遞交給SharedClassLoader加載,SharedClassLoader無法加載成功,會繼續向自己的父類委託,一直到BootstarpClassLoader,如果都沒有加載成功,則最後由WebAppClassLoader自己進行加載。
False,表示將不遵循這個delegate機制,即WebAppClassLoader在加載類文件時,會優先自己嘗試加載,如果加載失敗,纔會沿着繼承鏈,依次委託父類加載。
54、查看是否打開8788端口:netstat -an | grep 8788
55、mybatis插入的時候,設置主鍵根據序列設置值:
<insert id="insert" parameterType="com.atoz.pojo.ZoneTravelLine" >
<selectKey resultType="java.lang.Integer" keyProperty="id" order="BEFORE" >
select SEQ_zone_travel_line.nextval from dual
</selectKey>
insert into ZONE_TRAVEL_LINE (ID, ZONEID, TRAVEL_LINE
)
values (#{id,jdbcType=DECIMAL}, #{zoneid,jdbcType=DECIMAL}, #{travelLine,jdbcType=DECIMAL}
)
</insert>
56、動態編譯部署java工程,修改java代碼不重啓工程:配置jrebel插件-Xms512m -Xmx512m -XX:PermSize=64M -XX:MaxPermSize=256M -noverify -javaagent:E:/jr-ide-idea/lib/jrebel/jrebel.jar -Drebel.log=c:\rebel.log -Drebel.dirs=D:\xiujiala\Webroot\WEB-INF\classes
public class BeanCopy {
public static <T> T copyBeanFrom(Object src, Class<T> clazz) {
try {
T ans = clazz.newInstance();
BeanUtils.copyProperties(ans, src);
return ans;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
測試類:
SsoUserLoginToken query = new SsoUserLoginToken();
query.setCustomerid("123123");
query.setLoginType("123");
query.setMobile("3222222222222");
UserLoginTokenBean ans = BeanCopy.copyBeanFrom(query,
UserLoginTokenBean.class);
System.out.println(ans.getCustomerid());
58、js計算除法,有精度控制 下面是返回123.45% 精度爲2
function accDiv(arg1,arg2) { var t1 = 0,t2 = 0,r1,r2; try { t1 = arg1.toString().split(".")[1].length } catch (e) { } try { t2 = arg2.toString().split(".")[1].length } catch (e) { } with (Math) { r1 = Number(arg1.toString().replace(".","")) r2 = Number(arg2.toString().replace(".","")) var aa = (r1 / r2) * pow(10,t2 - t1)*100; return aa.toFixed(2); } }