Spring MVC使用ajax检查用户名可用性

时间:2017-06-26 11:02:39

标签: java ajax spring spring-mvc

我在谷歌搜索了用户名可用性。这个问题没有任何好的解决方案。在这里,我正在尝试检查数据库表user中的用户名可用性。我有以下代码

<input type="text" name="username" id="usernamee" tabindex="1"class="form-control" placeholder="Username"><span class="status">

这是我的script代码

<script>
$(function(){
    $("#usernamee").blur(function(){
        var uname = $('#usernamee').val();
        if(uname.length >= 3){
            $(".status").html("<font> Checking availability...</font>");
             $.ajax({
                type: "GET",
                url: "/exist/"+uname,
                success: function(msg){

                    $(".status").html(msg);

                    }
                });
            }
        else{

            $(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
        }

    });
 });
</script>

这是我的控制器代码

@RequestMapping(value = { "/exist/{name}" }, method = RequestMethod.POST)
public void checkUsername(@PathVariable("name") String username, HttpServletResponse response , HttpServletRequest request) throws IOException {

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

        String connectionURL = "jdbc:mysql://localhost:81/name"; // students is my database name
        Connection connection = null;
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = (Connection) DriverManager.getConnection(connectionURL, "root", "root");
        PreparedStatement ps = (PreparedStatement) connection.prepareStatement("select username from users where username=?");
        ps.setString(1,username);
        ResultSet rs = ps.executeQuery();

        if (!rs.next()) {
            out.println("<font color=green><b>"+username+"</b> is avaliable");
        }
        else{
        out.println("<font color=red><b>"+username+"</b> is already in use</font>");
        }
        out.println();



    } catch (Exception ex) {

        out.println("Error ->" + ex.getMessage());

    } finally {
        out.close();
    }

}

运行这些代码时,status span标记仅显示checking availability.....。我的控制器尚未被调用。 以上代码是从互联网复制的。欢迎任何建议。 提前谢谢

2 个答案:

答案 0 :(得分:1)

您发送GET请求

 $.ajax({
            type: "GET"

但你的控制器期待POST

@RequestMapping(value = { "/exist/{name}" }, method = RequestMethod.POST)

将ajax更改为POST或将控制器更改为GET

答案 1 :(得分:0)

我没有从你上面的内容中得到问题,但你应该为ajax请求添加@ResponseBody。 我记得上面所说的,使用PrintWriter并且不需要@ResponseBody,但使用@ResponseBody会更好