你的位置:首页 > Java教程

[Java教程]Ajax(6) Ajax向servlet请求数据库操作 并显示到当前页面 这个未经测试


假设:
1、你的页面在Web-Root下,内容为: <div id="showMsg"></div><input type="text" id="userName" />,所用编码为utf-8
2、你的servlet为: HelloWorldServlet.java 映射路径为 servlet/helloWorldServlet
步骤:
1、引入jquery-1.6.4.min.js
2、编写id为userName的输入框的点击触发函数:
$("#userName").keyup(function(){
$.ajax({
type: "post",
url: "servlet/helloWorldServlet?userName="+$(this).val(),
dataType: "json",
success: function(data){
$("#showMsg").html(data.msg);//修改id为showMsg标签的html
}, error: function(){
alert("请求出错");
}
})
})
3、后台处理接收到的内容:
request.setCharactorEncoding("utf-8");
String userName = request.getParameter("userName");
response.setCharactorEncoding("utf-8");
PringWriter out = response.getWriter();
out.print("{\"msg\":\"你好~~"+userName+"!\"}");

注意事项:
1、这里的编码统一为utf-8
2、请求路径servlet/helloWorldServlet为相对路径,因此你的页面必须在项目的Web-Root下(也就是默认的web文件夹下,名字可能因项目配置不同而改变)
3、没了,记得给分哦,打字很辛苦的~





servlet返回ajax请求数据

未来几年,程序员都应该这样写简历  

问题描述: 在前台(jsp)用ajax提交数据, 后台(servlet)处理后返回"1"或者"0". 可是前台获得的返回数据是长度为3的字符串, 即"1__"或"0__"(_表示一个空白字符).

环境:  tomcat-7.0.29 + MySQL 5.5 + jquery 1.7

其他: 以为是UTF-8 + BOM的问题, 可是把所有文件都改为UTF-8了,问题依旧.

这是后台处理请求的Validate.java文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
 
public class Validate extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
            String user_name = new String(request.getParameter("userName").getBytes("ISO-8859-1"), "UTF-8");
            String user_pwd = new String(request.getParameter("password").getBytes("ISO-8859-1"), "UTF-8");
            PrintWriter out = response.getWriter();
            String driver = "com.mysql.jdbc.Driver";
            String dbUser = "root";
            String dbPwd = "3306";
            String db = "appbase";
            String url = "jdbc:mysql://localhost:3306/" + db + "?user=" + dbUser + "&password=" + dbPwd;
            ResultSet rs = null;
            String sqlString = "select * from client where login_account='" + user_name + "' and password='" + user_pwd + "'";
            try {
                Class.forName(driver).newInstance();
                Connection conn = DriverManager.getConnection(url);
                Statement ps = conn.createStatement();
                rs = ps.executeQuery(sqlString);
                if(rs.next())
                    out.println("1");
                else
                    out.println("0");
            } catch(ClassNotFoundException e) {
                out.println("ClassNotFoundException");
            } catch(SQLException ex) {
                out.println("SQLException");
            } catch(Exception exe) {
                out.println("OtherException");
            }          
    }
}



 

这是前台ajax提交数据的代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function() {
        $("#_submit").click(function() {
            var user_name = $("#_user_name").val();
            var user_pwd = $("#_user_pwd").val();
            $.ajax({
                url: "login/validate",
                data: { userName: user_name, password: user_pwd },
                type: "GET",
                datatype: "html",
                success: function(data){
                    alert(data.length);
                }
            });
        });
    });