1. 程式人生 > >登錄檔單驗證 json格式傳參

登錄檔單驗證 json格式傳參

1.加入json相關架包

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="xc"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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 type="text/css" rel="stylesheet" href="css/style.css" />
<style type="text/css">
.dis {
	display:display;
}
 .aa {
	display: none;
} 
</style>
<script type="text/javascript" src="jquery/jquery-3.3.1.js"></script>
<script type="text/javascript" >
var flag1=false;
var flag2=false;
var flag3=false;
var flag4=false;
$(document).ready(function(e) {
	 $('#username').blur(function(){
	 	 if($("#username").val()==""){
	 		$("#result").text("請輸入使用者名稱");
		 } else{
         $.ajax({
             type: "GET",   //資料提交型別
             url: "panduanUserServlet",   //提交到哪裡
             data: {username:$("#username").val()},  //傳參json採用鍵值對
             //json格式傳參
             dataType: "json",  //json格式傳參
             success:function(data){   //data 回撥函式,伺服器執行完之後, 接收伺服器響應的資料
                        var resultObj=$("#result");
                        var eValue=eval('data.'+'response'); 
                      // alert(eValue); 
                        if(eValue){
                        	//做自己想做的事情
                        	$("#result").text("此使用者名稱已經被註冊");
                        }else{
                        	flag1=true;
                        	$("#result").text("");
                        }
                      },
             error: function (d,errorThrown) {
				alert("失敗");
				alert(errorThrown);
			} 
         });
		 }
    });
	
    $(":password:eq(0)").blur(function(){
		var len= $(":password:eq(0)").val().length;
		//alert(len);
		if(len<6){
			$("#a1").text("請輸入6位以上密碼!");	
			return false;
		}else{
			$("#a1").text("");
			flag2=true;
			return true;
		}
	});
	  $(":password:eq(1)").blur(function(){
		 var pwd1= $(":password:eq(0)").val();
	    var pwd2=$(":password:eq(1)").val();
		if(pwd1==pwd2){
			$("#a2").text("");
			flag3=true;
			return true;
		}else{
			$("#a2").text("兩次密碼輸入不一致!");
			return false;
		}
	  });
	  
	  $("#email").blur(function(){
		 
	  var emails= $("#email").val();
	 //  alert(emails);
	  var mg=/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]
[email protected]
([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; if (!mg.test(emails)) { $("#a3").text("郵箱格式錯誤"); } else { $("#a3").text(""); flag4=true; } }); $("form:eq(1)").submit(function(){ // alert("bbb"); if(flag1==false||flag2==false||flag3==false||flag4==false){ alert("無法提交,請正確輸入"); return false; }else{ return true; } }); }); </script> </head> <body> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String user=""; String flag = ""; if (request.getAttribute("flag") != null) { flag = (String) request.getAttribute("flag"); } if(request.getAttribute("username")!=null){ user=(String) request.getAttribute("username"); } System.out.print(flag); %> <div id="header" class="wrap"> <div id="logo">網上書城</div> <div id="navbar"> <form method="get" name="search" action=""> 搜尋:<input class="input-text" type="text" name="keywords" /><input class="input-btn" type="submit" name="submit" value="" /> </form> </div> </div> <div id="register"> <div class="title"> <h2>歡迎註冊網上書城</h2> </div> <div class="steps"> <ul class="clearfix"> <li class="current">1.填寫註冊資訊</li> <li class="unpass">2.註冊成功</li> </ul> </div> <form method="post" action="registerServlet"> <dl > <dt>用 戶 名:</dt> <dd> <input id="username" class="input-text" type="text" name="userName"/> <span id="result"></span> </dd> <dt>密  碼:</dt> <dd><input class="input-text" type="password" name="passWord" /><span id="a1" ></span></dd> <dt>確認密碼:</dt> <dd><input class="input-text" type="password" name="rePassWord" /><span id="a2"></span></dd> <dt>Email地址:</dt> <dd><input id="email" class="input-text" type="text" name="email" /><span id="a3"></span></dd> <dt></dt> <dd class="button"> <input class="input-reg" type="submit" name="register" value="" /> </dd> </dl> </form> </div> <div id="footer" class="wrap">網上書城 &copy; 版權所有</div> </body> </html>

servlet 

package com.db.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.db.service.UserService;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class panduanUserServlet
 */
@WebServlet("/panduanUserServlet")
public class panduanUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public panduanUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("utf-8");
		 response.setContentType("text/json; charset=utf-8");//設定響應的資料格式
		UserService service = new UserService();
		String username=request.getParameter("username");
		request.setAttribute("username", username);
		 JSONObject jsonobj = new JSONObject(); 
		PrintWriter out=response.getWriter();
		Boolean flag=false;
		System.out.println("user:"+username);
		flag= service.username(username);
			 jsonobj.put("response", flag);
		      out.println(jsonobj);
	out.flush();
	out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}