servlet:
1 @WebServlet("/login.do") 2 public class AjaxLoginServlet extends HttpServlet { 3 private static final long serialVersionUID = 1L; 4 5 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 6 7 ResultMsg rm = new ResultMsg(); 8 PrintWriter out = response.getWriter(); 9 Gson gson = new Gson(); 10 11 String name = request.getParameter("userName"); 12 String pass = request.getParameter("userPass"); 13 14 //非空校驗 15 if(isempty(name)||isempty(pass)){ 16 rm.setMsg("user pass is null"); 17 rm.setResult("0002"); 18 19 out.println(gson.toJson(rm)); 20 return; 21 } 22 23 //去數據庫確認一下用戶是不是存在,並且登錄成功 24 if("dabu".equals(name)&&"123".equals(pass)){ 25 rm.setResult("0000"); 26 }else { 27 rm.setMsg("user pass is wrong"); 28 rm.setResult("0001"); 29 } 30 31 out.println(gson.toJson(rm)); 32 33 //form表單 a標簽; 轉發或者重定向 34 //ajax的請求; out.println(json對象); 35 } 36 37 //判斷一個字符串是不是為空 38 private boolean isempty(String str){ 39 return null==str||"".equals(str.trim()); 40 } 41 42 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 43 // TODO Auto-generated method stub 44 doGet(request, response); 45 }
jsp里面的是重點:
1 <body> 2 3 <!-- 提交的方式; get post --> 4 5 6 <form action="login.do" method="post"> 7 8 <!-- name : 對應我們servlet去獲取前台文本框的值的 key --> 9 用戶名:<input id="nm" name="userName" type="text" value="${userName}" /> 10 密碼:<input name="userPass" type="password" /> 11 <button type="button">登錄</button> 12 <label id="lab1"></label> 13 14 </form> 15 </body> 16 <script type="text/javascript"> 17 18 $(function(){ 19 $("button").click(function(){ 20 21 //使用jQuery發送一個ajax請求 22 var name=$("#nm").val(); 23 var pass=$("input[name='userPass']").val(); 24 25 26 27 /* 28 使用get請求 29 $.get("login.love?userName="+name+"&userPass="+pass,function(obj){ //obj:后台返回給我的哪個json字符串 30 31 var json = JSON.parse(obj); 32 33 if(json.result == "0000"){ 34 location.href="http://www.baidu.com"; 35 }else if(json.result == "0001"){ 36 alert(json.msg); 37 }else{ 38 alert(json.msg); 39 } 40 }); */ 41 42 /* 43 使用post請求 44 $.post("login.love",{"userName":name,"userPass":pass},function(obj){ //obj:后台返回給我的哪個json字符串 45 46 var json = JSON.parse(obj); 47 48 if(json.result == "0000"){ 49 location.href="http://www.baidu.com"; 50 }else if(json.result == "0001"){ 51 alert(json.msg); 52 }else{ 53 alert(json.msg); 54 } 55 }) */ 56 57 58 59 $.ajax({ 60 61 62 url:"login.do",//目標地址 63 type:"post",//請求方式 64 data:{"userName":name,"userPass":pass},//請求參數 65 success:function(obj){//obj:后台返回給我們的一個json的字符串 66 67 var json=JSON.parse(obj); 68 69 if(json.result=="0000"){ 70 location.href="http//www.baidu.com"; 71 }else if (json.result=="0001") { 72 alert(json.msg); 73 }else{ 74 alert(json.msg); 75 } 76 77 } 78 79 }); 80 81 82 }); 83 }); 84 85 </script>