Java servlet/jsp Multi-language solution (ii)

Source: Internet
Author: User
Tags date getmessage http post insert integer sql tostring stringbuffer
Js|servlet| that's what I did, set up a servlet base class that overrides the service method, calling the service side of the parent class
Read and parse the form submission before the method, please see the following source code:
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: Chan Weichun
*/
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 ());
}
}
}
The function of this class is to read and save the information submitted by form and implement the common GetParameter method.
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: Chan Weichun
*/
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));
Super.service (Request,response);
}
}
This is the servlet base class, which overrides the service method of the parent class, and before invoking the parent service, create
A Utf8parameterreader object that holds the information submitted in the form. And then take this object as a
attribute is saved to the request object. The service method of the parent class is then called.
For the servlet that inherits this class, it should be noted that the "standard" getparameter cannot read the post
Data, because the data is already read from the ServletInputStream in this class. So we should make
Use the GetParameter method provided in this class.
The rest is the output problem, we want to transfer the output of the information to the UTF8 of the binary stream output. As long as I
When you set Content-type to specify CharSet as UTF8 and then use printwriter output, these conversions
is done automatically, in the servlet setting:
Response.setcontenttype ("Text/html;charset=utf8");
This setting in the JSP:
<%@ page contenttype= "Text/html;charset=utf8"%>
This will ensure that the output is UTF8 flow, the client can be displayed, look at the client.
For the content submitted by the Multipart/form-data form, I also provide a class to handle, in this class
The constructor can specify the charset used by the page, default or UTF-8, limited to the length of the source code, if
Interested can mail to:vividq@china.com and I explore.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.