用ajax发异步请求时,要注意url。“AppServer”为后台项目名,“LoginServlet.action”为web.xml中的
前台代码如下(核心代码):
index.html:
1 $(function() {
2 $('#login').click(function() {
3 var account = $("#account").val();
4 var passwords = $('#passwords').val();
5 $.ajax({
6 url: "http://localhost:8080/AppServer/LoginServlet.action?ajaxType=jsonp",
7 dataType: "jsonp",
8 jsonpCallback: "jsonpCallback",
9 jsonp: "callback",
10 data: {
11 account: account,
12 passwords: passwords,
13 },
14 success: function(server) {
15 if (server.is) {
16 alert("登录成功");
17 $(location).attr('href', 'main.html?account=' + account);
18 } else {
19 alert("登录失败:" + server.err);
20 }
21 },
22 error: function(server) {
23 alert("连接服务器失败");
24 },
25 });
26 });
27 $('#register').click(function() {
28 $(location).attr('href', 'register.html');
29 });
30 })
register.html:
1 $(function() {
2 $('#register').click(function() {
3 var islen = ($('#password1').val().length >= 6 && $('#password1').val().length <= 12) && ($('#password2').val().length >= 6 && $('#password2').val().length <= 12);
4 var isID = $('#user_id').val().length > 0 && $('#user_id').val().length <= 18;
5 if (islen && isID) {
6 if ($('#password1').val() == $('#password2').val()) {
7 $.ajax({
8 type: "post",
9 url: "http://localhost:8080/AppServer/RegisterServlet.action?ajaxType=jsonp",
10 dataType: "jsonp",
11 jsonpCallback: "jsonpCallback",
12 jsonp: "callback",
13 data: {
14 account: $('#account').val(),
15 passwords: $('#password1').val(),
16 phone: $('#phone').val(),
17 email: $('#email').val(),
18 userId: $('#user_id').val(),
19 userName: $('#user_name').val(),
20 sex: $('input:radio:checked').val(),
21 },
22 success: function(server) {
23 if (server.is) {
24 alert("注册成功");
25 $(location).attr('href', 'index.html');
26 } else {
27 alert("注册失败");
28 }
29 },
30 error: function(server) {
31 alert("连接服务器失败");
32 },
33 });
34 } else {
35 alert('密码不一致!');
36 }
37 } else {
38 if (!isID) {
39 alert('请输入正确的身份证!');
40 } else if (!islen) {
41 alert('密码长度不一致');
42 } else {
43 alert('请输入合法的信息!');
44 }
45 }
46 });
47 })
main.html:
1 $(function() { 2 var loc = location.href; 3 var n1 = loc.length; //地址的总长度 4 var n2 = loc.indexOf("="); //取得=号的位置 5 var accounts = decodeURI(loc.substr(n2 + 1, n1 - n2)); 6 $('#select').click(function() { 7 $('#div2').show(1500); 8 $('#div3').hide(1500); 9 $.ajax({ 10 url: "http://localhost:8080/AppServer/MainServlet.action?ajaxType=jsonp&Type=select", 11 dataType: "jsonp", 12 jsonpCallback: "jsonpCallback", 13 jsonp: "callback", 14 data: { 15 account: accounts, 16 }, 17 success: function(server) { 18 if (server.is) { 19 $('#account').val(server.account); 20 $('#phone').val(server.phone); 21 $('#email').val(server.email); 22 $('#ids').val(server.userId); 23 $('#name').val(server.userName); 24 $('#password').val(server.passwords); 25 $('#sex').val(server.sex); 26 } else { 27 alert("查看失败!"); 28 } 29 }, 30 error: function(server) { 31 alert("连接服务器失败!"); 32 }, 33 }); 34 }); 35 $('#save').click(function() { 36 var islen = $('#password').val().length >= 6 && $('#password').val().length <= 12; 37 var isID = $('#ids').val().length > 0 && $('#ids').val().length <= 18; 38 if (islen && isID) { 39 $.ajax({ 40 async: true, 41 type: "post", 42 url: "http://localhost:8080/AppServer/MainServlet.action?ajaxType=jsonp&Type=save", 43 dataType: "jsonp", 44 jsonpCallback: "jsonpCallback", 45 jsonp: "callback", 46 data: { 47 account: $('#account').val(), 48 passwords: $('#password').val(), 49 phone: $('#phone').val(), 50 email: $('#email').val(), 51 userId: $('#ids').val(), 52 userName: $('#name').val(), 53 sex: $('#sex').val(), 54 }, 55 success: function(server) { 56 if (server.is) { 57 alert("修改成功!"); 58 $('#div2').hide(1500); 59 } else { 60 alert("修改失败!"); 61 } 62 }, 63 error: function(server) { 64 alert("连接服务器失败!"); 65 }, 66 }); 67 } else { 68 if (!isID) { 69 alert('请输入正确的身份证!'); 70 } else if (!islen) { 71 alert('密码长度不一致'); 72 } else { 73 alert('请输入合法的信息!'); 74 } 75 } 76 }); 77 $('#cancel').click(function() { 78 $.ajax({ 79 url: "http://localhost:8080/AppServer/MainServlet.action?ajaxType=jsonp&Type=cancel", 80 dataType: "jsonp", 81 jsonpCallback: "jsonpCallback", 82 jsonp: "callback", 83 data: { 84 account: accounts, 85 }, 86 success: function(server) { 87 if (server.is) { 88 alert("注销成功!"); 89 $(location).attr('href', 'index.html'); 90 } else { 91 alert("注销失败!"); 92 } 93 }, 94 error: function(server) { 95 alert("连接服务器失败!"); 96 }, 97 }); 98 }); 99 $('#all').click(function() { 100 $('#div3').show(1500); 101 $('#div2').hide(1500); 102 $.ajax({ 103 url: "http://localhost:8080/AppServer/MainServlet.action?ajaxType=jsonp&Type=all", 104 dataType: "jsonp", 105 jsonpCallback: "jsonpCallback", 106 jsonp: "callback", 107 success: function(server) { 108 if (server.is) { 109 alert("查看成功!"); 110 var arrData = []; 111 var arr = null; 112 for (i = 0; i < server.data.length; i++) { 113 if (arr == null) { 114 arr = new Array; 115 } 116 arr.push(server.data[i].userId); 117 arr.push(server.data[i].userName); 118 arr.push(server.data[i].account); 119 arr.push(server.data[i].phone); 120 arr.push(server.data[i].email); 121 arr.push(server.data[i].passwords); 122 arr.push(server.data[i].sex); 123 arrData.push(arr); 124 arr = null; 125 } 126 var td = ""; 127 var table = ""; 128 if(arrData != null){ 129 for(var i=0 ; i){ 130 var tr = ""; 131 for(var j=0 ; j "; 135 table += (tr + td + tr2); 136 td = ""; 137 } 138 $('#bodys').html(table); 139 } 140 } else { 141 alert("查看失败!"); 142 } 143 }, 144 error: function(server) { 145 alert("连接服务器失败!"); 146 }, 147 }); 148 }); 149 })){ 132 td += ' ' + arrData[i][j] + ' '; 133 } 134 var tr2 = "
web.xml:
1
2
3
4
5 LoginServlet
6 com.yuw.servlet.LoginServlet
7
8
9 RegisterServlet
10 com.yuw.servlet.RegisterServlet
11
12
13 MainServlet
14 com.yuw.servlet.MainServlet
15
16
17 LoginServlet
18 /LoginServlet.action
19
20
21 RegisterServlet
22 /RegisterServlet.action
23
24
25 MainServlet
26 /MainServlet.action
27
28
后台代码:
项目结构:
AccessData.java(与数据库交互)
1 package com.yuw.jdbc;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.io.UnsupportedEncodingException;
6 import java.sql.Connection;
7 import java.sql.PreparedStatement;
8 import java.sql.ResultSet;
9 import java.sql.SQLException;
10 import java.util.List;
11
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 import com.yuw.servlet.example.JDBCDataBase;
16 import com.yuw.transfer.DataTransfer;
17
18 /**
19 *
20 * @author Yuw
21 * @data 2017-12-20
22 */
23 public abstract class AccessData {
24 public static final int ONE = 1;
25 protected Connection connection = null;
26 protected PreparedStatement preparedStatement = null;
27 protected ResultSet resultSet = null;
28 // 接收数据
29 protected List
LoginServlet.java(登录)
1 package com.yuw.servlet;
2
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.List;
7
8 import javax.servlet.ServletException;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12
13 import com.yuw.jdbc.AccessData;
14 import com.yuw.servlet.example.SQLserverJDBC;
15 import com.yuw.transfer.DataTransfer;
16
17 /**
18 * @author Yuw
19 * @data 2017-12-20
20 *
21 */
22 public class LoginServlet extends HttpServlet implements
23 DataTransfer> {
24
25 private static final long serialVersionUID = 1L;
26 // 数据传送
27 private List
MainServlet.java(主要功能)
1 package com.yuw.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.sql.PreparedStatement; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 import java.util.Arrays; 9 import java.util.List; 10 11 import javax.servlet.ServletException; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 import org.junit.Test; 17 18 import com.yuw.jdbc.AccessData; 19 import com.yuw.servlet.example.SQLserverJDBC; 20 import com.yuw.transfer.DataTransfer; 21 import com.yuw.transfer.DataTransferReport; 22 /** 23 * @author Yuw 24 * @data 2017-12-21 25 * 26 */ 27 public class MainServlet extends HttpServlet implements DataTransfer>{ 28 29 private static final long serialVersionUID = 1L; 30 //数据传送 31 private List
119 120 if(index <= 6){ 121 for(int j=0 ; j<1 ; j++){ 122 str2 += "\"" + actionListen.flag[index] + "\"" + ":" + "\"" + listDataReceive.get(i) + "\"" +","; 123 } 124 if(index++ == 6){ 125 str1 = "{"; 126 index = 0; 127 str += (str1+str2+str3); 128 str2 = ""; 129 } 130 } 131 } 132 System.out.println(str); 133 String jsonp = request.getParameter("callback"); 134 PrintWriter out = response.getWriter(); 135 out.write(jsonp+"({\"is\":true" + "," + "\"data\"" + ":" + "[" + str + "]" + "})"); 136 137 } 138 } 139 140 } 141 142 /* 143 * 监听类 144 */ 145 private class ActionListen extends AccessData implements DataTransferReportlistDataSend = null; 32 //数据接收 33 private List listDataReceive = null; 34 35 public MainServlet(){ 36 37 } 38 39 public List getListDataReceive() { 40 return listDataReceive; 41 } 42 43 public void setListDataReceive(DataTransferReport > dataTransferReport) { 44 this.listDataReceive = dataTransferReport.transfer(); 45 } 46 47 public List
getListDataSend() { 48 return listDataSend; 49 } 50 51 public void setListDataSend(List listDataSend) { 52 this.listDataSend = listDataSend; 53 } 54 55 public void doGet(HttpServletRequest request, HttpServletResponse response) 56 throws ServletException, IOException { 57 58 doPost(request, response); 59 } 60 61 public void doPost(HttpServletRequest request, HttpServletResponse response) 62 throws ServletException, IOException { 63 response.setContentType("text/plain; charset=utf-8"); 64 ActionListen actionListen = new ActionListen(); 65 List list = new ArrayList (); 66 // 查看个人信息 67 if("select".equals(request.getParameter("Type"))){ 68 System.out.println(request.getParameter("account")); 69 list.add(actionListen.toCharacterEncoding(request.getParameter("account"))); 70 setListDataSend(list); 71 actionListen.connectionJDBC(SQLserverJDBC.getInstance(), this); 72 final String sql = "select users.*,user_Account.password from users,user_Account where users.account = user_Account.account and user_Account.account = ?;"; 73 int t = actionListen.selectData(sql); 74 setListDataReceive(actionListen); 75 actionListen.WriteMsg(ActionListen.ONE,t,request,response,listDataReceive); 76 }else if("save".equals(request.getParameter("Type"))){ // 保存 77 list.addAll(Arrays.asList(actionListen.toCharacterEncoding(request.getParameter("account")), 78 actionListen.toCharacterEncoding(request.getParameter("account")), 79 actionListen.toCharacterEncoding(request.getParameter("account")), 80 actionListen.toCharacterEncoding(request.getParameter("passwords")), 81 actionListen.toCharacterEncoding(request.getParameter("userId")), 82 actionListen.toCharacterEncoding(request.getParameter("userName")), 83 actionListen.toCharacterEncoding(request.getParameter("account")), 84 actionListen.toCharacterEncoding(request.getParameter("phone")), 85 actionListen.toCharacterEncoding(request.getParameter("email")), 86 actionListen.toCharacterEncoding(request.getParameter("sex")))); 87 setListDataSend(list); 88 actionListen.connectionJDBC(SQLserverJDBC.getInstance(), this); 89 final String sql = "begin tran saves "+ 90 "delete users where account=?;"+ 91 "delete user_Account where account=?;"+ 92 "insert into user_Account values(?,?);"+ 93 "insert into users values(?,?,?,?,?,?);"+ 94 "commit tran saves"; 95 actionListen.WriteMsg(ActionListen.ONE,actionListen.insertData(sql), request, response); 96 }else if("cancel".equals(request.getParameter("Type"))){ // 注销 97 list.addAll(Arrays.asList(actionListen.toCharacterEncoding(request.getParameter("account")), 98 actionListen.toCharacterEncoding(request.getParameter("account")))); 99 setListDataSend(list); 100 actionListen.connectionJDBC(SQLserverJDBC.getInstance(), this); 101 final String sql = "begin tran deletes "+ 102 "delete users where account=?;"+ 103 "delete user_Account where account=?;"+ 104 "commit tran deletes"; 105 actionListen.WriteMsg(ActionListen.ONE,actionListen.deleteData(sql), request, response); 106 }else if("all".equals(request.getParameter("Type"))){ // 查看所有 107 actionListen.connectionJDBC(SQLserverJDBC.getInstance(), this); 108 final String sql = "select users.*,user_Account.password from users, user_Account where users.account = user_Account.account;"; 109 int t = actionListen.selectAllData(sql); 110 setListDataReceive(actionListen); 111 if(t == 1){ 112 // 拼接JSON数据 113 int index = 0; 114 String str = ""; 115 String str1 = ""; 116 String str2 = ""; 117 String str3 = "},"; 118 for(int i=0 ; i ){ >{ 146 //发送数据 147 private List
listDataSend = null; 148 // 前台标志 149 private final String[] flag = new String[]{"userId","userName","account","phone","email","passwords","sex"}; 150 @SuppressWarnings("unused") 151 public List getListDataSend() { 152 return listDataSend; 153 } 154 155 public void setListDataSend(List listDataSend) { 156 this.listDataSend = listDataSend; 157 } 158 159 public ActionListen() { 160 161 } 162 public int selectAllData(String sql){ 163 List total = new ArrayList (); 164 List row = null; 165 try { 166 PreparedStatement preparedStatement = setPreparedStatement(sql); 167 resultSet = preparedStatement.executeQuery(); 168 while (resultSet.next()) { 169 if(row == null){ 170 row = new ArrayList (); 171 row.addAll(Arrays.asList(resultSet.getString("userId"), 172 resultSet.getString("userName"), 173 resultSet.getString("account"), 174 resultSet.getString("phone"), 175 resultSet.getString("email"), 176 resultSet.getString("password"), 177 resultSet.getString("sex"))); 178 total.addAll(row); 179 } 180 row = null; 181 } 182 setListDataSend(total); 183 //if(listDataSend != null){ 184 return 1; 185 //} 186 } catch (SQLException e) { 187 // TODO Auto-generated catch block 188 e.printStackTrace(); 189 } 190 return 0; 191 192 } 193 /* 194 * 与前台交互 195 */ 196 public void WriteMsg(int msg, int t, HttpServletRequest request, 197 HttpServletResponse response,List list) { 198 String data = ""; 199 int index = 0; 200 try { 201 if(t == msg){ 202 String jsonp = request.getParameter("callback"); 203 PrintWriter out = response.getWriter(); 204 for(Object object : list){ 205 data += "," + "\"" + flag[index++] + "\"" + ":" + "\"" + (String)object + "\""; 206 } 207 System.out.println("DATA:"+data); 208 out.write(jsonp+"({\"is\":true" + data + "})"); 209 }else{ 210 String jsonp = request.getParameter("callback"); 211 PrintWriter out = response.getWriter(); 212 out.write(jsonp+"({\"is\":false,\"err\":"+"\"账号或密码错误!\""+"})"); 213 } 214 } catch (IOException e) { 215 // TODO Auto-generated catch block 216 e.printStackTrace(); 217 } 218 } 219 /* 220 * 查询 221 * @see com.yuanwei.jdbc.AccessData#selectData(java.lang.String) 222 */ 223 @Override 224 public int selectData(String sql) { 225 PreparedStatement preparedStatement = setPreparedStatement(sql); 226 try { 227 if(super.listDataReceive != null){ 228 int index = 1; 229 for(Object object : super.listDataReceive){ 230 preparedStatement.setString(index++, (String)object); 231 System.out.println((String)object); 232 } 233 resultSet = preparedStatement.executeQuery(); 234 while(resultSet.next()){ 235 List list = new ArrayList (); 236 list.addAll(Arrays.asList(resultSet.getString("userId"), 237 resultSet.getString("userName"), 238 resultSet.getString("account"), 239 resultSet.getString("phone"), 240 resultSet.getString("email"), 241 resultSet.getString("password"), 242 resultSet.getString("sex"))); 243 setListDataSend(list); 244 } 245 return returnONE(resultSet); 246 } 247 248 } catch (SQLException e) { 249 // TODO Auto-generated catch block 250 e.printStackTrace(); 251 }finally{ 252 close(); 253 } 254 return 0; 255 256 } 257 258 public List transfer() { 259 // TODO Auto-generated method stub 260 return this.listDataSend; 261 } 262 263 } 264 265 public List transfer() { 266 // TODO Auto-generated method stub 267 return this.listDataSend; 268 } 269 270 }
RegisterServlet.java(注册)
1 package com.yuw.servlet;
2
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.List;
7
8 import javax.servlet.ServletException;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12
13 import com.yuw.jdbc.AccessData;
14 import com.yuw.servlet.example.SQLserverJDBC;
15 import com.yuw.transfer.DataTransfer;
16
17 /**
18 *
19 * @author Yuw
20 * @data 2017-12-20
21 *
22 */
23 public class RegisterServlet extends HttpServlet implements
24 DataTransfer> {
25
26 private static final long serialVersionUID = 1L;
27 // 数据传送
28 private List listDataSend = null;
29
30 public List getListDataSend() {
31 return listDataSend;
32 }
33
34 public void setListDataSend(List listDataSend) {
35 this.listDataSend = listDataSend;
36 }
37
38 public void doGet(HttpServletRequest request, HttpServletResponse response)
39 throws ServletException, IOException {
40
41 doPost(request, response);
42 }
43
44 public void doPost(HttpServletRequest request, HttpServletResponse response)
45 throws ServletException, IOException {
46 ActionListen actionListen = new ActionListen();
47 List list = new ArrayList();
48 list.addAll(Arrays.asList(actionListen.toCharacterEncoding(request.getParameter("account")),
49 actionListen.toCharacterEncoding(request.getParameter("passwords")),
50 actionListen.toCharacterEncoding(request.getParameter("userId")),
51 actionListen.toCharacterEncoding(request.getParameter("userName")),
52 actionListen.toCharacterEncoding(request.getParameter("account")),
53 actionListen.toCharacterEncoding(request.getParameter("phone")),
54 actionListen.toCharacterEncoding(request.getParameter("email")),
55 actionListen.toCharacterEncoding(request.getParameter("sex"))));
56 setListDataSend(list);
57 // 发起数据库连接
58 actionListen.connectionJDBC(SQLserverJDBC.getInstance(), this);
59 final String sql = "begin tran inserta "+
60 "insert into user_Account values(?,?);"+
61 "insert into users values(?,?,?,?,?,?);"+
62 "commit tran inserta";
63 // 与前台交互
64 actionListen.WriteMsg(ActionListen.ONE,actionListen.insertData(sql), request, response);
65 }
66
67 private class ActionListen extends AccessData {
68
69 public ActionListen() {
70
71 }
72
73 }
74
75 public List transfer() {
76 // TODO Auto-generated method stub
77 return this.listDataSend;
78 }
79
80 }
JDBCDataBase.java(连接数据库的接口)
1 package com.yuw.servlet.example;
2
3 import java.sql.Connection;
4 /**
5 *
6 * @author Yuw
7 * @data 2017-12-20
8 * 数据库连接
9 */
10 public interface JDBCDataBase{
11
12 Connection example();
13 }
SQLserverJDBC.java(具体实现类)
1 package com.yuw.servlet.example;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 /**
6 *
7 * @author Yuw
8 * @data 2017-12-20
9 */
10 public class SQLserverJDBC implements JDBCDataBase{
11 private static final String DriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
12 private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=TestDB";
13 private static final String UserName = "sa";
14 private static final String UserCipher = "123456c";
15 /*
16 * 单例模式:整个应用只实例化JDBC一个
17 */
18 private SQLserverJDBC() {
19
20 }
21 private static class LazyHolder {
22 private static final SQLserverJDBC sqlserverJDBC = new SQLserverJDBC();
23 }
24
25 public static final SQLserverJDBC getInstance() {
26 return LazyHolder.sqlserverJDBC;
27 }
28 public Connection example() {
29 Connection dataBase = null;
30 try{
31 Class.forName(DriverName);
32 dataBase = DriverManager.getConnection(URL, UserName, UserCipher);
33 } catch (Exception e ){
34 // TODO Auto-generated catch block
35 System.out.println("连接失败");
36 e.printStackTrace();
37 }
38 return dataBase;
39 }
40
41 }
DataTransfer.java(servlet向数据层发送数据的中间价)
1 package com.yuw.transfer;
2
3 public interface DataTransfer{
4 /*
5 * 数据集通讯
6 */
7 T transfer();
8 }
DataTransferReport.java(数据层向servlet发送数据的中间价)
1 package com.yuw.transfer;
2
3 /*
4 * 回送
5 */
6 public interface DataTransferReport
7 {
8
9 /*
10 * 数据集通讯
11 */
12 T transfer();
13 }