Servlet + Ajax簡單demo

GET

AjaxServlet.java

@WebServlet("/ajax")
public class AjaxServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8" );
        PrintWriter out = response.getWriter();
        String old = request.getParameter("username" );
        if  (old ==  null  || old.length() ==  0 ) {
            out.println("用戶名不能為空" );
        } else  {
            if  (old.equals( "admin" )) {
                out.println("用戶名 ["  + old +  "] 已經(jīng)存在,請使用其他用戶名" );
            } else  {
                out.println("用戶名 ["  + old +  "] 尚未存在,可以使用該用戶名注冊" );
            }
        }
    }
}

ajax.html

<html>
<head>
    <title>ajax</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>

<body>
<input type="text" id="username"/>
<input type="button" value="11" onclick="verify();"/>
<div id="result"></div>
</body>

<script>
    function verify(){
        var jqueryObj = $("#username");
        var username = jqueryObj.val();
        $.get("/ajax?username=" + username, null, callback);
    }
    function callback(data){
        $("#result").html(data);
    }
</script>
</html>

POST

LoginServlet.java

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    public static final String DBDRIVER = "com.mysql.jdbc.Driver";
    public static final String DBURL = "jdbc:mysql://localhost:3306/login?useSSL=false";
    public static final String DBUSER = "root";
    public static final String DBPASS = "123";
    boolean flag = false;
    String username = null;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;  //數(shù)據(jù)庫連接
        PreparedStatement pstmt = null;    //數(shù)據(jù)庫預(yù)處理操作
        ResultSet rs = null;    //查詢要處理結(jié)果集

        try{
            Class.forName(DBDRIVER);
            conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);

            String sql = "select username from user where username = ? and password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, request.getParameter("username"));
            pstmt.setString(2, request.getParameter("password"));

            rs = pstmt.executeQuery();
            if(rs.next()){          //如果有數(shù)據(jù)就執(zhí)行
                flag = true;        //表示登陸成功
                username = rs.getString(1);
            }
            System.out.println(username);
        } catch (Exception e){
            e.printStackTrace();
        } finally{
            try{
                rs.close();
                pstmt.close();
                conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out=response.getWriter();
        if(flag == true) {
            out.println("success");
        } else {
            out.print("error");
        }
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>

<form action='/login' id='addForm' type='post'>
    用戶名:<input type='text' id='username' name="username" value=""><br>
    密碼:<input type='password' id='password' name="password" value=""><br>
    <input type='button' value='提交' onclick='login()'>
</form>
<label id="msg"></label>
</body>

<script type="text/javascript">
    function login(){
        var user = {
            username:"admin",
            password:"123456"
        };
        var username = $('#username').val();
        var password = $('#password').val();
        if ("" == name || "" == pwd) {
            alert('用戶名或者密碼不能為空');
        } else {
            $.ajax({
                url: 'http://localhost:8080/login?username=' + username + '&password=' + password,
                type: 'post',
                success: function (data) {
                    if('success' == data) {
                        // location.href='<%=basePath%>/index.jsp'
                        window.location.reload();
                    } else {
                        $('#msg').html(msg);
                    }
                }

            })
        }
    }

    function login2(){
        $.ajax({
            url: 'http://localhost:8080/login',        // 不能在末尾再加一個/,不然出現(xiàn)404
            data: $('#addForm').serialize(),
            type: 'post',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',    //防止亂碼
            success:function(data){
                console.log('添加成功');
                console.log(data);
            }
        })
    }
</script>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容