Java Servlet/Jsp多语言解决方案(二)

作者:网络 来源:佚名 更新时间:2008-06-11 17:19:27 点击:
我是这么做的,建立一个servlet基类,覆盖service方法,在调用父类的service方
法前读取并解析form提交的内容,请看下面的源代码:
package com.hto.servlet;
import javax.servlet.http.httpservletrequest;
import java.util.*;
/**
* insert the type's description here.
* creation date: (2001-2-4 15:43:46)
* @author: 钱卫春
*/
public class utf8parameterreader {
hashtable pairs = new hashtable();
/**
* utf8parameterreader constructor comment.
*/
public utf8parameterreader(httpservletrequest request) throws java.io.ioexce
ption{
super();
parse(request.getquerystring());
parse(request.getreader().readline());
}
/**
* utf8parameterreader constructor comment.
*/
public utf8parameterreader(httpservletrequest request,string encoding) throw
s java.io.ioexception{
super();
parse(request.getquerystring(),encoding);
parse(request.getreader().readline(),encoding);
}
public static string decode(string s) throws exception {
stringbuffer sb = new stringbuffer();
for(int i=0; i<s.length(); i++) {
char c = s.charat(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
try {
sb.append((char)integer.parseint(
s.substring(i+1,i+3),16));
}
catch (numberformatexception e) {
throw new illegalargumentexception();
}
i += 2;
break;
default:
sb.append(c);
break;
}
}
// undo conversion to external encoding
string result = sb.tostring();
byte[] inputbytes = result.getbytes("8859_1");
return new string(inputbytes,"utf8");
}
public static string decode(string s,string encoding) throws exception {
stringbuffer sb = new stringbuffer();
for(int i=0; i<s.length(); i++) {
char c = s.charat(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
try {
sb.append((char)integer.parseint(
s.substring(i+1,i+3),16));
}
catch (numberformatexception e) {
throw new illegalargumentexception();
}
i += 2;
break;
default:
sb.append(c);
break;
}
}
// undo conversion to external encoding
string result = sb.tostring();
byte[] inputbytes = result.getbytes("8859_1");
return new string(inputbytes,encoding);
}
/**
* insert the method's description here.
* creation date: (2001-2-4 17:30:59)
* @return java.lang.string
* @param name java.lang.string
*/
public string getparameter(string name) {
if (pairs == null || !pairs.containskey(name)) return null;
return (string)(((arraylist) pairs.get(name)).get(0));
}
/**
* insert the method's description here.
* creation date: (2001-2-4 17:28:17)
* @return java.util.enumeration
*/
public enumeration getparameternames() {
if (pairs == null) return null;
return pairs.keys();
}
/**
* insert the method's description here.
* creation date: (2001-2-4 17:33:40)
* @return java.lang.string[]
* @param name java.lang.string
*/
public string[] getparametervalues(string name) {
if (pairs == null || !pairs.containskey(name)) return null;
arraylist al = (arraylist) pairs.get(name);
string[] values = new string[al.size()];
for(int i=0;i<values.length;i++)
values[i] = (string) al.get(i);
return values;
}
/**
* insert the method's description here.
* creation date: (2001-2-4 20:34:37)
* @param urlenc java.lang.string
*/
private void parse(string urlenc) throws java.io.ioexception{
if (urlenc == null) return;
stringtokenizer tok = new stringtokenizer(urlenc,"&");
try{
while (tok.hasmoretokens()){
string apair = tok.nexttoken();
int pos = apair.indexof("=");
string name = null;
string value = null;
if(pos != -1){
name = decode(apair.substring(0,pos));
value = decode(apair.substring(pos+1));
}else{
name = apair;
value = "";
}
if(pairs.containskey(name)){
arraylist values = (arraylist)pairs.get(name);
values.add(value);
}else{
arraylist values = new arraylist();
values.add(value);
pairs.put(name,values);
}
}
}catch(exception e){
throw new java.io.ioexception(e.getmessage());
}
}
/**
* insert the method's description here.
* creation date: (2001-2-4 20:34:37)
* @param urlenc java.lang.string
*/
private void parse(string urlenc,string encoding) throws java.io.ioexception
{
if (urlenc == null) return;
stringtokenizer tok = new stringtokenizer(urlenc,"&");
try{
while (tok.hasmoretokens()){
string apair = tok.nexttoken();
int pos = apair.indexof("=");
string name = null;
string value = null;
if(pos != -1){
name = decode(apair.substring(0,pos),encoding);
value = decode(apair.substring(pos+1),encoding);
}else{
name = apair;
value = "";
}
if(pairs.containskey(name)){
arraylist values = (arraylist)pairs.get(name);
values.add(value);
}else{
arraylist values = new arraylist();
values.add(value);
pairs.put(name,values);
}
}
}catch(exception e){
throw new java.io.ioexception(e.getmessage());
}
}
}
这个类的功能就是读取并保存form提交的信息,并实现常用的getparameter方法。
package com.hto.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* insert the type's description here.
* creation date: (2001-2-5 8:28:20)
* @author: 钱卫春
*/
public class utfbaseservlet extends httpservlet {
public static final string params_attr_name = "params_attr_name";
/**
* process incoming http get requests
*
* @param request object that encapsulates the request to the servlet
* @param response object that encapsulates the response from the servlet
*/
public void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
performtask(request, response);
}
/**
* process incoming http post requests
*
* @param request object that encapsulates the request to the servlet
* @param response object that encapsulates the response from the servlet
*/
public void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
performtask(request, response);
}
/**
* insert the method's description here.
* creation date: (2001-2-5 8:52:43)
* @return int
* @param request javax.servlet.http.httpservletrequest
* @param name java.lang.string
* @param required boolean
* @param defvalue int
*/
public static java.sql.date getdateparameter(httpservletrequest request, str
ing name, boolean required, java.sql.date defvalue) throws servletexception{

string value = getparameter(request,name,required,string.valueof(defvalue));

return java.sql.date.valueof(value);
}
/**
* insert the method's description here.
* creation date: (2001-2-5 8:52:43)
* @return int
* @param request javax.servlet.http.httpservletrequest
* @param name java.lang.string
* @param required boolean
* @param defvalue int
*/
public static double getdoubleparameter(httpservletrequest request, string n
ame, boolean required, double defvalue) throws servletexception{
string value = getparameter(request,name,required,string.valueof(defvalue));

return double.parsedouble(value);
}
/**
* insert the method's description here.
* creation date: (2001-2-5 8:52:43)
* @return int
* @param request javax.servlet.http.httpservletrequest
* @param name java.lang.string
* @param required boolean
* @param defvalue int
*/
public static float getfloatparameter(httpservletrequest request, string nam
e, boolean required, float defvalue) throws servletexception{
string value = getparameter(request,name,required,string.valueof(defvalue));

return float.parsefloat(value);
}
/**
* insert the method's description here.
* creation date: (2001-2-5 8:52:43)
* @return int
* @param request javax.servlet.http.httpservletrequest
* @param name java.lang.string
* @param required boolean
* @param defvalue int
*/
public static int getintparameter(httpservletrequest request, string name, b
oolean required, int defvalue) throws servletexception{
string value = getparameter(request,name,required,string.valueof(defvalue));

return integer.parseint(value);
}
/**
* insert the method's description here.
* creation date: (2001-2-5 8:43:36)
* @return java.lang.string
* @param request javax.servlet.http.httpservletrequest
* @param name java.lang.string
* @param required boolean
* @param defvalue java.lang.string
*/
public static string getparameter(httpservletrequest request, string name, b
oolean required, string defvalue) throws servletexception{
if(request.getattribute(utfbaseservlet.params_attr_name) != null) {
utf8parameterreader params = (utf8parameterreader)request.getattribute(utfba
seservlet.params_attr_name);
if (params.getparameter(name) != null) return params.getparameter(name);
if (required) throw new servletexception("the parameter "+name+" required bu
t not provided!");
else return defvalue;
}else{
if (request.getparameter(name) != null) return request.getparameter(name);
if (required) throw new servletexception("the parameter "+name+" required bu
t not provided!");
else return defvalue;
}
}
/**
* returns the servlet info string.
*/
public string getservletinfo() {
return super.getservletinfo();
}
/**
* insert the method's description here.
* creation date: (2001-2-5 8:52:43)
* @return int
* @param request javax.servlet.http.httpservletrequest
* @param name java.lang.string
* @param required boolean
* @param defvalue int
*/
public static java.sql.timestamp gettimestampparameter(httpservletrequest re
quest, string name, boolean required, java.sql.timestamp defvalue) throws se
rvletexception{
string value = getparameter(request,name,required,string.valueof(defvalue));

return java.sql.timestamp.valueof(value);
}
/**
* initializes the servlet.
*/
public void init() {
// insert code to initialize the servlet here
}
/**
* process incoming requests for information
*
* @param request object that encapsulates the request to the servlet
* @param response object that encapsulates the response from the servlet
*/
public void performtask(httpservletrequest request, httpservletresponse resp
onse) {
try
{
// insert user code from here.
}
catch(throwable theexception)
{
// uncomment the following line when unexpected exceptions
// are occuring to aid in debugging the problem.
//theexception.printstacktrace();
}
}
/**
* insert the method's description here.
* creation date: (2001-2-5 8:31:54)
* @param request javax.servlet.servletrequest
* @param response javax.servlet.servletresponse
* @exception javax.servlet.servletexception the exception description.
* @exception java.io.ioexception the exception description.
*/
public void service(servletrequest request, servletresponse response) throws
javax.servlet.servletexception, java.io.ioexception {
string content = request.getcontenttype();
if(content == null || content != null && content.tolowercase().startswith("a
pplication/x-www-form-urlencoded"))
request.setattribute(params_attr_name,new utf8parameterreader((httpservletre
quest)request));
super.service(request,response);
}
}
  这个就是servlet基类,它覆盖了父类的service方法,在调用父类service前,创建
了utf8parameterreader对象,其中保存了form中提交的信息。然后把这个对象作为一个
attribute保存到request对象中。然后照样调用父类的service方法。
  对于继承这个类的servlet,要注意的是,"标准"getparameter在也不能读到post的
数据,因为在这之前这个类中已经从servletinputstream中读出了数据了。所以应该使
用该类中提供的getparameter方法。
  剩下的就是输出问题了,我们要把输出的信息,转为utf8的二进制流输出。只要我
们设置content-type时指定charset为utf8,然后使用printwriter输出,那么这些转换
是自动进行的,servlet中这样设置:
  response.setcontenttype("text/html;charset=utf8");
jsp中这样设置:
  <%@ page contenttype="text/html;charset=utf8"%>
  这样就可以保证输出是utf8流,客户端能否显示,就看客户端的了。
  对于multipart/form-data的form提交的内容,我也提供一个类用来处理,在这个类
的构造子中可以指定页面使用的charset,默认还是utf-8,限于篇幅不贴出源码,如果
感兴趣可以mail to:[email protected]和我探讨。