Some of the functions of "Javaweb program design" When doing large jobs

Source: Internet
Author: User
Tags set cookie

1. Remembering user names and passwords using cookies

Read the value in the cookie, then transcode and password decryption, to avoid the occurrence of Chinese garbled cookie[] cookies=request.getcookies (); if (Cookies!=null && name==null && password==null) {for (int i=-1;++i<cookies.length;) {if (Cookies[i].getname (). Equals ("UserName")) {Name =java.net.urldecoder.decode (Cookies[i].getvalue (), "UTF-8");} if (Cookies[i].getname (). Equals ("Key")) {password= ""; String P=java.net.urldecoder.decode (Cookies[i].getvalue (), "UTF-8"), for (int j=-1;++j<p.length ();) {password+= ( Char) (P.charat (j) ^ ' A ');}}} The user name password is stored in the browser cookie, different browser cookie location is not the same as String Ec_name=java.net.urlencoder.encode (name, "UTF-8");// Use a string store to avoid transcoding after the text box output Chinese garbled cookie Cookie=new cookie ("UserName", ec_name);//The name of the transcoded is stored in the "UserName" In this name Cookie.setmaxage (600);//Set Cookie survival time is 1 minutes response.addcookie (cookie);//Add cookiestring key = "";// Encrypt the password and store it in a cookie for (i=-1;++i<password.length ();) {key+= (char) (Password.charat (i) ^ ' a ');} Transcode the password to string Ec_key=java.net.urlencoder.encode (key, "UTF-8");//java.lang.illegalargumentexception:control character in cookie value or attrIbute.cookie=new Cookie ("key", ec_key);//The code after transcoding is stored in the name "Key" Cookie.setmaxage (600);// Set cookie survival time is 1 minutes response.addcookie (cookie);//Add Cookie
====================================================================================

2. js to determine which browser is used
/* Determine which browser to use */

function GetExplorer () {var explorer = window.navigator.userAgent;//ie if (Explorer.indexof ("MSIE") >= 0) {browser = 1 ;} Firefox else if (Explorer.indexof ("Firefox") >= 0) {browser = 2;} Chromeelse if (Explorer.indexof ("Chrome") >= 0) {browser = 3;} Operaelse if (Explorer.indexof ("Opera") >= 0) {browser = 4;} Safarielse if (Explorer.indexof ("Safari") >= 0) {browser = 5;}}
====================================================================================

3. Ajax Technology

/* Ajax initialization Xmlhttpreq */function createxmlhttprequest () {//Window.alert (" Call Createxmlhttprequest () ");//for Mozilla Browser if (window. XMLHttpRequest) {//Use XMLHttpRequest function directly to create XMLHttpRequest object xmlhttpreq = new XMLHttpRequest ();} For IE browser else if (window. ActiveXObject) {try{//uses the ActiveXObject function to create the browser xmlhttpreq = new ActiveXObject ("Msxml2.xmlhttp");} catch (E) {//If an exception occurs, try again to create Xmlhttprequesttry{xmlhttpreq = new ActiveXObject ("Microsoft.XMLHTTP") as follows;} catch (E) {Window.alert ("Cannot invoke Ajax technology");}}} function Ajax () {createxmlhttprequest (); var url = "xxx.jsp";//fill in the JSP file that needs to run in the background xmlhttpreq.open ("POST", url,true); Xmlhttpreq.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xmlhttpreq.onreadystatechange = function () {if (xmlhttpreq.readystate = = 4) {Window.alert ("4"); if (Xmlhttpreq.status = = ) {Window.alert (xmlhttpreq.responsetext);//This is the full contents of the return page}}; Xmlhttpreq.send ("info=" +msg+ "&p=1.0");//if the corresponding JSP file has parameters, place it here. }
====================================================================================

4. The database language can be placed inside a JSP file, and then the specified database language is invoked by specifying a number

<% @page language = "java" import= "java.sql.*" import= "java.util.*" import= "java.text.*" pageencoding= "Utf-8"%> <% request.setcharacterencoding ("Utf-8"); String key = Request.getparameter ("K"), if (Key!=null && key.equals ("Databasekey")) {//out.println ("password Pass"); String number = Request.getparameter ("n"), if (number!=null) {//out.println ("enter" +number+ "channel");///////////////////// Connect database/////////////////////////////////class.forname ("Com.mysql.jdbc.Driver"); Connection conn = drivermanager.getconnection ("jdbc:mysql://localhost:3306/user name? user= username &password= password"); Statement stat=conn.createstatement (); int i =-1; PreparedStatement PS =null; String sql = ""; String name = "";  String id = ""; switch (number) {//////////1. Insert Comment//////////*** 1.  User's currently logged on Username * 2. Comment comment */case "1": Name = (String) request.getsession (). getattribute ("user"); String content = Request.getparameter ("Comment"); id = request.getparameter ("id"); if (Name!=null && content!= Null && ID!=NUll &&!name.equals ("") &&!content.equals ("") && id.matches ("^[0-9]*[1-9][0-9]*$")) {String IP =request.getheader ("x-forwarded-for"); if (IP = = null) {ip=request.getremoteaddr ();} String posttime=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (Calendar.getinstance (). GetTime ()); sql = "Insert Into Comment (ip,name,content,posttime) Values (?,?,?,?) "; PS = conn.preparestatement (sql);p s.setstring (1,IP);p s.setstring (2,name);p s.setstring (3,content);p s.setstring (4, Posttime); I=ps.executeupdate (); if (i>0) {out.println (name+ ":" +content);///////comment and message map////sql = "Insert into CL ( Listid,commentid) Values (?, (SELECT MAX (ID) from Comment)) ";p s = conn.preparestatement (sql);p s.setstring (1,id); Ps.executeupdate ();}} Break;case "2"://///////2.  Upload Avatar/////////** * 1.  User's currently logged on Username * 2.     It uploads a picture suffix, and the name of the image is named after the user name. */name = (String) request.getsession (). getattribute ("user"); String Image = Request.getparameter ("i"); if (name!=null && image!=null &&!name.equals ("") &&!  Image.equals ("")) {sql = "Update headimage set hi=? where userid= (Select ID from user where username=?) "; PS = conn.preparestatement (sql);p s.setstring (1,image);p s.setstring (2,name);p s.executeupdate ();} Break;case "3":///////3. Add friend//////name = (String) request.getsession (). getattribute ("user"); String friendname = Request.getparameter ("f"); if (name!=null && friendname!=null &&! Friendname.equals ("") &&!name.equals ("")) {sql = "Insert into Friends (Nameid,friendid) Values ((select ID FR Om user where username=?), (select ID from user where username=?)) "; PS = conn.preparestatement (sql);p s.setstring (1,name);p s.setstring (2,friendname);p s.executeupdate ();p s =    Conn.preparestatement (SQL);p s.setstring (1,friendname);p s.setstring (2,name);p s.executeupdate ();}  Break;case "4"://///////4. Likes///////////id = request.getparameter ("id"); if (Id!=null && id.matches ("^[0-9]*[1-9][0-9]*$")) {sql = "UPDATE List SET agree=agree+1 WHERE id=? ";    PS = conn.preparestatement (SQL);    Ps.setstring (1,id);  Ps.executeupdate (); } Break;default:break;} if (conn!=null) {conn.close ();}}} %>
====================================================================================

5. How to use Ajax to achieve other people like, comments, add friends, AI, do not refresh can pop up the prompt box. (in production or with WebSocket instead of Ajax long polling)

1. Application's role is that all access to this page can be accessed by all the variables under application.

2. The role of the session is that everyone has their own piece of a niche.

Then the method of implementation:

① uses appliaction to produce a linked list linkedlist<object> A, and everyone can access the list.

② the session to everyone to produce a list of linkedlist<object> s, the role is to extract their own information from the application.

③ Create a JSP file a.jsp. Others in the praise, comments, add friends, AI, you can send the following information to a.jsp.

Likes: a agree b Comment: a comment b add friend: A friend B ai @:a aite b

After the message is sent, it is stored in linkedlist<object> a

④ to a.jsp implementation Ajax long polling, the code is as follows:

/* Ajax long polling, query who commented on himself or liked */function sendemptyrequest () {if (document.getElementById ("Loginname"). InnerHTML! = "") {// Determine if the user has logged//ajax technology createxmlhttprequest (); var url = "A.jsp"; Xmlhttpreq.open ("POST", url,true); Xmlhttpreq.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xmlhttpreq.onreadystatechange = function () {if (xmlhttpreq.readystate = = 4) {if (Xmlhttpreq.status = =) {var s = Xmlhttpreq.responsetext;if (s.length<=0) {return;} Input.innertext = Input.value + S + "," +s.substr (0,1) + "," + (S.SUBSTR (0,1) = = "F") + ";"; /Read a.jsp page if you find your own information, it will output the corresponding character, and then xmlhttpreq.responsetext get the page content. if (s.substr (0,1) = = "C") {Window.alert ("you are commented. ");d Ocument.getelementbyid (" Ncomment "). innerhtml++;} else if (s.substr (0,1) = = "L") {Window.alert ("You've been praised.") ");d Ocument.getelementbyid (" Nlike "). innerhtml++;} else if (s.substr (0,1) = = "F") {Window.alert ("someone adds you as a friend.") ");} else if (s.substr (0,1) = = "a") {Window.alert ("someone's AI you.") ");} else if (s.substr (0,1) = = "R") {Window.alert ("Someone has rejected your friend request.") ");} else if (s.substr (0,1) = = "P"){Window.alert ("Someone has accepted your friend request. ");}   }}}; Xmlhttpreq.send (null);} SetTimeout ("Sendemptyrequest ()", 2000);//indicates that the function is called every two seconds}
⑤ in a.jsp linkedlist<object> A, if a agree B is their own words stored in linkedlist<object> s, you can read s to obtain information about self Your own information.

The code for A.JSP is as follows:

<% @page language = "java" import= "java.sql.*" import= "java.util.*" import= "java.text.*" import= "MSG. Notice "pageencoding=" Utf-8 "%><% request.setcharacterencoding (" Utf-8 "); Response.setcontenttype (" text/html; Charset=utf-8 "); String user = (string) request.getsession (). getattribute ("user");//Gets the name of the current login if (user!=null) {String action = Request.getparameter ("Action");//Likes: a agree b Comment: a comment b add friend: A friend B ai @:a aite bstring id = request.getparam Eter ("id");//post id///////////////Create or get appliaction linked list linkedlist<object> a/////////////////////////////if (        Application.getattribute ("action") ==null) {Application.setattribute ("action", New Linkedlist<string> ()); }if (Request.getsession (). getattribute ("notice") ==null) {request.getsession (). SetAttribute ("notice", new Linkedlist<notice> ());} Gets the time of the action////////////////////////////////String posttime=new SimpleDateFormat ("yyyy -mm-dd HH:mm:ss "). Format (Calendar.getinstancE (). GetTime ()); linkedlist<string> ll = (linkedlist<string>) application.getattribute ("Action");//////////////////////  /Get Session list linkedlist<object> s////////////////////////////////notice used JavaBeans, a class, would like: a agree B comment: a Comment B Add friend: A friend B ai @:a aite b content stored separately. Linkedlist<notice> ll_request = (linkedlist<notice>) request.getsession (). GetAttribute ("Notice");///// Put action into application linked list////////////////////////////////////if (action!=null) {Ll.add (actio    n+ "" +id);    Application.setattribute ("action", LL);    }/////////////the application linked list, extracting information about itself///////////////////////////////string s = "";    for (int i=0;i<ll.size (); i++) {s = ll.get (i);    string[] op = S.split ("");        if (Op.length >=3) {if (User.equals (op[2])) {switch (op[1]) {case ' quit ': break;        Case ' login ': break; Case "comment": Ll_request.add (New Notice (Notice.comment,op[0],op[2],integer.parseint (op[3]), posttime));   Request.getsession (). SetAttribute ("notice", ll_request);               Out.print ("C");//For the Ajax return value is judged by the comment ll.remove (i);        Break   Case "like": Ll_request.add (New Notice (Notice.like,op[0],op[2],integer.parseint (op[3]), posttime));   Request.getsession (). SetAttribute ("notice", ll_request);           Out.print ("L");//For the Ajax return value is judged to be like ll.remove (i);        Break   Case "friend": Ll_request.add (New Notice (Notice.addfriend,op[0],op[2],-1,posttime));   Request.getsession (). SetAttribute ("notice", ll_request);           Out.print ("F");//used to determine the value of the Ajax return is to add a friend Ll.remove (i);        Break   Case "Aite": Ll_request.add (New Notice (Notice.aite,op[0],op[2],-1,posttime));   Request.getsession (). SetAttribute ("notice", ll_request);           Out.print ("a");//used to determine the value of the Ajax return is Ll.remove (i);        Break   Case "Refuse": Ll_request.add (New Notice (Notice.refuse,op[0],op[2],-1,posttime));   Request.getsession (). SetAttribute ("notice", ll_request); Out.print ("R");//used to determine in the Ajax return value is to deny addingFriend Ll.remove (i);    Break   Case "Pass": Ll_request.add (New Notice (Notice.pass,op[0],op[2],-1,posttime));   Request.getsession (). SetAttribute ("notice", ll_request);           Out.print ("P");//used to judge in the Ajax return value is to refuse to add a friend Ll.remove (i);        Break    Default:break;}    }}else{ll.remove (i);} }}%>




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Some of the functions of "Javaweb program design" When doing large jobs

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.