购物网站1:常用到的工具类---泛型工具类---图像压缩工具---MD5加密---读取URL配置---获取用户购物车等

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
 * 泛型工具类
 * @author lihuoming
 *
 */
public class GenericsUtils {
 /** 
     * 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer> 
     * 
     * @param clazz clazz 需要反射的类,该类必须继承范型父类
     * @param index 泛型参数所在索引,从0开始. 
     * @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */ 
    @SuppressWarnings("unchecked")
 public static Class getSuperClassGenricType(Class clazz, int index) {   
        Type genType = clazz.getGenericSuperclass();//得到泛型父类 
        //如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class  
        if (!(genType instanceof ParameterizedType)) {
            return Object.class;  
        } 
        //返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();                  
        if (index >= params.length || index < 0) {
          throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
        }     
        if (!(params[index] instanceof Class)) {
            return Object.class;  
        }  
        return (Class) params[index];
    }
 /** 
     * 通过反射,获得指定类的父类的第一个泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer> 
     * 
     * @param clazz clazz 需要反射的类,该类必须继承泛型父类
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */ 
    @SuppressWarnings("unchecked")
 public static Class getSuperClassGenricType(Class clazz) {
     return getSuperClassGenricType(clazz,0);
    }
 /** 
     * 通过反射,获得方法返回值泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
     * 
     * @param Method method 方法
     * @param int index 泛型参数所在索引,从0开始.
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */
    @SuppressWarnings("unchecked")
 public static Class getMethodGenericReturnType(Method method, int index) {
     Type returnType = method.getGenericReturnType();
     if(returnType instanceof ParameterizedType){
         ParameterizedType type = (ParameterizedType) returnType;
         Type[] typeArguments = type.getActualTypeArguments();
            if (index >= typeArguments.length || index < 0) {
              throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
            }
         return (Class)typeArguments[index];
     }
     return Object.class;
    }
 /** 
     * 通过反射,获得方法返回值第一个泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
     * 
     * @param Method method 方法
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */
    @SuppressWarnings("unchecked")
 public static Class getMethodGenericReturnType(Method method) {
     return getMethodGenericReturnType(method, 0);
    }
   
 /** 
     * 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
     * 
     * @param Method method 方法
     * @param int index 第几个输入参数
     * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
     */
    @SuppressWarnings("unchecked")
 public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
     List<Class> results = new ArrayList<Class>();
     Type[] genericParameterTypes = method.getGenericParameterTypes();
     if (index >= genericParameterTypes.length ||index < 0) {
             throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
        }
     Type genericParameterType = genericParameterTypes[index];
     if(genericParameterType instanceof ParameterizedType){
          ParameterizedType aType = (ParameterizedType) genericParameterType;
          Type[] parameterArgTypes = aType.getActualTypeArguments();
          for(Type parameterArgType : parameterArgTypes){
              Class parameterArgClass = (Class) parameterArgType;
              results.add(parameterArgClass);
          }
          return results;
     }
     return results;
    }
 /** 
     * 通过反射,获得方法输入参数第一个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
     * 
     * @param Method method 方法
     * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
     */
    @SuppressWarnings("unchecked")
 public static List<Class> getMethodGenericParameterTypes(Method method) {
     return getMethodGenericParameterTypes(method, 0);
    }
 /** 
     * 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
     * 
     * @param Field field 字段
     * @param int index 泛型参数所在索引,从0开始.
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */
    @SuppressWarnings("unchecked")
 public static Class getFieldGenericType(Field field, int index) {
     Type genericFieldType = field.getGenericType();
     
     if(genericFieldType instanceof ParameterizedType){
         ParameterizedType aType = (ParameterizedType) genericFieldType;
         Type[] fieldArgTypes = aType.getActualTypeArguments();
         if (index >= fieldArgTypes.length || index < 0) {
          throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
            }
         return (Class)fieldArgTypes[index];
     }
     return Object.class;
    }
 /** 
     * 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
     * 
     * @param Field field 字段
     * @param int index 泛型参数所在索引,从0开始.
     * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
     */
    @SuppressWarnings("unchecked")
 public static Class getFieldGenericType(Field field) {
     return getFieldGenericType(field, 0);
    }
}

 

----------------------------------------------------------------

 

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图像压缩工具
 * @author lihuoming@sohu.com
 *
 */
public class ImageSizer {
    public static final MediaTracker tracker = new MediaTracker(new Component() {
        private static final long serialVersionUID = 1234162663955668507L;}
    );
    /**
     * @param originalFile 原图像
     * @param resizedFile 压缩后的图像
     * @param width 图像宽
     * @param format 图片格式 jpg, png, gif(非动画)
     * @throws IOException
     */
    public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {
        if(format!=null && "gif".equals(format.toLowerCase())){
         resize(originalFile, resizedFile, width, 1);
         return;
        }
        FileInputStream fis = new FileInputStream(originalFile);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int readLength = -1;
        int bufferSize = 1024;
        byte bytes[] = new byte[bufferSize];
        while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
            byteStream.write(bytes, 0, readLength);
        }
        byte[] in = byteStream.toByteArray();
        fis.close();
        byteStream.close();
       
     Image inputImage = Toolkit.getDefaultToolkit().createImage( in );
        waitForImage( inputImage );
        int imageWidth = inputImage.getWidth( null );
        if ( imageWidth < 1 )
           throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
        int imageHeight = inputImage.getHeight( null );
        if ( imageHeight < 1 )
           throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
       
        // Create output image.
        int height = -1;
        double scaleW = (double) imageWidth / (double) width;
        double scaleY = (double) imageHeight / (double) height;
        if (scaleW >= 0 && scaleY >=0) {
            if (scaleW > scaleY) {
                height = -1;
            } else {
                width = -1;
            }
        }
        Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);
        checkImage( outputImage );       
        encode(new FileOutputStream(resizedFile), outputImage, format);       
    }   

    /** Checks the given image for valid width and height. */
    private static void checkImage( Image image ) {
       waitForImage( image );
       int imageWidth = image.getWidth( null );
       if ( imageWidth < 1 )
          throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
       int imageHeight = image.getHeight( null );
       if ( imageHeight < 1 )
          throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
    }

    /** Waits for given image to load. Use before querying image height/width/colors. */
    private static void waitForImage( Image image ) {
       try {
          tracker.addImage( image, 0 );
          tracker.waitForID( 0 );
          tracker.removeImage(image, 0);
       } catch( InterruptedException e ) { e.printStackTrace(); }
    }

    /** Encodes the given image at the given quality to the output stream. */
    private static void encode( OutputStream outputStream, Image outputImage, String format )
       throws java.io.IOException {
       int outputWidth  = outputImage.getWidth( null );
       if ( outputWidth < 1 )
          throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" );
       int outputHeight = outputImage.getHeight( null );
       if ( outputHeight < 1 )
          throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" );

       // Get a buffered image from the image.
       BufferedImage bi = new BufferedImage( outputWidth, outputHeight,
          BufferedImage.TYPE_INT_RGB );                                                  
       Graphics2D biContext = bi.createGraphics();
       biContext.drawImage( outputImage, 0, 0, null );
       ImageIO.write(bi, format, outputStream);
       outputStream.flush();     
    }
   
 /**
  * 缩放gif图片
  * @param originalFile 原图片
  * @param resizedFile 缩放后的图片
  * @param newWidth 宽度
  * @param quality 缩放比例 (等比例)
  * @throws IOException
  */
    private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
        if (quality < 0 || quality > 1) {
            throw new IllegalArgumentException("Quality has to be between 0 and 1");
        }
        ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
        Image i = ii.getImage();
        Image resizedImage = null;
        int iWidth = i.getWidth(null);
        int iHeight = i.getHeight(null);
        if (iWidth > iHeight) {
            resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
        } else {
            resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
        }
        // This code ensures that all the pixels in the image are loaded.
        Image temp = new ImageIcon(resizedImage).getImage();
        // Create the buffered image.
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                                                        BufferedImage.TYPE_INT_RGB);
        // Copy image to buffered image.
        Graphics g = bufferedImage.createGraphics();
        // Clear background and paint the image.
        g.setColor(Color.white);
        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
        g.drawImage(temp, 0, 0, null);
        g.dispose();
        // Soften.
        float softenFactor = 0.05f;
        float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};
        Kernel kernel = new Kernel(3, 3, softenArray);
        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        bufferedImage = cOp.filter(bufferedImage, null);
        // Write the jpeg to a file.
        FileOutputStream out = new FileOutputStream(resizedFile);       
        // Encodes image as a JPEG data stream
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
        param.setQuality(quality, true);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(bufferedImage);
    }
}

 

 

----------------------------------------------------------------------------

 

 

import java.security.MessageDigest;

public class MD5 {
 private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
   "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

 /**
  * 转换字节数组为16进制字串
  *
  * @param b
  *            字节数组
  * @return 16进制字串
  */

 public static String byteArrayToHexString(byte[] b) {
  StringBuffer resultSb = new StringBuffer();
  for (int i = 0; i < b.length; i++) {
   resultSb.append(byteToHexString(b[i]));
  }
  return resultSb.toString();
 }

 private static String byteToHexString(byte b) {
  int n = b;
  if (n < 0)
   n = 256 + n;
  int d1 = n / 16;
  int d2 = n % 16;
  return hexDigits[d1] + hexDigits[d2];
 }

 public static String MD5Encode(String origin) {
  String resultString = null;

  try {
   resultString = new String(origin);
   MessageDigest md = MessageDigest.getInstance("MD5");
   resultString = byteArrayToHexString(md.digest(resultString
     .getBytes()));
  } catch (Exception ex) {

  }
  return resultString;
 }

}

 

 

 

---------------------------------------------------------------------------------

 

import java.io.IOException;
import java.util.Properties;

public class SiteUrl {
 private static Properties properties = new Properties();
 static{
  try {
   properties.load(SiteUrl.class.getClassLoader().getResourceAsStream("siteurl.properties"));
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 public static String readUrl(String key){  
  return (String)properties.get(key);
 }
}

 

 

------------------------------------------------------------------------------

 

 

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.bean.BuyCart;
import cn.itcast.bean.privilege.Employee;
import cn.itcast.bean.user.Buyer;

/**
 *
 * @author Administrator
 *
 */
public class WebUtil {
 /**
  * 获取登录员工
  */
 public static Employee getEmployee(HttpServletRequest request){
  return (Employee) request.getSession().getAttribute("employee");
 }
 /**
  * 获取登录用户
  */
 public static BuyCart getBuyCart(HttpServletRequest request){
  return (BuyCart)request.getSession().getAttribute("buyCart");
 }
 
 /**
  * 获取登录用户
  */
 public static Buyer getBuyer(HttpServletRequest request){
  return (Buyer) request.getSession().getAttribute("user");
 }
 /**
  * 删除购物车
  */
 public static void deleteBuyCart(HttpServletRequest request){
  request.getSession().removeAttribute("buyCart");
 }
    /***
     * 获取URI的路径,如路径为http://www.babasport.com/action/post.htm?method=add, 得到的值为"/action/post.htm"
     * @param request
     * @return
     */
    public static String getRequestURI(HttpServletRequest request){    
        return request.getRequestURI();
    }
    /**
     * 获取完整请求路径(含内容路径及请求参数)
     * @param request
     * @return
     */
    public static String getRequestURIWithParam(HttpServletRequest request){    
        return getRequestURI(request) + (request.getQueryString() == null ? "" : "?"+ request.getQueryString());
    }
    /**
     * 添加cookie
     * @param response
     * @param name cookie的名称
     * @param value cookie的值
     * @param maxAge cookie存放的时间(以秒为单位,假如存放三天,即3*24*60*60; 如果值为0,cookie将随浏览器关闭而清除)
     */
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {       
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        if (maxAge>0) cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
   
    /**
     * 获取cookie的值
     * @param request
     * @param name cookie的名称
     * @return
     */
    public static String getCookieByName(HttpServletRequest request, String name) {
     Map<String, Cookie> cookieMap = WebUtil.readCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie.getValue();
        }else{
            return null;
        }
    }
   
    protected static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (int i = 0; i < cookies.length; i++) {
                cookieMap.put(cookies[i].getName(), cookies[i]);
            }
        }
        return cookieMap;
    }
    /**
     * 去除html代码
     * @param inputString
     * @return
     */
    public static String HtmltoText(String inputString) {
        String htmlStr = inputString; //含html标签的字符串
        String textStr ="";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_style;
        java.util.regex.Matcher m_style;
        java.util.regex.Pattern p_html;
        java.util.regex.Matcher m_html;         
        java.util.regex.Pattern p_ba;
        java.util.regex.Matcher m_ba;
       
        try {
            String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; //定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script> }
            String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; //定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style> }
            String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
            String patternStr = "//s+";
           
            p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); //过滤script标签

            p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); //过滤style标签
        
            p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); //过滤html标签
           
            p_ba = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);
            m_ba = p_ba.matcher(htmlStr);
            htmlStr = m_ba.replaceAll(""); //过滤空格
        
         textStr = htmlStr;
        
        }catch(Exception e) {
                    System.err.println("Html2Text: " + e.getMessage());
        }         
        return textStr;//返回文本字符串
     }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值