美文网首页
Servlet + Ajax简单demo

Servlet + Ajax简单demo

作者: 野狗子嗷嗷嗷 | 来源:发表于2017-05-21 10:40 被阅读86次

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 +  "] 已经存在,请使用其他用户名" );
            } 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;  //数据库连接
        PreparedStatement pstmt = null;    //数据库预处理操作
        ResultSet rs = null;    //查询要处理结果集

        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()){          //如果有数据就执行
                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',        // 不能在末尾再加一个/,不然出现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>

相关文章

网友评论

      本文标题:Servlet + Ajax简单demo

      本文链接:https://www.haomeiwen.com/subject/gcmmxxtx.html