javaEE12(ajax课后题3,4(第4题省市、省市区级联任选一个)

设计一个注册表单,当用户填写注册id时,页面即时给出该id是否可用。

页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>注册页</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="icon" href="image/code.png">
    <script  src="js/ajax.js"></script>
</head>
<body>
<div class="login-main">
    <header class="layui-elip" style="width: 82%;">注册页</header>
    <!-- 表单选项 -->
    <form class="layui-form" id="form1" method="post" >
        <div class="layui-input-inline">
            <!-- 用户名 -->
            <div class="layui-inline" style="width: 85%">
                <input type="text" id="user" name="user"    placeholder="请输入用户名" autocomplete="off" class="layui-input" onclick="document.getElementById('p1').innerHTML=''" onblur="check2(this.value)">
            </div>
           <div class="layui-inline">
                <i class="layui-icon" id="ri" style="color: green;font-weight: bolder;font-size:15px" ></i>
            </div>
        </div>
            <!-- 密码 -->
        <div class="layui-input-inline">
            <div class="layui-inline" style="width: 85%">
                <input type="password" id="pwd" name="pwd"   lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
        </div>
            <!-- 确认密码 -->
        <div class="layui-input-inline">
            <div class="layui-inline" style="width: 85%">
                <input type="password" id="rpwd" name="repassword" required  lay-verify="required" placeholder="请确认密码" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-input-inline login-btn" style="width: 85%">
            <button type="button" lay-submit lay-filter="sub" class="layui-btn" onclick="check()">注册</button>
        </div>
       
         <p id="p1" style="width: 85%;text-align:center;margin-top:30px;color:red">
         <%
          request.setCharacterEncoding("UTF-8");
          String user= request.getParameter("user");
          String pwd = request.getParameter("pwd");
          if (user != null && request.getMethod().equals("POST")) {
             try {
                  Class.forName("com.mysql.jdbc.Driver");
                  String url = "jdbc:mysql:///student?useUnicode=true&characterEncoding=utf8";
                  Connection con = DriverManager.getConnection(url, "root", "12345678");
                  String sql = "insert into test values(?,?)";
                  PreparedStatement pst = con.prepareStatement(sql);
                  pst.setString(1, user);
                  pst.setString(2, pwd);
                  pst.executeUpdate();
                  pst.close();
                  con.close();
                  } catch (Exception e) {
                	  out.print(e.getMessage());
                      out.print("用户名已经存在,注册失败");
                  }
          }
          %>
         </p>
    </form>
</div>
<script >
 function trim(s){
	  return s.replace(/(^\s*)|(\s*$)/g,"")
	}
 function check(){
	 var userid=trim(document.getElementById("user").value);
	 var pwd1=document.getElementById("pwd").value;
	 var pwd2=document.getElementById("rpwd").value;
	 if(userid==''){
		 alert("用户名不能为空");
	 }
	 else if(pwd1.length<6){
		 alert("密码不足六位");
	 }
	 else if(pwd1!=pwd2){
		 alert("两次密码不一致");
	 }
	 else{
		 document.getElementById("form1").submit();
	 }
 }
 function check2(a){
	 if(a!=""){
		 sendRequest("ajax","user="+a,"POST",show)
	 }
 }
 function show(){
	 if (httpRequest.readyState == 4) { 
			if (httpRequest.status == 200) {
				 document.getElementById("ri").innerHTML=httpRequest.responseText;
			}
		}
}
</script>
</body>
</html>

 后台servle:

package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ajax")
public class ajax extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8";
	private Connection con = null;
    public void destroy() {
        super.destroy(); 
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        ResultSet rs = null;
        String user=(String)request.getParameter("user");
        try {
    		Class.forName("com.mysql.jdbc.Driver");
    		con = DriverManager.getConnection(url,"root", "12345678");
            String sql = "select * from test where user=?";
            PreparedStatement stmt = con.prepareStatement(sql);
            stmt.setString(1,user);
            rs = stmt.executeQuery();
            if(rs.next()) {
            	String ri="用户名已占用";
                out.print(ri);
            }else {
            	String ri="用户名可以使用";
                out.print(ri);
            }
    	}catch (Exception ex) {
    		ex.getMessage();
        }
	}
	public void init() throws ServletException {
        // Put your code here
    }
}

下载我国省市区数据库,实现省、市(、区)级联列表。

省市:

页面:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript">
   function refreshCity(){
      var p=document.getElementById("prov").value;
      var city=document.getElementById("city");
      if(p==""){
         city.options.length=0;
         city.options.add(new Option("--请选择市--"))
      }
      else{
        var url="ajax1";
        var params="id="+p ;
        sendRequest(url,params,'POST',showCity);
      }
   }
   function showCity(){
   var city=document.getElementById("city");
      if (httpRequest.readyState == 4) { 
         if (httpRequest.status == 200) {
            var citylist=httpRequest.responseText.split(",");
            var citynum=citylist.length;
            city.options.length=0;
            for(i=0;i<citynum;i++)
               city.options.add(new Option(citylist[i]))
            }
       }
   }
</script>
</head>
   <body>
      
       <select name="prov" id="prov" onchange="refreshCity();">
        <option value="">--请选择省--</option>
        
         <option value="2">北京市</option>
        
         <option value="3">天津市</option>
        
         <option value="4">河北省</option>
        
         <option value="5">山西省</option>
        
         <option value="6">内蒙古自治区</option>
        
         <option value="7">辽宁省</option>
        
         <option value="8">吉林省</option>
        
         <option value="9">黑龙江省</option>
        
         <option value="10">上海市</option>
        
         <option value="11">江苏省</option>
        
         <option value="12">浙江省</option>
        
         <option value="13">安徽省</option>
        
         <option value="14">福建省</option>
        
         <option value="15">江西省</option>
        
         <option value="16">山东省</option>
        
         <option value="17">河南省</option>
        
         <option value="18">湖北省</option>
        
         <option value="19">湖南省</option>
        
         <option value="20">广东省</option>
        
         <option value="21">广西壮族自治区</option>
        
         <option value="22">海南省</option>
        
         <option value="23">重庆市</option>
        
         <option value="24">四川省</option>
        
         <option value="25">贵州省</option>
        
         <option value="26">云南省</option>
        
         <option value="27">西藏自治区</option>
        
         <option value="28">陕西省</option>
        
         <option value="29">甘肃省</option>
        
         <option value="30">青海省</option>
        
         <option value="31">宁夏回族自治区</option>
        
         <option value="32">新疆维吾尔自治区</option>
        
       </select>
      <select name="city" id="city" onchange="refreshDistrict();">
         <option value="">--请选择市--</option>
      </select>  
   </body>
</html>

servlet:
 

@WebServlet("/ajax1")
public class ajax1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8";
	private Connection con = null;
    public void destroy() {
        super.destroy(); 
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        ResultSet rs = null;
        String id=request.getParameter("id");
        ArrayList<String> list = new ArrayList<String>();
        try {
    		Class.forName("com.mysql.jdbc.Driver");
    		con = DriverManager.getConnection(url,"root", "12345678");
            String sql = "select * from region where PARENT_ID=?";
            PreparedStatement stmt = con.prepareStatement(sql);
            stmt.setString(1,id);
            rs = stmt.executeQuery();
            
            while(rs.next()) {
            	list.add(rs.getString(3));
            }
           
    	}catch (Exception ex) {
    		out.print(ex.getMessage());
        }
        for(String x:list){
    		out.print(x+",");
    		}
	}
	public void init() throws ServletException {
        // Put your code here
    }
}

省市区:

页面:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript">
   function refreshCity(){
  
      var p=document.getElementById("prov").value;
      var city=document.getElementById("city");
      var district=document.getElementById("district");
     
         district.options.length=0;
         district.options.add(new Option("--请选择区--"));
      if(p==""){
         city.options.length=0;
         city.options.add(new Option("--请选择市--"));
      }else{
        var url="ajax2";
        var params="id="+p ;
        sendRequest(url,params,'POST',showCity);
      }
   }
   function showCity(){
   var city=document.getElementById("city");
   var index;
      if (httpRequest.readyState == 4) { 
         if (httpRequest.status == 200) {
            var cityJson=eval("("+httpRequest.responseText+")");
            city.options.length=0;
            city.options.add(new Option("--请选择市--"));
            for(index in cityJson)
               city.options.add(new Option(cityJson[index].regionName,cityJson[index].regionId));
            }
       }
   }
   
   function refreshDistrict(){
  
      var c=document.getElementById("city").value;
      var district=document.getElementById("district");
      if(c==""){
         district.options.length=0;
         district.options.add(new Option("--请选择区--"));
      }
      else{
        var url="ajax2";
        var params="id="+c ;
        sendRequest(url,params,'POST',showDistrict);
      }
   }
   function showDistrict(){
   var index;
   var district=document.getElementById("district");
      if (httpRequest.readyState == 4) { 
         if (httpRequest.status == 200) {
            var districtJson=eval("("+httpRequest.responseText+")");
            district.options.length=0;
            district.options.add(new Option("--请选择区--"));
            for(index in districtJson)
               district.options.add(new Option(districtJson[index].regionName,districtJson[index].regionId));
            }
       }
   }
  
  function tijiao(){
  var prov=document.getElementById('prov');
  var city=document.getElementById('city');
  var district=document.getElementById('district');
  
  if(prov.value==''){
    alert( "请选择省");
    return;
  }
   if(city.value==''){
    alert( "请选择市");
    return;
  }
  if(district.value==''){
    alert( "请选择区");
    return;
  }
  var provtext=prov.options[prov.selectedIndex].text;
   var citytext=city.options[city.selectedIndex].text;
    var districttext=district.options[district.selectedIndex].text;
  document.getElementById("pcdtext").value=provtext+citytext+districttext;
  
  var prov=document.getElementById('form1').submit();
  }
    
</script>
</head>
   <body>
      <form action="result.jsp" method="post" id="form1">
       <select name="prov" id="prov" onchange="refreshCity();">
        <option value="">--请选择省--</option>
        
         <option value="2">北京市</option>
        
         <option value="3">天津市</option>
        
         <option value="4">河北省</option>
        
         <option value="5">山西省</option>
        
         <option value="6">内蒙古自治区</option>
        
         <option value="7">辽宁省</option>
        
         <option value="8">吉林省</option>
        
         <option value="9">黑龙江省</option>
        
         <option value="10">上海市</option>
        
         <option value="11">江苏省</option>
        
         <option value="12">浙江省</option>
        
         <option value="13">安徽省</option>
        
         <option value="14">福建省</option>
        
         <option value="15">江西省</option>
        
         <option value="16">山东省</option>
        
         <option value="17">河南省</option>
        
         <option value="18">湖北省</option>
        
         <option value="19">湖南省</option>
        
         <option value="20">广东省</option>
        
         <option value="21">广西壮族自治区</option>
        
         <option value="22">海南省</option>
        
         <option value="23">重庆市</option>
        
         <option value="24">四川省</option>
        
         <option value="25">贵州省</option>
        
         <option value="26">云南省</option>
        
         <option value="27">西藏自治区</option>
        
         <option value="28">陕西省</option>
        
         <option value="29">甘肃省</option>
        
         <option value="30">青海省</option>
        
         <option value="31">宁夏回族自治区</option>
        
         <option value="32">新疆维吾尔自治区</option>
        
       </select>
      <select name="city" id="city" onchange="refreshDistrict();">
         <option value="">--请选择市--</option>
      </select>
      <select name="district" id="district">
         <option>--请选择区--</option>
      </select>
  <input type="button" value="提交选择" onclick="tijiao()"/>
  <input type="hidden" name="pcdtext" id="pcdtext"/>
  </form>
   </body>
</html>

servlet:

@WebServlet("/ajax2")
public class ajax2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8";
	private Connection con = null;
    public void destroy() {
        super.destroy(); 
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        ResultSet rs = null;
        String id=request.getParameter("id");
        JSONArray list=new JSONArray();

        try {
    		Class.forName("com.mysql.jdbc.Driver");
    		con = DriverManager.getConnection(url,"root", "12345678");
            String sql = "select * from region where PARENT_ID=?";
            PreparedStatement stmt = con.prepareStatement(sql);
            stmt.setString(1,id);
            rs = stmt.executeQuery();      
            while(rs.next()) {
            	JSONObject list2=new JSONObject();
            	String b=rs.getString(3);
        		String c=rs.getString(1);
        		list2.put("regionName",b);
            	list2.put("regionId",c);
                list.add(list2);
            }
            String a=list.toString();
            out.print(a);
    	}catch (Exception ex) {
    		out.print(ex.getMessage());
        }
	}
	public void init() throws ServletException {
        // Put your code here
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值