我的工具类 发表于 2017-08-17 Json工具类12345<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.2</version></dependency> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import java.util.List;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JavaType;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;public class JsonUtils { // 定义jackson对象 private static final ObjectMapper MAPPER = new ObjectMapper(); /** * 将对象转换成json字符串。 * <p>Title: pojoToJson</p> * <p>Description: </p> * @param data * @return */ public static String objectToJson(Object data) { try { String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 将json结果集转化为对象 * * @param jsonData json数据 * @param clazz 对象中的object类型 * @return */ public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { try { T t = MAPPER.readValue(jsonData, beanType); return t; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将json数据转换成pojo对象list * <p>Title: jsonToList</p> * <p>Description: </p> * @param jsonData * @param beanType * @return */ public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); try { List<T> list = MAPPER.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace(); } return null; } } redis工具类(需要在配置文件里面加入)123456789101112public interface JedisClient { String get(String key); String set(String key, String value); String hget(String hkey, String key); long hset(String hkey, String key, String value); long incr(String key); long decr(String key); long expire(String key, int second); long ttl(String key); long del(String key); long hdel(String hkey, String key);} 单机实现类123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import com.migo.order.jediscomp.JedisClient;import org.springframework.beans.factory.annotation.Autowired;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;public class JedisClientSingle implements JedisClient { @Autowired private JedisPool jedisPool; @Override public String get(String key) { Jedis jedis=jedisPool.getResource(); String result=jedis.get(key); jedis.close(); return result; } @Override public String set(String key, String value) { Jedis jedis=jedisPool.getResource(); String result=jedis.set(key, value); jedis.close(); return result; } @Override public String hget(String hkey, String key) { Jedis jedis=jedisPool.getResource(); String result=jedis.hget(hkey, key); jedis.close(); return result; } @Override public long hset(String hkey, String key, String value) { Jedis jedis=jedisPool.getResource(); Long result = jedis.hset(hkey, key, value); jedis.close(); return result; } @Override public long incr(String key) { Jedis jedis=jedisPool.getResource(); Long result = jedis.incr(key); jedis.close(); return result; } @Override public long decr(String key) { Jedis jedis=jedisPool.getResource(); Long result = jedis.decr(key); jedis.close(); return result; } @Override public long expire(String key, int second) { Jedis jedis=jedisPool.getResource(); Long result = jedis.expire(key, second); jedis.close(); return result; } @Override public long ttl(String key) { Jedis jedis=jedisPool.getResource(); Long result = jedis.ttl(key); jedis.close(); return result; } @Override public long del(String key) { Jedis jedis=jedisPool.getResource(); Long result = jedis.del(key); jedis.close(); return result; } @Override public long hdel(String hkey, String key) { Jedis jedis=jedisPool.getResource(); Long result = jedis.hdel(hkey, key); jedis.close(); return result; }} 集群实现类12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import com.migo.order.jediscomp.JedisClient;import org.springframework.beans.factory.annotation.Autowired;import redis.clients.jedis.JedisCluster;public class JedisClientCluster implements JedisClient { @Autowired private JedisCluster jedisCluster; @Override public String get(String key) { return jedisCluster.get(key); } @Override public String set(String key, String value) { return jedisCluster.set(key, value); } @Override public String hget(String hkey, String key) { return jedisCluster.hget(hkey, key); } @Override public long hset(String hkey, String key, String value) { return jedisCluster.hset(hkey, key, value); } @Override public long incr(String key) { return jedisCluster.incr(key); } @Override public long decr(String key) { return jedisCluster.decr(key); } @Override public long expire(String key, int second) { return jedisCluster.expire(key, second); } @Override public long ttl(String key) { return jedisCluster.ttl(key); } @Override public long del(String key) { return jedisCluster.del(key); } @Override public long hdel(String hkey, String key) { return jedisCluster.hdel(hkey,key); }} redis与spring整合applicationContext-redis.xml12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!--扫描包加载service实现类--> <context:component-scan base-package="com.migo.order.service"/> <!-- 配置redis客户端单机版 --> <bean id="jedisPool" class="redis.clients.jedis.JedisPool"> <constructor-arg name="host" value="192.168.42.131"/> <constructor-arg name="port" value="6379"/> </bean> <!-- 配置redis客户端实现类 --> <bean id="jedisClientSingle" class="com.migo.order.jediscomp.impl.JedisClientSingle"/> <!-- 配置redis客户端集群版 --> <!--<bean id="jedisCluster" class="redis.clients.jedis.JedisCluster"> <constructor-arg> <set> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.42.131"/> <constructor-arg name="port" value="7001"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.42.131"/> <constructor-arg name="port" value="7002"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.42.131"/> <constructor-arg name="port" value="7003"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.42.131"/> <constructor-arg name="port" value="7004"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.42.131"/> <constructor-arg name="port" value="7005"/> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="192.168.42.131"/> <constructor-arg name="port" value="7006"/> </bean> </set> </constructor-arg> </bean> <bean id="jedisClientCluster" class="com.migo.order.jediscomp.impl.JedisClientCluster"/>--></beans> redis缓存使用12345678910**service实现类中*** private static final String REDIS_KEY = "MIGO_MANAGE_ITEM_CAT_LIST"; // 规则:项目名_模块名_业务名 // 从缓存中命中,如果命中返回,没有命中继续查询 String jsonData = jedisClient.get(REDIS_KEY); //将查询结果集写入到Redis中 this.jedisClient.set(REDIS_KEY,JsonUtils.objectToJson(resultList),REDIS_TIME);---------------------------------------华丽分割线--------------------------------------------至于写的操作对缓存做出了修改根据你更新的数据的key看能否命中redis的缓存数据,如果没命中,什么都不做,如果命中,更新redis缓存中的命中的数据。缓存是典型的读多写少,你不能每次更新都去更新缓存 Excel模板导出工具类123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446/** * 报表工具类 * @author Administrator * */import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.regex.Matcher;import java.util.regex.Pattern; import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * * <p class="detail"> * 描述:poi根据模板导出excel,根据excel坐标赋值,如(B1) * </p> * @ClassName: ExcelUtil * @version V1.0 * @date 2015年9月27日 * @author <a href="mailto:1435290472@qq.com">zq</a> */public class PoiUtils { //模板map private Map<String,Workbook> tempWorkbook = new HashMap<String, Workbook>(); //模板输入流map private Map<String,FileInputStream> tempStream = new HashMap<String, FileInputStream>(); /** * * <p class="detail"> * 描述:临时单元格数据 * </p> * @ClassName: Cell * @version V1.0 * @date 2015年9月26日 * @author <a href="mailto:1435290472@qq.com">zq</a> */ class TempCell{ private int row; private int column; private CellStyle cellStyle; private Object data; //用于列表合并,表示几列合并 private int columnSize = -1; public int getColumn() { return column; } public void setColumn(int column) { this.column = column; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public CellStyle getCellStyle() { return cellStyle; } public void setCellStyle(CellStyle cellStyle) { this.cellStyle = cellStyle; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public int getColumnSize() { return columnSize; } public void setColumnSize(int columnSize) { this.columnSize = columnSize; } } /** * * <p class="detail"> * 功能:按模板向Excel中相应地方填充数据 * </p> * @date 2015年9月26日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param tempFilePath * @param dataMap * @param sheetNo * @throws IOException */ public void writeData(String tempFilePath,Map<String,Object> dataMap,int sheetNo) throws IOException{ //获取模板填充格式位置等数据 // HashMap tem = getTemp(tempFilePath,sheet); //读取模板 Workbook wbModule = getTempWorkbook(tempFilePath); //数据填充的sheet Sheet wsheet = wbModule.getSheetAt(sheetNo); Iterator it = dataMap.entrySet().iterator(); while(it.hasNext()){ Entry<String, Object> entry = (Entry<String, Object>) it.next(); String point = entry.getKey(); Object data = entry.getValue(); TempCell cell = getCell(point, data,wsheet); //指定坐标赋值 setCell(cell,wsheet); } //设置生成excel中公式自动计算 wsheet.setForceFormulaRecalculation(true); } /** * * <p class="detail"> * 功能:按模板向Excel中列表填充数据。 只支持列合并 * </p> * @date 2015年9月27日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param tempFilePath * @param heads 列表头部位置集合 * @param datalist * @param sheetNo * @throws FileNotFoundException * @throws IOException */ public void writeDateList(String tempFilePath,String[] heads,List<Map<Integer, Object>> datalist,int sheetNo) throws FileNotFoundException, IOException { //读取模板 Workbook wbModule = getTempWorkbook(tempFilePath); //数据填充的sheet Sheet wsheet = wbModule.getSheetAt(sheetNo); //列表数据模板cell List<TempCell> tempCells = new ArrayList<TempCell>(); for(int i=0;i<heads.length;i++){ String point = heads[i]; TempCell tempCell = getCell(point,null,wsheet); //取得合并单元格位置 -1:表示不是合并单元格 int pos = isMergedRegion(wsheet, tempCell.getRow(), tempCell.getColumn()); if(pos>-1){ CellRangeAddress range = wsheet.getMergedRegion(pos); tempCell.setColumnSize(range.getLastColumn()-range.getFirstColumn()); } tempCells.add(tempCell); } //赋值 for(int i=0;i<datalist.size();i++){ Map<Integer, Object> dataMap = datalist.get(i); for(int j=0;j<tempCells.size();j++){ TempCell tempCell = tempCells.get(j); tempCell.setRow(tempCell.getRow()+1); tempCell.setData(dataMap.get(j+1)); setCell(tempCell, wsheet); } } } /** * * <p class="detail"> * 功能:获取输入工作区 * </p> * @date 2015年9月26日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param tempFilePath * @return * @throws FileNotFoundException * @throws IOException */ private Workbook getTempWorkbook(String tempFilePath) throws FileNotFoundException, IOException { if(!tempWorkbook.containsKey(tempFilePath)){ if(tempFilePath.endsWith(".xlsx")){ tempWorkbook.put(tempFilePath, new XSSFWorkbook(getFileInputStream(tempFilePath))); }else if(tempFilePath.endsWith(".xls")){ tempWorkbook.put(tempFilePath, new HSSFWorkbook(getFileInputStream(tempFilePath))); } } return tempWorkbook.get(tempFilePath); } /** * * <p class="detail"> * 功能:获得模板输入流 * </p> * @date 2015年9月26日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param tempFilePath * @return * @throws FileNotFoundException */ private FileInputStream getFileInputStream(String tempFilePath) throws FileNotFoundException { if(!tempStream.containsKey(tempFilePath)){ tempStream.put(tempFilePath, new FileInputStream(tempFilePath)); } return tempStream.get(tempFilePath); } /** * * <p class="detail"> * 功能:设置单元格数据,样式 (根据坐标:B3) * </p> * @date 2015年9月27日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param point * @param data * @param sheet * @return */ private TempCell getCell(String point,Object data,Sheet sheet){ TempCell tempCell = new TempCell(); //得到列 字母 String lineStr = ""; String reg = "[A-Z]+"; Pattern p = Pattern.compile(reg); Matcher m = p.matcher(point); while(m.find()){ lineStr = m.group(); } //将列字母转成列号 根据ascii转换 char[] ch = lineStr.toCharArray(); int column = 0; for(int i=0;i<ch.length;i++){ char c = ch[i]; int post = ch.length-i-1; int r = (int) Math.pow(10, post); column = column + r*((int)c-65); } tempCell.setColumn(column); //得到行号 reg = "[1-9]+"; p = Pattern.compile(reg); m = p.matcher(point); while(m.find()){ tempCell.setRow((Integer.parseInt(m.group())-1)); } //获取模板指定单元格样式,设置到tempCell (写列表数据的时候用) Row rowIn = sheet.getRow(tempCell.getRow()); if(rowIn == null) { rowIn = sheet.createRow(tempCell.getRow()); } Cell cellIn = rowIn.getCell(tempCell.getColumn()); if(cellIn == null) { cellIn = rowIn.createCell(tempCell.getColumn()); } tempCell.setCellStyle(cellIn.getCellStyle()); tempCell.setData(data); return tempCell; } /** * * <p class="detail"> * 功能:给指定坐标赋值 * </p> * @date 2015年9月27日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param tempCell * @param sheet */ private void setCell(TempCell tempCell,Sheet sheet) { if(tempCell.getColumnSize()>-1){ CellRangeAddress rangeAddress = mergeRegion(sheet, tempCell.getRow(), tempCell.getRow(), tempCell.getColumn(), tempCell.getColumn()+tempCell.getColumnSize()); setRegionStyle(tempCell.getCellStyle(), rangeAddress, sheet); } Row rowIn = sheet.getRow(tempCell.getRow()); if(rowIn == null) { rowIn = sheet.createRow(tempCell.getRow()); } Cell cellIn = rowIn.getCell(tempCell.getColumn()); if(cellIn == null) { cellIn = rowIn.createCell(tempCell.getColumn()); } //根据data类型给cell赋值 if(tempCell.getData() instanceof String){ cellIn.setCellValue((String)tempCell.getData()); }else if(tempCell.getData() instanceof Integer){ cellIn.setCellValue((Integer)tempCell.getData()); }else if(tempCell.getData() instanceof Double){ cellIn.setCellValue((Double)tempCell.getData()); }else{ cellIn.setCellValue((String)tempCell.getData()); } //样式 if(tempCell.getCellStyle()!=null && tempCell.getColumnSize()==-1){ cellIn.setCellStyle(tempCell.getCellStyle()); } } /** * * <p class="detail"> * 功能:写到输出流并移除资源 * </p> * @date 2015年9月27日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param tempFilePath * @param os * @throws FileNotFoundException * @throws IOException */ public void writeAndClose(String tempFilePath,OutputStream os) throws FileNotFoundException, IOException{ if(getTempWorkbook(tempFilePath)!=null){ getTempWorkbook(tempFilePath).write(os); tempWorkbook.remove(tempFilePath); } if(getFileInputStream(tempFilePath)!=null){ getFileInputStream(tempFilePath).close(); tempStream.remove(tempFilePath); } } /** * * <p class="detail"> * 功能:判断指定的单元格是否是合并单元格 * </p> * @date 2015年9月27日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param sheet * @param row * @param column * @return 0:不是合并单元格,i:合并单元格的位置 */ private Integer isMergedRegion(Sheet sheet,int row ,int column) { int sheetMergeCount = sheet.getNumMergedRegions(); for (int i = 0; i < sheetMergeCount; i++) { CellRangeAddress range = sheet.getMergedRegion(i); int firstColumn = range.getFirstColumn(); int lastColumn = range.getLastColumn(); int firstRow = range.getFirstRow(); int lastRow = range.getLastRow(); if(row >= firstRow && row <= lastRow){ if(column >= firstColumn && column <= lastColumn){ return i; } } } return -1; } /** * * <p class="detail"> * 功能:合并单元格 * </p> * @date 2015年9月27日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param sheet * @param firstRow * @param lastRow * @param firstCol * @param lastCol */ private CellRangeAddress mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) { CellRangeAddress rang = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol); sheet.addMergedRegion(rang); return rang; } /** * * <p class="detail"> * 功能:设置合并单元格样式 * </p> * @date 2015年9月27日 * @author <a href="mailto:1435290472@qq.com">zq</a> * @param cs * @param region * @param sheet */ private static void setRegionStyle(CellStyle cs, CellRangeAddress region, Sheet sheet){ for(int i=region.getFirstRow();i<=region.getLastRow();i++){ Row row=sheet.getRow(i); if(row==null) row=sheet.createRow(i); for(int j=region.getFirstColumn();j<=region.getLastColumn();j++){ Cell cell=row.getCell(j); if(cell==null){ cell=row.createCell(j); cell.setCellValue(""); } cell.setCellStyle(cs); } } } //测试 public static void main(String[] args) throws FileNotFoundException, IOException {// String tempFilePath = ExcelUtil.class.getResource("demo.xlsx").getPath(); String tempFilePath = "D:/demo.xls"; File file = new File("d:/data.xls"); OutputStream os = new FileOutputStream(file); PoiUtils excel = new PoiUtils(); List<Map<Integer, Object>> datalist = new ArrayList<Map<Integer,Object>>(); Map<Integer, Object> data = new HashMap<Integer,Object>(); data.put(1, "dfe"); data.put(2, "男"); data.put(3, 45); datalist.add(data); data = new HashMap<Integer,Object>(); data.put(1, "dfeddddd"); data.put(2, "男"); data.put(3, 45); datalist.add(data); String[] heads = new String[]{"A2","C2","E2"}; //必须为列表头部所有位置集合, 输出 数据单元格样式和头部单元格样式保持一致 excel.writeDateList(tempFilePath,heads,datalist,0); //写到输出流并移除资源 excel.writeAndClose(tempFilePath, os); os.flush(); os.close(); }} demo.xls下载 这个工具类在service实现类中的用法(与上面提供的模板是一样的)*12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 @Override public void exportLogEle() { // TODO Auto-generated method stub File file1=new File(""); String tempFilePath=file1.getAbsolutePath()+"\\config\\demo1.xls"; String exportfileName=DateUtils.getFileName(); File file = new File("d:/"+exportfileName+".xls"); OutputStream os=null; try { os = new FileOutputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } PoiUtils excel = new PoiUtils(); Syslog syslog=new Syslog(); syslog.setLogType("1"); List<Syslog> syslogs=syslogMapper.selectAll(syslog); List<Map<Integer, Object>> datalist = new ArrayList<Map<Integer,Object>>(); for (int i = 0; i < syslogs.size(); i++) { Map<Integer, Object> data = new HashMap<Integer,Object>(); System.out.println(i); data.put(1, i); data.put(2, syslogs.get(i).getVisitor()); data.put(3, syslogs.get(i).getArchivesNum()); data.put(4, syslogs.get(i).getTitle()); data.put(5, DateUtils.formatDate(syslogs.get(i).getCreateTime().toString())); data.put(6, syslogs.get(i).getIp()); datalist.add(data); } String[] heads = new String[]{"A2","B2","C2","D2","E2","F2"}; //必须为列表头部所有位置集合, 输出 数据单元格样式和头部单元格样式保持一致 try { excel.writeDateList(tempFilePath,heads,datalist,0); //写到输出流并移除资源 excel.writeAndClose(tempFilePath, os); os.flush(); os.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }} cookie工具类123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;/** * * Cookie 工具类 * */public final class CookieUtils { /** * 得到Cookie的值, 不编码 * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName) { return getCookieValue(request, cookieName, false); } /** * 得到Cookie的值, * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { if (isDecoder) { retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8"); } else { retValue = cookieList[i].getValue(); } break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; } /** * 得到Cookie的值, * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString); break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; } /** * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) { setCookie(request, response, cookieName, cookieValue, -1); } /** * 设置Cookie的值 在指定时间内生效,但不编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage) { setCookie(request, response, cookieName, cookieValue, cookieMaxage, false); } /** * 设置Cookie的值 不设置生效时间,但编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean isEncode) { setCookie(request, response, cookieName, cookieValue, -1, isEncode); } /** * 设置Cookie的值 在指定时间内生效, 编码参数 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode); } /** * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码) */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString); } /** * 删除Cookie带cookie域名 */ public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) { doSetCookie(request, response, cookieName, "", -1, false); } /** * 设置Cookie的值,并使其在指定时间内生效 * * @param cookieMaxage cookie生效的最大秒数 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) { try { if (cookieValue == null) { cookieValue = ""; } else if (isEncode) { cookieValue = URLEncoder.encode(cookieValue, "utf-8"); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request) {// 设置域名的cookie String domainName = getDomainName(request); System.out.println(domainName); if (!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /** * 设置Cookie的值,并使其在指定时间内生效 * * @param cookieMaxage cookie生效的最大秒数 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { try { if (cookieValue == null) { cookieValue = ""; } else { cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request) {// 设置域名的cookie String domainName = getDomainName(request); System.out.println(domainName); if (!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /** * 得到cookie的域名 */ private static final String getDomainName(HttpServletRequest request) { String domainName = null; String serverName = request.getRequestURL().toString(); if (serverName == null || serverName.equals("")) { domainName = ""; } else { serverName = serverName.toLowerCase(); serverName = serverName.substring(7); final int end = serverName.indexOf("/"); serverName = serverName.substring(0, end); final String[] domains = serverName.split("\\."); int len = domains.length; if (len > 3) { // www.xxx.com.cn domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1]; } else if (len <= 3 && len > 1) { // xxx.com or xxx.cn domainName = "." + domains[len - 2] + "." + domains[len - 1]; } else { domainName = serverName; } } if (domainName != null && domainName.indexOf(":") > 0) { String[] ary = domainName.split("\\:"); domainName = ary[0]; } return domainName; }} -------------本文结束感谢您的阅读-------------