基於jquery+servlet實現Ajax效果

來源:互聯網
上載者:User

這裡我們將來實現一個使用Ajax非同步實現的登入效果,話不多說,直接看代碼:

登入頁面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>論壇首頁</title><link href="CSS/common.css" rel="stylesheet" type="text/css" /><link href="CSS/denglu.css" type="text/css" rel="stylesheet" /><script type="text/javascript" src="jslib/jquery.js"></script><script type="text/javascript" src="jslib/verify.js"></script></head><body><center>    <div id="body_bg">        <div id="body_all">            <div id="body_main">                <div class="dlcontent">                    <div class="dlmain">                        <div class="dlmain_username">                        <span>帳號:</span>                        <span><input type="text" name="username" id="username"/></span></div>                        <div class="dlmain_password">                        <span>密碼:</span>                        <span><input type="password" name="username" id="userpassword"/></span></div>                        <div class="dlmain_sm"><div id="result1"></div></div>                        <div class="dlmain_xuanze">                               <input type="radio" checked="checked" name="type" id="type" value="聯盟會員" />                                    聯盟會員                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;                            <input type="radio" value="論壇會員" name="type" id="type1"/>論壇會員                        </div>                        <div class="dlmain_queren">                            <input type="reset" name="reset" style="margin-right:20px" value="重設" />                            <input type="button" value="確認" onclick="verify()"/>                        </div>                    </div>                    <div class="dlright">                        <div class="dlkszc"><a href="Register.jsp">快速註冊</a></div>                    </div>                </div>            </div>            <div id="body_footer"></div>        </div>    </div></center></body></html>

實現ajax的jquery代碼:

function verify(){    //alert("來了");    //解決中文亂碼問題的方法 1,頁面端發出的資料做一次encodeURI,伺服器端使用 new String(old.getBytes("iso8859-1"),"utf-8")    //var url= "AJAXServer?name="+encodeURI($("#userName").val() ) ; // encodeURI處理中文亂碼問題   // 解決中文亂碼問題的方法 2.頁面端發出的資料做兩次encodeURI處理, 伺服器端用URLDecoder.decode(old,"utf-8");    var input=$("input[name='type']");//因為得不到單選鈕選定的value值,所以就只能先得到所有的值,通過迴圈來判斷    for(i=0;i<input.length;i++){        if(input[i].checked){            //alert(input[i].value);            var url= "Users?name="+encodeURI(encodeURI($("#username").val() ))+"&password="+encodeURI(encodeURI($("#userpassword").val() ) )+"&type="+encodeURI(encodeURI(input[i].value) ); // encodeURI處理中文亂碼問題        }    }    url=convertURL(url);//擷取函數的傳回值'login?uname='+ uname + '&psw=' + psw    $.get(url,null,function(data){            $("#result1").html(data); //簡潔版    });    //alert(url);}//給URL增加時間戳記,騙過瀏覽器,不讀取緩衝function convertURL(url){    //擷取時間戳記        var timstamp=(new Date()).valueOf();    //將時間戳記資訊拼接到URL上    if(url.indexOf("?")>=0){//用indexof判斷該URL地址是否有問號    url=url+"&t="+timstamp;    }else{       url=url+"?t="+timstamp;      }   return  url;}

後台Servlet的處理代碼:

package com.xidian.bbs.servlet;import java.io.IOException;import java.io.PrintWriter;import java.net.URLDecoder;import java.sql.Connection;import java.sql.ResultSet;import java.sql.Statement;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import com.xidian.bbs.util.DBAccess;@SuppressWarnings("serial")public class Users extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html;charset=utf-8");         request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");        PrintWriter out = response.getWriter();                //1.取js中傳遞的參數        String name1 =request.getParameter("name");        String password1 =request.getParameter("password");        String type1 =request.getParameter("type");        // String name=new String(old.getBytes("iso8859-1"),"utf-8");     //處理中文亂碼1,需和前台js檔案中的encodeURI配合        String name2= URLDecoder.decode(name1,"utf-8");                 //處理中文亂碼2        String password2= URLDecoder.decode(password1,"utf-8");        String type2= URLDecoder.decode(type1,"utf-8");                if(name2==null||name2.length()==0){            out.println("使用者名稱不可為空!!");            return;//不執行下面的代碼        } else if(password2==null||password2.length()==0){            out.println("密碼不可為空!!");            return;        }            //3.校正操作        Statement sql = null;        ResultSet rs = null;        try {            Connection con = DBAccess.getConnection();            sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,                ResultSet.CONCUR_UPDATABLE);            if(type2.equals("聯盟會員")){                HttpSession session=request.getSession();                session.setAttribute("bs_type", "聯盟會員");                rs = sql.executeQuery("select * from yh_yhxx ");                while(rs.next()){                String     yhxx_id=rs.getString("yhxx_id");                String     yhxx_pwd=rs.getString("yhxx_psw");                System.out.println(yhxx_id+"  "+yhxx_pwd);                //2.檢查參數是否有問題                //3.校正操作                if(name2.equals(yhxx_id)&&password2.equals(yhxx_pwd)){                    //4.與傳統應用不同的是,這一步將使用者感興趣的資料返回給頁面端。而不是將一個新的頁面返回給頁面端                  //寫法沒有改變,本質變化了                session.setAttribute("username", name2);                                out.println("<script language='javascript'>window.location.href='index.jsp';</script>");                  out.flush();                  out.close();              }             }}else{                HttpSession session=request.getSession();                session.setAttribute("bs_type", "論壇會員");                rs = sql.executeQuery("select * from users ");                while(rs.next()){                    if(name2.equals(rs.getString("userID"))&&password2.equals(rs.getString("uPwd"))&&rs.getInt("if_forbid")==0){                        session.setAttribute("username", name2);                        out.println("<script language='javascript'>window.location.href='index.jsp';</script>");                        out.flush();                        out.close();                    }else if(name2.equals(rs.getString("userID"))&&password2.equals(rs.getString("uPwd"))&&rs.getInt("if_forbid")==1){                        out.println("該使用者已被禁!!");                        out.flush();                        out.close();                    }                    }                    }         out.println("使用者名稱或密碼錯誤!!");        }catch(Exception e){            e.printStackTrace();        } }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doGet(request, response);    }}

 

 

相關文章

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。