Javaweb's Request/response Code cultivation chapter (v)

Source: Internet
Author: User
Tags response code

1. Solve Chinese character encoding problem
String str = "I love Java";//The first method Response.setcontenttype ("TEXT/HTML;CHARSET=GBK");(recommended)//The second method//response.setheader (" Content-type "," text/html;charset=utf-8 ");//The Third method//response.getoutputstream (). Write (" <meta http-equiv= " Content-type ' content= ' text/html;charset=utf-8 ' > '. getBytes ()); Response.getoutputstream (). Write (Str.getbytes ( ));

2. Firefox Chinese file name download problem
String path = "/web-inf/classes/hello. jpg"; String filename = path.substring (Path.lastindexof ("/") +1); String Absolutepath = Getservletcontext (). Getrealpath (path), if (Request.getheader ("User-agent"). Contains ("Firefox" ) {Response.setheader ("content-disposition", "attachment;filename=" +encodedownloadfilename (filename, "Firefox")) ;} else {response.setheader ("content-disposition", "attachment;filename=" +encodedownloadfilename (filename, "ie");} InputStream is = new FileInputStream (absolutepath); OutputStream os = Response.getoutputstream (); int len = -1;byte buf[] = New Byte[1024];while ((Len=is.read (BUF))! =-1) {os.write (buf, 0, Len);} Is.close ();p ublic string Encodedownloadfilename (string filename, string agent) throws IOException {if (Agent.contains (" Firefox ") {filename =" =? ") UTF-8? B? " +new Base64encoder (). Encode (Filename.getbytes ("Utf-8")) + "? =";} else {filename = urlencoder.encode (filename, "UTF-8");} return filename;}
3. Verification Code Picture
Control Browser timed Refresh Response.setheader ("Refresh", "10");//define height and width int width =, height = 25;//Create an image buffer BufferedImage Bimage = New BufferedImage (width, height, bufferedimage.type_int_rgb);//Get the brush graphics g = bimage.getgraphics ();//Set the brush color to draw a border, Fill background, draw lines, draw string G.setcolor (Color.Black), g.drawrect (0, 0, width, height);//Fill Background g.setcolor (Color.light_gray); G.fillrect (1, 1, width-2, height-2);//Draw lines random r = new Random () G.setcolor (Color.cyan); for (int i=0; i<20; i++) {G.dra Wline (R.nextint (width), r.nextint (height), r.nextint (width), r.nextint (height));} A string that sets the font style for fonts font = new Font ("italics", font.bold| Font.Italic, G.setfont (font); G.setcolor (color.red); String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728"; for (int i=0; i<4; i++) {String ch = Base.charat (R.nextint ( Base.length ())) + ""; g.drawstring (CH, 20+ (20*i), 20);} Set header information to display data type Response.setheader ("Content-type", "image/jpeg");//Empty cache information Response.setheader ("Expires", "0"); Response.setheader ("Cache-control", "No-cache"); Response.setheader ("Pragma", "no-Cache "); Imageio.write (bimage," JPG ", Response.getoutputstream ()); 

4. Set the cache time
Response.setcontenttype ("Text/html;charset=utf-8"); Response.setdateheader ("Expires", System.currenttimemillis () +60*60*1000); PrintWriter out = Response.getwriter (); Out.write ("Rene-10 years");
5.1 Get request parameter Mode 1
1. Gets the GET request parameter (the value in the text box) request.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8"); enumeration<string> names = Request.getparameternames (); while (Names.hasmoreelements ()) {/*string name = new String (Names.nextelement (). GetBytes ("Iso-8859-1"), "UTF-8"); String value = new String (request.getparameter (name). GetBytes ("Iso-8859-1"), "UTF-8"); */string name = Names.nextelement (); String value = request.getparameter (name); Response.getwriter (). Write (name+ ":  " +value);

5.2 Get request parameter Mode 2
2. Obtain request parameter request.setcharacterencoding ("UTF-8") by reflection; Response.setcontenttype ("Text/html;charset=utf-8"); User user = new user (); enumeration<string> names = Request.getparameternames (); while (Names.hasmoreelements ()) {String name = Names.nextelement (); String values[] = request.getparametervalues (name); Class clazz = User.getclass (); try {Field field = Clazz.getdeclaredfield (name); Field.setaccessible (true); if (values! = Null & values.length > 1) {field.set (user, (Object) values),} else {field.set (user, values[0]);}} catch (Exception e) {throw new RuntimeException (e);}} Response.getwriter (). Write (User.getusername () + ">>" + arrays.tostring (User.getpassword ()));
5.3 Get request parameter Mode 3
3. Get request parameter request.setcharacterencoding ("UTF-8") through introspection, Response.setcontenttype ("Text/html;charset=utf-8"); User user = new user (); map<string, string[]> map = Request.getparametermap (); for (map.entry<string, string[]> Entry:map.entrySet ()) {String name = Entry.getkey (); String values[] = Entry.getvalue (); try {propertydescriptor PD = new PropertyDescriptor (name, User.class); Method m = Pd.getwritemethod (), if (Values!=null && values.length>1) {m.invoke (user, (Object) values);} else { M.invoke (user, values[0]);}} catch (Exception e) {e.printstacktrace ();}} Response.getwriter (). Write (User.getusername () + ">>" +arrays.tostring (User.getpassword ()));
5.4 Get request parameter Mode 4
4. by Beanutils SetProperty () method request.setcharacterencoding ("UTF-8"); Response.setcontenttype ("text/html;charset= UTF-8 "); User user = new user (); map<string, string[]> map = Request.getparametermap (); for (map.entry<string, string[]> Entry:map.entrySet ()) {String name = Entry.getkey (); String values[] = Entry.getvalue (); try {if (values!=null && values.length>1) {beanutils.setproperty (user, Name, (Object) values);} else {beanutils.setproperty (user, name, values[0]);}} catch (Illegalaccessexception | InvocationTargetException e) {e.printstacktrace ();}} Response.getwriter (). Write (User.getusername () + ">>" + arrays.tostring (User.getpassword ()));
5.5 Get request parameter Mode 5
5. Request.setcharacterencoding ("UTF-8") through the Populator () method in Beanutils; Response.setcontenttype ("text/html;charset= UTF-8 "); User user = new user (); try {beanutils.populate (user, Request.getparametermap ());} catch (Illegalaccessexception | InvocationTargetException e) {e.printstacktrace ();} Response.getwriter (). Write (User.getusername () + ">>" + arrays.tostring (User.getpassword ()));

Javaweb's Request/response Code cultivation chapter (v)

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.