java其他工具类

抓取网页


import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
    URL url = new URL("http://jj.24365pt.com/index.jhtml");

    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    InputStream in = null;
    in = url.openStream();
    String content = pipe(in,"utf-8");
    System.out.println(content);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 static String pipe(InputStream in,String charset) throws IOException {
        StringBuffer s = new StringBuffer();
        if(charset==null||"".equals(charset)){
         charset="utf-8";
        }
        String rLine = null;
        BufferedReader bReader = new BufferedReader(new InputStreamReader(in,charset));
        PrintWriter pw = null;
       
  FileOutputStream fo = new FileOutputStream("../index.html");
  OutputStreamWriter writer = new OutputStreamWriter(fo, "utf-8");
  pw = new PrintWriter(writer);
        while ( (rLine = bReader.readLine()) != null) {
            String tmp_rLine = rLine;
            int str_len = tmp_rLine.length();
            if (str_len > 0) {
              s.append(tmp_rLine);
              pw.println(tmp_rLine);
              pw.flush();
            }
            tmp_rLine = null;
       }
        in.close();
        pw.close();
        return s.toString();
 }
}

 


以前工作的时候由于Oracle8i数据库经常出现用户过多的错误,由于数据量大,经常出现ORA:12500错误,但主要原因是访问过多而引起的,后来就用Java写了个简单的用JDBC连接来测试Oracle最大连接数的程序.现在常用MySQL,所以又写了一个简单的测试其最大连接数的程序,在此介绍给大家:


import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.Statement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.io.IOException;
 
 class testMaxConn{
   public static void main(String args[]){
     int count=0;
     Connection []conn=new Connection[1000];
     Statement  []stmt =new Statement[1000];
     ResultSet  []rs =new ResultSet[1000];
    try{
     Class.forName
("com.MySQL.jdbc.Driver").newInstance();
for(count=0;count<300;count++){
conn[count] = DriverManager.getConnection
("jdbc:mysql://localhost/MySQL", "root", "");
      stmt[count]=conn[count].createStatement();
      rs[count]=stmt[count].executeQuery
("SELECT * FROM user");
      while (rs[count].next()){
  //System.out.println(rs.getString(1)+
"\t "+rs.getString(2)); 
      }
      System.out.print(count+"\t");
     }
    
    
    }catch(SQLException ex1){
      System.out.println("\n"+ex1.toString());
    }catch(InstantiationException ex2){
      System.out.println("\n"+ex2.toString());
    }catch(ClassNotFoundException ex3){
      System.out.println("\n"+ex3.toString());
    }catch(IllegalAccessException ex4){
      System.out.println("\n"+ex4.toString());
    }finally{
      try{
        System.out.println("\nSystem has opened
"+count--+" MySQL connections.\nPress Enter key
to close the connections");
        System.in.read();
        System.out.println
("\nClose the Connections:");
        for(;count>=0;count--){
         rs[count].close();
         stmt[count].close();
         conn[count].close();
         System.out.print(count+"\t");
        }
      }catch(SQLException ex){
       System.out.println
("\n Close connection exception:"+ex.toString());
      }catch(IOException io_ex){}
    }//end the first "try"
   }
 }

获取汉字拼音首字母的工具类 

 

public class GetCh2Spell {
    public static int compare(String str1, String str2)
     {
         int result = 0;
         String m_s1 = null;
         String m_s2 = null;
         try
         {
             m_s1 = new String(str1.getBytes(_FromEncode_), _ToEncode_);
             m_s2 = new String(str2.getBytes(_FromEncode_), _ToEncode_);
         }
         catch(Exception e)
         {
             return str1.compareTo(str2);
         }
         result = chineseCompareTo(m_s1, m_s2);
         return result;
     }
     public static int getCharCode(String s)
     {
         if(s == null && s.equals(""))
             return -1;
         byte b[] = s.getBytes();
         int value = 0;
         for(int i = 0; i < b.length && i <= 2; i++)
             value = value * 100 + b[i];
         return value;
}

}

 

验证码工具类

 

<%@page import="java.io.*,java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*"%>
<%
/*
使用方法:在需要显示验证码的html代码中使用<img p">
  在需判断session的时候判断session.getAttribute("YZKL")
*/
  int codeLength=5;//验证码长度
  int mixTimes=20;//模糊程度参数
  Color bgColor=getRandColor(200, 250);//背景颜色
  Color bfColor=new Color(0,0,0);//字体颜色
  boolean ifRandomColor=true;//单个字符是否颜色随机
  boolean ifMixColor=false;//模糊线是否颜色随机

 


  //设置页面不缓存
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);
  // 在内存中创建图象
  int width = 13*codeLength+6, height = 20;
  BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
  // 获取图形上下文
  Graphics g = image.getGraphics();
  // 设定背景色
  g.setColor(bgColor);
  g.fillRect(0, 0, width, height);
  //设定字体
  g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
  //画边框
  g.setColor(new Color(33,66,99));
  g.drawRect(0,0,width-1,height-1);
  // 随机产生干扰线,使图象中的认证码不易被其它程序探测到
  g.setColor(getRandColor(160, 200));
  for (int i = 0; i < mixTimes*codeLength/10; i++) {
 if(ifMixColor)
 {
  g.setColor(getRandColor(160, 200));
 }
 int x = random.nextInt(width);
    int y = random.nextInt(height);
    int xl = random.nextInt(12);
    int yl = random.nextInt(12);
    g.drawLine(x, y, x + xl, y + yl);
  }
  // 取随机产生的认证码(4位数字)
  String sRand = "";
  for (int i = 0; i < codeLength; i++) {
    String rand = String.valueOf(random.nextInt(10));
    sRand += rand;
    // 将认证码显示到图象中
 if(ifRandomColor)
  g.setColor(getRandColor(20,110,0));
 else
  g.setColor(bfColor);
 //调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
    g.drawString(rand, 13 * i + 6, 16);
  }
  // 将认证码存入SESSION
  session.setAttribute("YZKL", sRand);
  // 图象生效
  g.dispose();
  // 输出图象到页面
  ImageIO.write(image, "PNG", response.getOutputStream());
%>
<%!
//给定范围获得随机颜色
private static Random random=new Random();
private Color getRandColor(int fc, int bc) {
  return getRandColor(fc, bc, fc);
}
private Color getRandColor(int fc, int bc,int interval) {
  if (fc > 255) {
    fc = 255;
  }
  if (bc > 255) {
    bc = 255;
  }
  int r = fc + random.nextInt(bc - interval);
  int g = fc + random.nextInt(bc - interval);
  int b = fc + random.nextInt(bc - interval);
  return new Color(r, g, b);
}
%>

 中文验证码

 

/*
一个验证图形生成程序. 支持中文的验证码生成程序. 写的时候没有仔细看, 可能有小问题.但是运行没有任何问题.

    使用方法 :
    <tr><td>&nbsp;验 证 码:&nbsp;</td>
    <td><input tabindex=3 maxlength=4 size=4 name=yzmimg usage="int" tip="验证码请输入阿拉伯数字!" title="输入阿拉伯数字"/>&nbsp;</td>
    <td><a href="javascript:refreshImg('validateCodeImg');"><img src="yzmImg.jsp" alt="请在左侧输入对应的阿拉伯数字" name="validateCodeImg" border=0 align="absmiddle" id="validateCodeImg" /></a>
    输入对应阿拉伯数字.看不清点请点击更换</td></tr>

 

    <script language="javascript" type="text/javascript">
    function refreshImg(imgID){var img = document.getElementById(imgID);  img.src = img.src;}
    </script>

    生成图形的jsp文件:
*/

    <%@page session="true" contentType="image/jpeg; charset=gb2312"

    import="java.awt.image.*,java.awt.*"

    import="java.util.*"

    import="javax.servlet.*"

    import="javax.servlet.http.*"

    import="javax.imageio.*"

    import="java.io.OutputStream"

    import="java.io.OutputStream"

    %><%!

      private int iCharHeight = 20;

      private int iCharCnt = 4;

      private int iMaxOffset = 8; //字符位置左右最大便宜像素

      private int iImgWidth = 20*iCharCnt + iMaxOffset*2; //图片宽度

      private int iImgHeight = iCharHeight + 5; //图片高度

      private int iDisturbLineCnt = 8; //干扰线数量

      //

      //private String Src = "零壹贰叁肆伍陆柒捌玖";

      private String Src = "零一二三四五六七八九";

      //private String Src = "的了是我不在人们有来他这上着个地到大里说就去子得也和那要下看天时过出小么起你都把好还多没为又可家学只以主会样年想生同老中十从自面前头道它后然走很像见两用她国动进成回什边作对开而己些现山民候经发工向事命给长水几义三声于高手知理眼志点心战二问但身方实吃做叫当住听革打呢真全才四已所敌之最光产情路分总条白话东席次亲如被花口放儿常气五第使写军吧文运再果怎定许快明行因别飞外树物活部门无往船望新带队先力完却站代员机更九您每风级跟笑啊孩万少直意夜比阶连车重便斗马哪化太指变社似士者干石满日决百原拿群究各六本思解立河村八难早论吗根共让相研今其书坐接应关信觉步反处记将千找争领或师结块跑谁草越字加脚紧爱等习阵怕月青半火法题建赶位唱海七女任件感准张团屋离色脸片科倒睛利世刚且由送切星导晚表够整认响雪流未场该并底深刻平伟忙提确近亮轻讲农古黑告界拉名呀土清阳照办史改历转画造嘴此治北必服雨穿内识验传业菜爬睡兴形量咱观苦体众通冲合破友度术饭公旁房极南枪读沙岁线野坚空收算至政城劳落钱特围弟胜教热展包歌类渐强数乡呼性音答哥际旧神座章帮啦受系令跳非何牛取入岸敢掉忽种装顶急林停息句区衣般报叶压慢叔背细";

      String[] strFontNames = {

          "隶书", "华文新魏", "黑体", "幼圆", "楷体_GB2312", "新宋体", "华文彩云"};

      private int FONTSTYLE = Font.BOLD | Font.ITALIC;

 //

      private String getRandomStr(Random random, int cnt, StringBuffer sbNum) {

        String str = "";

        int max = Src.length();

        for (int i = 0; i < cnt; i++) {

          int t = random.nextInt(max);

          str += Src.charAt(t);

          sbNum.append(t);

        }

        return str;

      }
//生成随机颜色

      Color getRandColor(Random random, int fc, int bc) {

        if (fc > 255)

          fc = 255;

        if (bc > 255)

          bc = 255;

        int r = fc + random.nextInt(bc - fc);

        int g = fc + random.nextInt(bc - fc);

        int b = fc + random.nextInt(bc - fc);

        return new Color(r, g, b);

      }

    %><%

      String strText = "";

      try {

        Date now = new Date();

        Random random = new Random(now.getTime());

        now = null;

        StringBuffer bufNum = new StringBuffer("");

        strText = getRandomStr(random, iCharCnt, bufNum);

 

        response.setHeader("Cache-Control", "no-store"); //HTTP 1.1

        response.setHeader("Pragma", "no-cache"); //HTTP 1.0

        response.setDateHeader("Expires", 0); //prevents caching at the proxy server

        BufferedImage image = new BufferedImage(iImgWidth, iImgHeight, BufferedImage.TYPE_INT_RGB);

        Graphics g = image.getGraphics();

      // 设定图像背景色(因为是做背景,所以偏淡)

        g.setColor(getRandColor(random, 200, 250));

        g.fillRect(0, 0, iImgWidth, iImgHeight);

      //画边框

        g.setColor(Color.black);

        g.drawRect(0, 0, iImgWidth - 1, iImgHeight - 1);

        //干扰线

for (int k = 0; k < iDisturbLineCnt; k++)

        {

          g.setColor(getRandColor(random, 160, 200));

          g.drawLine(random.nextInt(iImgWidth), random.nextInt(iImgHeight), random.nextInt(iImgWidth), random.nextInt(iImgHeight));

        }
int startx = 0;

        int strWidth = 0;

        for (int i = 0; i < iCharCnt; i++) {

          g.setColor(getRandColor(random, 10, 150));

          char ch = strText.charAt(i);

          String fname = strFontNames[random.nextInt(strFontNames.length)];

          Font f = new Font(fname, FONTSTYLE, iCharHeight);

          System.out.println(fname + "  " + ch);

          g.setFont(f);

          g.drawString("" + ch, startx + strWidth + random.nextInt(iMaxOffset), iCharHeight);

          java.awt.FontMetrics fm = g.getFontMetrics();

          strWidth += fm.charWidth(ch);

          fm = null;

        }

      // 图象生效

        g.dispose();

        ServletOutputStream responseOutputStream = response.getOutputStream();

        // 输出图象到页面

        ImageIO.write(image, "JPEG", responseOutputStream);

        //以下关闭输入流!~~~

        responseOutputStream.flush();

        responseOutputStream.close();

        /**//*

        ServletOutputStream outstream = response.getOutputStream();

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outstream);

        encoder.encode(image);

        outstream.close();

        */

        // 将认证码存入SESSION

        session.setAttribute("YZMIMAGE", bufNum.toString());

        random = null;

        bufNum = null;

        image = null;

      }

      catch (Exception ex) {ex.printStackTrace();  }%>

 

jsp分页

 

<%@ page contentType="text/html;charset=gbk"%>
<%
    // 页面连接路径
    String jspUrl = null ;
    // 定义如下分页变量
    // 1、定义没页要显示的记录数,默认是10条每页
    int lineSize = 10 ;
    // 2、定义一个当前是第几页
    int currentPage = 1 ;
    // 计算出总页数
    int pageSize = 0 ;
    // 总记录数 / 每页显示的记录数
    int allRecorders = 0 ;
    // 加入查询关键字变量
    String keyWord = null ;
    // 加入一个检索标记
    String searchFlag = "F" ;
%>
<%
    // 需要从外面接收以下参数
    // 当前页、每页显示的记录数、总记录数、查询关键字、连接地址
    jspUrl = request.getParameter("jspUrl") ;
    keyWord = request.getParameter("keyWord") ;
    searchFlag = request.getParameter("searchFlag") ;
    try
    {
        lineSize = Integer.parseInt(request.getParameter("lineSize")) ;
        currentPage = Integer.parseInt(request.getParameter("currentPage")) ;
        allRecorders = Integer.parseInt(request.getParameter("allRecorders")) ;
    }
    catch(Exception e)
    {
        // s
    }
%>
<%
    // 计算总页数
    pageSize = (allRecorders+lineSize-1)/lineSize ;
%>
<script language="javaScript">
    function openPage(curpage)
    {
        document.spage.cp.value = curpage ;
        // alert(cupage) ;
        document.spage.submit() ;
    }
    function selOpenPage()
    {
        document.spage.cp.value = document.spage.selpage.value ;
        document.spage.submit() ;
    }
    function change()
    {
        if(document.spage.kw.value!="")
        {
            document.spage.status.value = "selectlike" ;
        }
    }
</script>
<form name="spage" action="<%=jspUrl%>" onSubmit="change()">
<input type="hidden"
    name="status" value="${status}"> <input type="hidden"
    name="${param.flagname}" value=${param.flagvalue}> <%
 if ("T".equals(searchFlag)) {
 %> 输入查询关键字:<input type="text" name="kw"
    value="<%=keyWord.equals("null") ? "" : keyWord%>"> <input
    type="submit" value="查询"> <br>
<br>
<%
}
%> <%
 if (allRecorders > 0) {
 %> <input type="button" value="首页" onClick="openPage(1)"
    <%=currentPage == 1 ? "disabled" : ""%>> <input type="button"
    value="上一页" onClick="openPage(<%=currentPage - 1%>)"
    <%=currentPage == 1 ? "disabled" : ""%>> <input type="button"
    value="下一页" onClick="openPage(<%=currentPage + 1%>)"
    <%=currentPage == pageSize ? "disabled" : ""%>> <input type="button"
    value="尾页" onClick="openPage(<%=pageSize%>)"
    <%=currentPage == pageSize ? "disabled" : ""%>> <input type="hidden"
    name="cp" value=""> <font color="red" size="5"><%=currentPage%></font>
/ <font color="red" size="5"><%=pageSize%></font> 跳转到 <select
    name="selpage" onChange="selOpenPage()">
    <%
    for (int x = 1; x <= pageSize; x++) {
    %>
    <option value="<%=x%>" <%=currentPage == x ? "selected" : ""%>><%=x%></option>
    <%
    }
    %>
</select> 页 <%
}
%>
</form>

 

cookie计数


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
 * <p>Title: servlet读取cookie</p>
 * <p>Description: 这个servlet演示怎样创建和获取cookie并设置cookie的期限</p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Filename: CookieCounter.java</p>
 * @author 杜江
 * @version 1.0
 */
//必须继承HttpServlet类
public class CookieCounter extends HttpServlet {
  private int pageCount = 0;

/**
 *<br>方法说明:初始化
 *<br>输入参数:ServletConfig config 服务器配置对象
 *<br>返回类型:
 */

  public void init(ServletConfig config) throws ServletException  {
    super.init(config);
  }
/**
 *<br>方法说明:实现service方法
 *<br>输入参数:HttpServletRequest req 客户请求对象
 *<br>输入参数:HttpServletResponse res 服务器应答对象
 *<br>返回类型:
 */
  public void service(HttpServletRequest req, HttpServletResponse res)
       throws IOException
  {
    boolean cookieFound = false;
    Cookie thisCookie = null;
   
    // 设置内容类型
    res.setContentType("text/html; charset=GB2312");
    // 调用getWriter()
    PrintWriter out = res.getWriter();
   
    // 从请求获取coolies
    Cookie[] cookies = req.getCookies();
   
    if(cookies!=null){
      for(int i=0; i < cookies.length; i++) {
        thisCookie = cookies[i];
        //检查是否存在CookieCount数据
        if (thisCookie.getName().equals("CookieCount")) {
          cookieFound = true;
          break;
        }
      }
    }
    if (cookieFound == false) {
      // 创建新的Cookie并设置它的存活期
      thisCookie = new Cookie("CookieCount", "1");
      thisCookie.setMaxAge(60*1);
      // 在response对象中加入cookie
      res.addCookie(thisCookie);
    }
    //输出页面
    out.println("<html><head>\n" + "<title>Cookie计数器</title></head><body>\n" +
                "<center><h1>Cookie 计数器</h1></center></font>");
    pageCount++;
    out.println("<p>");
    out.println("<font color=blue size=+1>");
    out.println("<p><br><br><br>这个页面您已经拜访了 " + pageCount +
                " 次.\n");
   
    // 显示客户端详细信息,是否存在计数器cookie
    if (cookieFound) {
      int cookieCount = Integer.parseInt(thisCookie.getValue());
      cookieCount++;
      // 设置cookie的新值, 加到相应对象中
      thisCookie.setValue(String.valueOf(cookieCount));
      thisCookie.setMaxAge(10);
      res.addCookie(thisCookie);
     
      out.println("<p>这是你近10秒内第 " +
                  thisCookie.getValue() +
                  " 次拜访这一页\n");
     
    } else {
      out.println("<p>你在近10秒内没有拜访过此页或者你的浏览器不支持cookie "+
                  "如果你的浏览器支持cookie,请确认是否打开了!\n");
    }
    out.println("</body></html>");
   
  }
}

 

 

 

 



 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值