Java-servlet Basics

Source: Internet
Author: User
Tags set set

Servlet Tips & template code

Request-related

Obtain basic parameters

// Obtain the submission address request. getrequesturi (); // obtain the submitted content request. getquerystring (); // obtain the client address (browser) request. getremoteaddr (); // obtain the client port (browser) request. getremoteport (); // obtain the submission method (get, post or .....) request. getmethod ();

 

Get submitted content body

// Obtain a submitted content parameter // http: // xxx/XX? Username = flxstring username = request. getparameter ("username"); system. out. println (username); // get some parameters for submitting content with the same name // http: // xxx/XX? Username = flx & username = lhmstring values [] = request. getparametervalues ("username"); For (INT I = 0; values! = NULL & I <values. length; I ++) {system. out. println (Values [I]);} // obtain a set of all submitted parameters (not suitable for those with parameters of the same name) Enumeration E = request. getparameternames (); While (E. hasmoreelements () {string name = (string) E. nextelement (); string value = request. getparameter (name); system. out. println (name + "=" + value);} // obtain all parameter sets. It is suitable for parameters with the same name. // http: // xxx/XX? Username = flx & Password = 123map <string, string []> map = request. getparametermap (); // map. keyset () Set set = map. entryset () for (map. entry <string, string []> entry: map. entryset () {string name = entry. getkey (); values = entry. getvalue (); For (string value: values) {system. out. println (name + "=" + value );}}

 

Garbled Problem

// The obtained content is "iso8859-1" encoded string username = request by default. getparameter ("username"); // first obtain the original byte with the current encoding, and then convert it to the target encoding username = new string (username. getbytes ("iso8859-1"), "UTF-8"); // You can also manually set the encoding request. setcharacterencoding ("UTF-8"); string username = request. getparameter ("username ");

 

Use org. Apache. commons. beanutils to quickly populate beans

// Obtain the submitted data set map = request. getparametermap (); // This Is A beanuser user that stores the submitted data = new user (); // Org. apache. commons. beanutils // beanutils Conversion Tool. Here we register a date type conversion convertutils. register (New converter () {// converter interface // after implementing this method, convertutils knows how to convert the date type to public object convert (class type, object value) {// first judge whether it is null if (value = NULL | value. equals ("") {return NULL;} // judge whether it is a string if (! (Value instanceof string) {Throw new conversionexception ("only string type conversion is supported !! ");} String S = (string) value; // format the date string to the date type simpledateformat SDF = new simpledateformat (" yyyy-mm-dd "); try {return SDF. parse (s);} catch (parseexception e) {Throw new conversionexception (S + "not a valid date value") ;}}, date. class); // starts to fill the set with mapbeanutils in the bean. populate (user, MAP );

 

Response Problems

Set browser cache

// Response body parameters, used to describe the cache settings // response. setheader ("Content-Type", "image/JPEG"); // expires:-1 // cache-control: No-Cache // Pragma: no-Cache // set the browser to not cache data response. setdateheader ("expires",-1); response. setheader ("cache-control", "No-Cache"); response. setheader ("Pragma", "No-Cache ");

 

Output text

// Set all methods of encoding format response. setcharacterencoding ("UTF-8"); response. setheader ("Content-Type", "text/html; charset = UTF-8"); response. setcontenttype ("text/html; charset = UTF-8"); response. getwriter (). write ("<meta http-equiv = 'content-type' content = 'text/html; charset = UTF-8 '>"); // OUTPUT response. getwriter (). write ("output content ");

 

Output file

// Obtain the true path string Path = This. getservletcontext (). getrealpath ("/download/ ..jpg"); // obtain the file name string filename = path from the actual path. substring (path. lastindexof ("\") + 1); // sets the response body to indicate the file type response. setheader ("content-disposition", "attachment; filename =" + urlencoder. encode (filename, "UTF-8"); // sets the input stream fileinputstream in = new fileinputstream (PATH); // template code, read from the input stream and output int Len = 0 to the output stream; byte buffer [] = new byte [1024]; outputstream out = response. getoutputstream (); While (LEN = in. read (buffer)> 0) {out. write (buffer, 0, Len);} In. close ();

 

Page Jump

// 1) Redirect method response. sendredirect ("/a. jsp"); // The page path is relative. Sendredirect can jump the page to any page, not necessarily limited to this web application, such as: Response. sendredirect ("http://www.ycul.com"); // the browser address bar changes after the jump. // If you want to pass out the value in this method, you can only include parameter in the URL or put it in the session. You cannot use request. setattribute to pass the parameter. // 2) forward mode: requestdispatcher dispatcher = request. getrequestdispatcher ("/a. jsp"); dispatcher. Forward (request, response); // The page path is the relative path. The forward method can only jump to the page in this web application. // The Address Bar of the browser does not change after the jump. // You can use this method to redirect data by using three methods: parameter, session, and request. setattribute in the URL.

 

A verification code image output Template

Import Java. AWT. color; import Java. AWT. font; import Java. AWT. graphics; import Java. AWT. graphics2d; import Java. AWT. image. bufferedimage; import Java. io. ioexception; import Java. io. outputstream; import Java. util. random; import javax. imageIO. imageIO; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresp Onse; // output the random image public class responsedemo extends httpservlet to the browser {// set the image size Private Static final int width = 130; Private Static final int Height = 30; public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {// first create an image object bufferedimage image = new bufferedimage (width, height, bufferedimage. type_int_rgb); // obtain the graphics G = image. getgraphics (); // set the background se Tbackground (g); // set the border setborder (g); // draw the interference line drawrandomline (g); // write the random number drawrandomnum (graphics2d) g ); // set the cache to avoid refreshing the image. The browser calls the parameters in the cached image // response to describe the cache settings // response. setheader ("Content-Type", "image/JPEG"); // expires:-1 // cache-control: No-Cache // Pragma: no-Cache // set the browser to not cache data response. setdateheader ("expires",-1); response. setheader ("cache-control", "No-Cache"); response. setheader ("Pragma", "No-Cache"); // you can specify the response body. The media format is the image format response. setcontenttype ("image/JPEG"); // output outputstream out = response. getoutputstream (); ImageIO. write (image, "jpg", out);} // sets the background private void setbackground (Graphics g) {// sets the color (white) g. setcolor (color. white); // fill the rectangle G. fillrect (0, 0, width, height);} // set the border private void setborder (Graphics g) {// set the color (blue) g. setcolor (color. blue); // stroke of a rectangle. The width of the side is G. drawrect (1, 1, width-2, height-2);} // draw the interference line Private void Dr Awrandomline (Graphics g) {// set the straight line color (green) g. setcolor (color. green); // loop 5 times, that is, draw five lines for (INT I = 0; I <5; I ++) {// All are random // set the actual point of the Line Segment int X1 = new random (). nextint (width); int Y1 = new random (). nextint (height); // sets the end point of a line segment, int X2 = new random (). nextint (width); int y2 = new random (). nextint (height); // draw line G. drawline (x1, Y1, X2, Y2) ;}// man verification code. The Unicode code of Chinese characters ranges from [\ u4e00-\ u9fa5] private void drawrandomnum (graphics2d g) {// set the font color (red) g. Setcolor (color. red); // set the font style G. setfont (new font ("", Font. bold, 20); // common Chinese characters, the uncommon Characters String base = "\ u7684 \ u4e00 \ Jun \ u662f \ u6211 \ Jun \ u5728 \ Jun \ u6709 \ u6765 \ u4ed6 \ u8fd9 \ Jun \ u7740 \ u4e2a \ u5730 \ u5230 \ u5927 \ u91cc \ Users \ u5c31 \ u53bb \ u5b50 \ u5f97 \ Users \ u90a3 \ u8981 \ Users \ u65f6 \ u8fc7 \ u51fa \ Users \ u4e48 \ u8d77 \ u4f60 \ u90fd \ u628a \ u597d \ u8fd8 \ u591a \ u6ca1 \ u4e3a \ u53c8 \ u53ef \ u5bb6 \ u5b66 \ U5 3ea \ u4ee5 \ u4e3b \ u4f1a \ u6837 \ Alibaba \ u60f3 \ Alibaba \ u8001 \ Alibaba \ u4ece \ u81ea \ u9762 \ Alibaba \ u5934 \ u9053 \ Alibaba \ u540e \ users \ u8d70 \ u5f88 \ u50cf \ u89c1 \ u4e24 \ u7528 \ u5979 \ u56fd \ u52a8 \ Users \ u6210 \ u56de \ Users \ u800c \ u5df1 \ users \ u73b0 \ u5c71 \ u6c11 \ u5019 \ u7ecf \ u53d1 \ u5de5 \ u5411 \ Users \ u547d \ Users \ u58f0 \ Users \ u9ad8 \ u624b \ u77e5 \ u7406 \ u773c \ u5fd7 \ u70b9 \ u5fc3 \ U6218 \ Users \ u95ee \ Users \ u65b9 \ Users \ u5403 \ u505a \ u53eb \ u5f53 \ Users \ u542c \ u9769 \ Users \ u5462 \ u771f \ u5168 \ Users \ u56db \ alibaba \ u6240 \ u654c \ u4e4b \ u6700 \ u5149 \ u4ea7 \ u60c5 \ u8def \ Alibaba \ u603b \ u6761 \ Alibaba \ u4eb2 \ u5982 \ u88ab \ u82b1 \ u53e3 \ u653e \ Users \ u6c14 \ u4e94 \ u7b2c \ Users \ u5199 \ Users \ u5427 \ u6587 \ Users \ u679c \ u600e \ u5b9a \ Users \ u660e \ u884c \ u56e0 \ u522b \ u98de \ u5916 \ u681 1 \ u00009 \ u6d3b \ u90e8 \ u95e8 \ Users \ u8239 \ u671b \ Users \ u5148 \ u529b \ Users \ u4ee3 \ u5458 \ u673a \ u66f4 \ Alibaba \ u60a8 \ Alibaba \ u98ce \ Alibaba \ u8ddf \ u7b11 \ u554a \ u5b69 \ Alibaba \ u76f4 \ Alibaba \ u591c \ Alibaba \ u9636 \ u8fde \ Alibaba \ u91cd \ alibaba \ u6597 \ Alibaba \ u54ea \ u5316 \ u592a \ u6307 \ u53d8 \ u793e \ Alibaba \ u58eb \ u8005 \ Alibaba \ u77f3 \ Alibaba \ u51b3 \ u767e \ Alibaba \ u62ff \ u7fa4 \ u7a76 \ u5404 \ u516d \ u672c \ u601d \ u89e3 \ u7 ACB \ u6cb3 \ u6751 \ u516b \ u96be \ Alibaba \ u5417 \ u6839 \ Alibaba \ u76f8 \ u7814 \ u4eca \ Alibaba \ u5750 \ u63a5 \ Alibaba \ u5173 \ users \ u89c9 \ u6b65 \ u53cd \ u5904 \ u8bb0 \ Users \ u9886 \ u6216 \ Users \ u5757 \ Users \ u8349 \ u8d8a \ u5b57 \ u52a0 \ u811a \ Users \ u7231 \ Users \ u4e60 \ u9635 \ u6015 \ u6708 \ u9752 \ Users \ u706b \ Users \ u8d76 \ u4f4d \ u5531 \ Users \ u5973 \ u4efb \ u4ef6 \ u611f \ u51c6 \ u5f20 \ u56e2 \ Alibaba \ u79bb \ u8272 \ Alibaba \ u79d1 \ u5012 \ u775b \ u5229 \ u4e16 \ u521a \ Alibaba \ u7531 \ u9001 \ Alibaba \ u5bfc \ u665a \ u8868 \ Alibaba \ u6574 \ Alibaba \ u54cd \ u96ea \ Alibaba \ u672a \ u573a \ u8be5 \ u5e76 \ u5e95 \ Alibaba \ u63d0 \ u786e \ u8fd1 \ u4department \ Alibaba \ users \ u519c \ u53e4 \ u9ed1 \ u544a \ u754c \ u62c9 \ u540d \ u5440 \ Users \ u9633 \ Users \ u53f2 \ u6539 \ Users \ u753b \ u9020 \ u5634 \ u6b64 \ u6cbb \ u5317 \ u5fc5 \ u670d \ u96e 8 \ u7a7f \ u5185 \ u8bc6 \ Alibaba \ u83dc \ Alibaba \ u7761 \ Alibaba \ u91cf \ u54b1 \ u89c2 \ u82e6 \ Alibaba \ u4f17 \ u901a \ u51b2 \ alibaba \ u7834 \ u53cb \ u5ea6 \ u672f \ u996d \ u516c \ u65c1 \ Alibaba \ u6781 \ Alibaba \ u67aa \ Alibaba \ Users \ Alibaba \ u91ce \ u575a \ u7a7a \ u6536 \ alibaba \ u81f3 \ u653f \ u57ce \ u52b3 \ u843d \ u94b1 \ Alibaba \ u56f4 \ Alibaba \ u80dc \ u6559 \ u70ed \ Alibaba \ u5305 \ Alibaba \ u5f3a \ u6570 \ u4e61 \ u547c \ u6027 \ u97f3 \ u7b54 \ u54e5 \ u9645 \ U6 5e7 \ u795e \ u5ea7 \ u7ae0 \ u5e2e \ Alibaba \ u7cfb \ Alibaba \ u725b \ u53d6 \ u5165 \ Alibaba \ u6133 \ Alibaba \ u5ffd \ u79cd \ u88c5 \ u9876 \ u6025 \ u6797 \ u505c \ u606f \ Users \ u533a \ u8863 \ u822c \ u62a5 \ u53f6 \ Users \ u6162 \ u53d4 \ u80cc \ u7ec6 "; int x = 10; for (INT I = 0; I <4; I ++) {string CH = base. charat (new random (). nextint (base. length () + ""; // before writing a word, set rotation and rotate int degree = new random () in radians (). nextint () % 30; // modulo with 30, that is, the range is-30 ~ + 30 // rotate (radians, X points, y points) g. rotate (degree * Math. PI/180, X, 20); // draw character (character, X point, y point) g. drawstring (CH, X, 20); // after painting, do not forget to restore the Rotation Angle of the canvas to G. rotate (-degree * Math. PI/180, X, 20); // The X coordinate is increased, otherwise the subsequent words will overlap x = x + 30;} public void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {doget (request, response );}}
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.