【JavaWeb程序设计】完成大作业的时候的一些功能实现

来源:互联网 发布:淘宝账号被永久限制 编辑:程序博客网 时间:2024/06/08 17:29

1.   使用cookie实现记住用户名和密码

//读取cookie中的值,然后进行 转码 和 密码解密,避免出现中文乱码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');}}}}//将用户名密码存放在浏览器的cookie里面,不同的浏览器cookie存放的位置不一样String ec_name=java.net.URLEncoder.encode(name,"UTF-8");//用一个String存储避免转码后在文本框输出中文乱码Cookie cookie=new Cookie("UserName",ec_name);//将转码后的名字存进"UserName"这一名字中cookie.setMaxAge(600);//设置cookie存活时间是1分钟response.addCookie(cookie);//添加cookieString key = "";// 给密码加密然后存储到cookie中for(i=-1;++i<passWord.length();){key+=(char)(passWord.charAt(i)^'a');}//将密码转码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);//将转码后的密码存进"Key"这一名字中cookie.setMaxAge(600);//设置cookie存活时间是1分钟response.addCookie(cookie);//添加cookie
====================================================================================

2.   JS判断使用的是哪个浏览器
/* 判断使用的是哪个浏览器 */

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技术

/* ajax初始化XMLHTTPREQ */function createXMLHttpRequest(){//  window.alert("调用createXMLHttpRequest()");//对于Mozilla浏览器if(window.XMLHttpRequest){//直接使用XMLHttpRequest函数来创建XMLHttpRequest对象XMLHttpReq = new XMLHttpRequest();}//对于IE浏览器else if(window.ActiveXObject){try{//使用ActiveXObject函数创建浏览器XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");}catch(e){//如果出现异常,再次尝试以如下方式创建XMLHttpRequesttry{XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");}catch(e){window.alert("无法调用ajax技术");}}}}function ajax(){createXMLHttpRequest();var url = "XXX.jsp";//这里填写需要后台运行的JSP文件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 == 200){    window.alert(XMLHttpReq.responseText);//这里是返回页面的全部内容}}};XMLHttpReq.send("info="+msg+"&p=1.0");//如果对应的JSP文件有参数的话,放在这里。}
====================================================================================

4.   数据库语言可以都放在一个JSP文件里面,然后通过指定数字调用指定的数据库语言

<%@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("密码通过");String number = request.getParameter("n");if(number!=null){//out.println("进入"+number+"号通道");///////////////////////      连接数据库      /////////////////////////////////Class.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/用户名?user=用户名&password=密码");Statement stat=conn.createStatement();int i = -1;PreparedStatement ps =null;String sql = "";String name = "";String id = "";switch(number){////////// 1.插入评论 //////////***  1.  user 当前登录的用户名*  2.  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);ps.setString(1,ip);ps.setString(2,name);ps.setString(3,content);ps.setString(4,postTime);i=ps.executeUpdate();if(i>0){out.println(name+":"+content);/////// 评论与留言映射  ////sql = "Insert into CL(ListId,CommentId) Values(?,(SELECT MAX(ID) from Comment))";ps = conn.prepareStatement(sql);ps.setString(1,id);ps.executeUpdate();}}break;case "2":///////// 2. 上传头像  /////////** *  1.  user 当前登录的用户名  *  2.  it 上传图片的后缀名,图片的名字用用户名命名。     */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);ps.setString(1,Image);ps.setString(2,name);ps.executeUpdate();}break;case "3":     ///////   3. 添加朋友   //////    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 from user where UserName=?), (Select id from user where UserName=?) )";ps = conn.prepareStatement(sql);ps.setString(1,name);ps.setString(2,FriendName);ps.executeUpdate();ps = conn.prepareStatement(sql);ps.setString(1,FriendName);ps.setString(2,name);ps.executeUpdate();}    break;case "4":      /////////  4.点赞  ///////////  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.  如何使用ajax实现别人点赞,评论,添加好友,艾特的时候,不刷新即可弹出提示框。(生产中还是用websocket代替ajax长轮询)

1. application的作用是  所有访问到这个网页的人都可以访问application下的所有变量。

2. Session的作用是 每个人都有自己的一片小天地。

那么实现的方法:

    ①  用appliaction产生一个链表LInkedList<Object>  a,所有人都可以访问这个链表。

    ②  用Session给每个人都产生一个链表LinkedList<Object>  s,作用是从application中提取出自己的信息。

    ③  建立一个JSP文件 A.jsp。别人在点赞,评论,添加好友,艾特的时候,可以分别发以下信息给A.jsp。

                    点赞:A agree B   评论:A comment B   添加好友:A friend B  艾特@:A aite B

          发送信息后,存储在LInkedList<Object>  a

    ④ 对A.jsp实现ajax长轮询,代码如下:

/* ajax长轮询,查询谁评论自己或为自己点赞 */function sendEmptyRequest(){if(document.getElementById("Loginname").innerHTML !="" ){//判断用户是否已经登录//ajax技术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 == 200){var s = XMLHttpReq.responseText;if(s.length<=0){return;}//  input.innerText = input.value + s + "," +s.substr(0,1)+ ","+(s.substr(0,1)=="f") +";";//读取A.jsp页面后如果找到了自己的信息,就会输出对应的字符,然后XMLHttpReq.responseText获取该页面内容。if(s.substr(0,1) == "c"){window.alert("你被评论了。");document.getElementById("ncomment").innerHTML++;}else if(s.substr(0,1) == "l"){window.alert("你被点赞了。");document.getElementById("nlike").innerHTML++;}else if(s.substr(0,1) == "f"){window.alert("有人添加你为好友。");}else if(s.substr(0,1) == "a"){window.alert("有人艾特你。");}else if(s.substr(0,1) == "r"){window.alert("有人拒绝了您的好友请求。");}else if(s.substr(0,1) == "p"){window.alert("有人接受了您的好友请求。");}   }}};XMLHttpReq.send(null);}setTimeout("sendEmptyRequest()",2000);//表示每两秒钟调用该函数一次}
      ⑤ 在A.jsp中遍历LInkedList<Object>  a,如果A agree B 中B是自己的话就存储进LinkedList<Object>  s中,就可以读取s来获取关于自己的信息了。

A.jsp的代码如下:

<%@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");//获取当前登录的名字if(user!=null){String action = request.getParameter("Action");//点赞:A agree B   评论:A comment B   添加好友:A friend B  艾特@:A aite BString id = request.getParameter("id");//帖子id///////////////    建立或获取appliaction链表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>());}///////////////////////      获取action的时间    ////////////////////////////////    String postTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());    LinkedList<String> ll = (LinkedList<String>)application.getAttribute("action");///////////////////////     获取Session链表LinkedList<Object>  s  ////////////////////////////////  Notice用了JavaBeans,一个类,将点赞:A agree B   评论:A comment B   添加好友:A friend B  艾特@:A aite B里面的内容分开存储。LinkedList<Notice> ll_request = (LinkedList<Notice>)request.getSession().getAttribute("notice");//////////////////////      把action存入application链表中   ////////////////////////////////////    if(action!=null){    ll.add(action+" "+id);    application.setAttribute("action",ll);    }/////////////  进行application链表的遍历,提取出关于自己的信息   ///////////////////////////////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");//用于ajax返回值中判断是评论   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");//用于ajax返回值中判断是赞   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");//用于ajax返回值中判断是添加好友   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");//用于ajax返回值中判断是艾特   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");//用于ajax返回值中判断是拒绝添加朋友   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");//用于ajax返回值中判断是拒绝添加朋友   ll.remove(i);           break;        default:break;}    }    }else{ll.remove(i);}    }}%>




1 0