Chinaunix首页 | 论坛 | 博客
  • 博客访问: 788610
  • 博文数量: 142
  • 博客积分: 10288
  • 博客等级: 上将
  • 技术积分: 2905
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-03 13:19
文章分类

全部博文(142)

文章存档

2019年(2)

2009年(51)

2008年(89)

分类: Java

2008-11-17 22:53:38

1 获取系统时间

import java.util.*;
import java.text.*;

String ddate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

2  关于验证码

A 实现一个servlet用来生成图片(当然也可以用jsp实现):

 import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.geom.GeneralPath;
import javax.swing.*;
import java.math.*;
public class Servlet1
extends HttpServlet {
//Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    response.setContentType("image/jpeg");  //必须设置ContentType为image/jpeg
    int length = 4;      //设置默认生成4个数字
    Date d = new Date();
    long lseed = d.getTime();
    java.util.Random r = new Random(lseed);   //设置随机种子
    if (request.getParameter("length") != null) {
      try {
       length = Integer.parseInt(request.getParameter("length"));
      }
      catch (NumberFormatException e) {
      }
    }
    StringBuffer str = new StringBuffer();
    for (int i = 0; i       str.append(r.nextInt(9));        //生成随机数字
}
//可以在此加入保存验证码的代码
    //创建内存图像
    BufferedImage bi = new BufferedImage(40, 16, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.clearRect(0, 0, 16, 40);
    g.setColor(Color.green.CYAN);
    g.drawString(str.toString(), 4, 12);
    try {
      //使用JPEG编码,输出到response的输出流
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.
      getOutputStream());
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
      param.setQuality(1.0f, false);
      encoder.setJPEGEncodeParam(param);
      encoder.encode(bi);
    }
    catch (Exception ex) {
    
    }
  }    
}   
然后在需求显示验证码的加入以下代码就可以了

将/WebModule1/servlet1替换成你用来生成验证码的servlet的全路径。

 B 生成带有干扰条纹的验证码

<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
Color getRandColor(int fc,int bc){//给定范围获得随机颜色
Random random = new Random();
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);
}
%>
<%
//设置页面不缓存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);

// 在内存中创建图象
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

// 获取图形上下文
Graphics g = image.getGraphics();

//生成随机类
Random random = new Random();

// 设定背景色
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);

//设定字体
g.setFont(new Font("Times New Roman",Font.PLAIN,18));

//画边框
g.setColor(new Color(255,255,255));
g.drawRect(0,0,width-1,height-1);

// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160,200));
for (int i=0;i<155;i++)
{
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<4;i++){
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
// 将认证码显示到图象中
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand,13*i+6,16);
}

// 将认证码存入SESSION
session.setAttribute("rand",sRand);

// 图象生效
g.dispose();

// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
%>

     关于表单验证:  表单其他项目最好能在客户端和服务器端都检验一次,否则可以将提交页面保存下来去掉scrpit控制,制成另一个提交页面提交一些我们不想要的东西了。

3 关于乱码的问题

要点:统一字符集(JSP页面编码,mysql建库时字符集选择,连接数据库URL,request设定等)
下面我以GBK为例讲解。如果要使用utf-8,只要在相应的GBK处换成utf-8即可
--------------------------- 步骤1 以GBK字符集建库建表 -------------------------------------
我使用EMS来建mysql的数据库及表,因为它是图形界面,方便操作(就像SQL SERVER 2000中的企业管理器一样)。
建库时,从EMS菜单中选create Database...新建一个数据库,CharacterSet选gbk_bin(另一个gbk_chinese_ci不知道与这个有什么区别,我找资料也没有找到。如果你知道,请告诉我,我补充在这里)。不要把工具栏上有一个加号和数据库模样的图标当成新建数据库了,那个新注册一个已经存在的数据库。
后面建表时,也要选择同样的字符集。
建好后,此时不要用EMS向里面插入数据,否则你看到的中文依然是乱码。
--------------------------- 步骤2 连接数据库的URL后加些参数 -------------------------------
假设我新建的数据库是testdb,那么我连接数据库的url应该为:
jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=gbk
此时要注意:如果我是把这个url写在JAVA代码中,就直接这样写。但如果是在xml配置文件中(如struts-config.xml,web.xml等),要把其中的&改为&才行,否则会出错。也就是:
jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=gbk
--------------------------- 步骤3 每个JSP页面都要声明该中文字符集 ----------------------------
在每个JSP页面的最上面都加上一句
<%@ page language="java" contentType="text/html;charset=GBK" %>
这样才能保证JSP页面中的中文显示正常
--------------------------- 步骤4 加一个传递参数时设定request字符集的filter类 -----------------------
因为网络中字符在传递的时候,都是统一以iso-8859-1的编码传递,所以我们必须对request重新设定字符集,才能正常显示中文。如果采用filter类来实现,我们不用在每次取中文参数时都要重新设定。
filter类的内容:
/*
* ====================================================================
*
* JavaWebStudio 开源项目
*
* Struts_db v0.1
*
* ====================================================================
*/
package com.strutsLogin.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 中文过滤器
*/
public class SetCharacterEncodingFilter implements Filter {
// ----------------------------------------------------- Instance Variables
/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;
/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;
/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;
// --------------------------------------------------------- Public Methods
/**
* Take this filter out of service.
*/
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
// ------------------------------------------------------ Protected Methods
/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
* null.
*


* The default implementation unconditionally returns the value configured
* by the encoding initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
*/
protected String selectEncoding(ServletRequest request) {

return (this.encoding);
}
}//EOC

该代码来自于,特此感谢!
然后我们在web.xml中加一些配置,就可以了,配置如下:

Set Character Encoding
javawebstudio.struts_db.SetCharacterEncodingFilter

encoding
GBK


ignore
true


Set Character Encoding
action
放在web.xml的合适位置。一般在最后,标签之前(如果有的话)
经过以上步骤,JSP和mysql的中文显示及插入就都正常了。在STRUTS中也正常。
但是,此时如果你用EMS或mysql的命令行控制台来看表中的数据,却发现它们都是????。这是怎么回事呢?
不用担心,只要我们运行下面的这几行命令,就能看到正常的中文了!
SET character_set_client = gbk;
SET character_set_connection = gbk;
SET character_set_database = gbk;
SET character_set_results = gbk;
SET character_set_server = gbk;
SET collation_connection = gbk_bin;
SET collation_database = gbk_bin;
SET collation_server = gbk_bin;
如果你用的是mysql的命令行,则直接输入就好。
如果是EMS,则在工具栏中有一个Show SQL Editor按钮,点一下,把上面的命令输入,再按一个"execute"的按钮,就行了!
而且在这种情况下,你可以甚至可以用中文名来建数据库,表名和字段名!!!!
----------------------------------------------------------------------------------------------------
但是有一点要特别注意!
像GBK,UTF-8这样的名字,在mysql与JAVA中有不同的规定,写的时候要格外注意,否则会出错。
比如GBK,在JAVA中要写成GBK,但在mysql中要写成gbk(连接数据库的URL)
比如UTF-8,在JAVA中要写成UTF-8,但在Mysql中要写成utf8
其它的字集符也有类似的区别
利用上面的一些代码,然后老老实实的根据页面安排,逻辑关系写好各个页面的代码,就是建设网站的现在任务了,然后是网站的优化,这个不懂,觉得很重要。
阅读(1382) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2008-11-17 22:55:33

JSP常用代码 1。 获取当前路径 request.getRealPath("/") 当前文件名 request.getServletPath() 服务器名 request.getServerName() 服务器端口 request.getServerPort() 服务器时间 out.println( new java.util.Date() ) //Wed Mar 22 17:10:45 CST 2006 String date=new Date().toLocaleString(); //2006.3.22 19:20:11 本文件路径 request.getPathTranslated() 获得客户IP request.getRemoteAddr() 请求URL request.getRequestURL() 重定向 response.sendRedirect("login"); //response.setHeader("refresh","3600");刷新 2。注释 <%-- 代码--%> 如:<%----------------------