用ajax发异步请求时,要注意url。“AppServer”为后台项目名,“LoginServlet.action”为web.xml中的<url-pattern></url-pattern>标签中的内容。
前台代码如下(核心代码):
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<arrData.length ; i++){
130 var tr = "<tr>";
131 for(var j=0 ; j<arrData[i].length; j++){
132 td += ‘<td>‘ + arrData[i][j] + ‘</td>‘;
133 }
134 var tr2 = "</tr>";
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 })
web.xml:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
3 <display-name></display-name>
4 <servlet>
5 <servlet-name>LoginServlet</servlet-name>
6 <servlet-class>com.yuw.servlet.LoginServlet</servlet-class>
7 </servlet>
8 <servlet>
9 <servlet-name>RegisterServlet</servlet-name>
10 <servlet-class>com.yuw.servlet.RegisterServlet</servlet-class>
11 </servlet>
12 <servlet>
13 <servlet-name>MainServlet</servlet-name>
14 <servlet-class>com.yuw.servlet.MainServlet</servlet-class>
15 </servlet>
16 <servlet-mapping>
17 <servlet-name>LoginServlet</servlet-name>
18 <url-pattern>/LoginServlet.action</url-pattern>
19 </servlet-mapping>
20 <servlet-mapping>
21 <servlet-name>RegisterServlet</servlet-name>
22 <url-pattern>/RegisterServlet.action</url-pattern>
23 </servlet-mapping>
24 <servlet-mapping>
25 <servlet-name>MainServlet</servlet-name>
26 <url-pattern>/MainServlet.action</url-pattern>
27 </servlet-mapping>
28 </web-app>
后台代码:
项目结构:
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<Object> listDataReceive = null;
30 public AccessData() {
31
32 }
33 /*
34 * @dataBase 数据库连接
35 * @dataTransfer 获得每次连接的数据信息
36 */
37 public void connectionJDBC(JDBCDataBase dataBase,DataTransfer<List<Object>> dataTransfer) {
38 if(this.connection == null){
39 this.connection = dataBase.example();
40 this.listDataReceive = dataTransfer.transfer();
41 }
42 }
43 /*
44 * 删除
45 */
46 public int deleteData(String sql){
47 int msg = 0;
48 try {
49 if(listDataReceive != null){
50 preparedStatement = connection.prepareStatement(sql);
51 int index = 1;
52 for(Object object : listDataReceive){
53 preparedStatement.setString(index++, (String)object);
54 }
55 msg = preparedStatement.executeUpdate();
56 }
57 } catch (SQLException e) {
58 // TODO Auto-generated catch block
59 e.printStackTrace();
60 }finally{
61 close();
62 }
63 return msg;
64 }
65 /*
66 * 插入
67 */
68 public int insertData(String sql){
69 int msg = 0;
70 try {
71 if(listDataReceive != null){
72 preparedStatement = connection.prepareStatement(sql);
73 int index = 1;
74 for(Object object : listDataReceive){
75 preparedStatement.setString(index++, (String)object);
76 }
77 msg = preparedStatement.executeUpdate();
78 }
79 } catch (SQLException e) {
80 // TODO Auto-generated catch block
81 e.printStackTrace();
82 }finally{
83 close();
84 }
85 return msg;
86
87 }
88 /*
89 * 查询
90 */
91 public int selectData(String sql){
92 PreparedStatement preparedStatement = setPreparedStatement(sql);
93 try {
94 if(listDataReceive != null){
95 int index = 1;
96 for(Object object : listDataReceive){
97 preparedStatement.setString(index++, (String)object);
98 System.out.println((String)object);
99 }
100 resultSet = preparedStatement.executeQuery();
101 return returnONE(resultSet);
102 }
103
104 } catch (SQLException e) {
105 // TODO Auto-generated catch block
106 e.printStackTrace();
107 }finally{
108 close();
109 }
110 return 0;
111
112 }
113 /*
114 * 判断结果集是否只有一行
115 */
116 public int returnONE(ResultSet resultSet){
117 try {
118 resultSet.last();
119 if(resultSet.getRow() == ONE){
120 return ONE;
121 }
122 } catch (SQLException e) {
123 // TODO Auto-generated catch block
124 e.printStackTrace();
125 }
126 return 0;
127
128 }
129
130 public PreparedStatement setPreparedStatement(String sql){
131 try {
132 if(this.preparedStatement == null){
133 this.preparedStatement = connection.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
134 }
135 } catch (SQLException e) {
136 // TODO Auto-generated catch block
137 e.printStackTrace();
138 }
139 return preparedStatement;
140
141 }
142 /*
143 * 处理乱码
144 */
145 public String toCharacterEncoding(String str) throws UnsupportedEncodingException{
146 if(str == null){
147 System.out.println("请传参");
148 }
149 return new String(str.getBytes("iso-8859-1"),"utf-8");
150
151 }
152 /*
153 * 关闭连接
154 */
155 public void close(){
156 if(preparedStatement != null){
157 try {
158 preparedStatement.close();
159 } catch (SQLException e) {
160 // TODO Auto-generated catch block
161 e.printStackTrace();
162 }
163 }
164 if(connection != null){
165 try {
166 connection.close();
167 } catch (SQLException e) {
168 // TODO Auto-generated catch block
169 e.printStackTrace();
170 }
171 }
172 }
173 /*
174 * 与前台交互
175 */
176 public void WriteMsg(int msg,int t,HttpServletRequest request,HttpServletResponse response){
177 try {
178 if(t == msg){
179 String jsonp = request.getParameter("callback");
180 PrintWriter out = response.getWriter();
181 out.write(jsonp+"({\"is\":true})");
182 }else{
183 String jsonp = request.getParameter("callback");
184 PrintWriter out = response.getWriter();
185 out.write(jsonp+"({\"is\":false,\"err\":"+"\"账号或密码错误!\""+"})");
186 }
187 } catch (IOException e) {
188 // TODO Auto-generated catch block
189 e.printStackTrace();
190 }
191 }
192
193 }
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<List<Object>> {
24
25 private static final long serialVersionUID = 1L;
26 // 数据传送
27 private List<Object> listDataSend = null;
28
29 public List<Object> getListDataSend() {
30 return listDataSend;
31 }
32
33 public void setListDataSend(List<Object> listDataSend) {
34 this.listDataSend = listDataSend;
35 }
36
37 public void doGet(HttpServletRequest request, HttpServletResponse response)
38 throws ServletException, IOException {
39
40 doPost(request, response);
41 }
42
43 public void doPost(HttpServletRequest request, HttpServletResponse response)
44 throws ServletException, IOException {
45 response.setContentType("text/plain; charset=utf-8");
46
47 ActionListen actionListen = new ActionListen();
48 List<Object> list = new ArrayList<Object>();
49 list.addAll(Arrays.asList(
50 actionListen.toCharacterEncoding(request.getParameter("account")),
51 actionListen.toCharacterEncoding(request.getParameter("passwords"))));
52 setListDataSend(list);
53 // 发起数据库连接
54 actionListen.connectionJDBC(SQLserverJDBC.getInstance(), this);
55 final String sql = "select * from user_Account where account = ? and password = ?";
56 // 与前台交互
57 actionListen.WriteMsg(ActionListen.ONE,actionListen.selectData(sql), request, response);
58
59 }
60 /*
61 * 监听类
62 */
63 private class ActionListen extends AccessData {
64
65 public ActionListen() {
66
67 }
68
69 }
70
71 public List<Object> transfer() {
72 // TODO Auto-generated method stub
73 return this.listDataSend;
74 }
75
76 }
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<List<Object>>{
28
29 private static final long serialVersionUID = 1L;
30 //数据传送
31 private List<Object> listDataSend = null;
32 //数据接收
33 private List<Object> listDataReceive = null;
34
35 public MainServlet(){
36
37 }
38
39 public List<Object> getListDataReceive() {
40 return listDataReceive;
41 }
42
43 public void setListDataReceive(DataTransferReport<List<Object>> dataTransferReport) {
44 this.listDataReceive = dataTransferReport.transfer();
45 }
46
47 public List<Object> getListDataSend() {
48 return listDataSend;
49 }
50
51 public void setListDataSend(List<Object> 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<Object> list = new ArrayList<Object>();
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<listDataReceive.size() ; i++){
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 DataTransferReport<List<Object>>{
146 //发送数据
147 private List<Object> listDataSend = null;
148 // 前台标志
149 private final String[] flag = new String[]{"userId","userName","account","phone","email","passwords","sex"};
150 @SuppressWarnings("unused")
151 public List<Object> getListDataSend() {
152 return listDataSend;
153 }
154
155 public void setListDataSend(List<Object> listDataSend) {
156 this.listDataSend = listDataSend;
157 }
158
159 public ActionListen() {
160
161 }
162 public int selectAllData(String sql){
163 List<Object> total = new ArrayList<Object>();
164 List<Object> 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<Object>();
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<Object> 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<Object> list = new ArrayList<Object>();
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<Object> transfer() {
259 // TODO Auto-generated method stub
260 return this.listDataSend;
261 }
262
263 }
264
265 public List<Object> 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<List<Object>> {
25
26 private static final long serialVersionUID = 1L;
27 // 数据传送
28 private List<Object> listDataSend = null;
29
30 public List<Object> getListDataSend() {
31 return listDataSend;
32 }
33
34 public void setListDataSend(List<Object> 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<Object> list = new ArrayList<Object>();
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<Object> 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<T>{
4 /*
5 * 数据集通讯
6 */
7 T transfer();
8 }
DataTransferReport.java(数据层向servlet发送数据的中间价)
1 package com.yuw.transfer;
2
3 /*
4 * 回送
5 */
6 public interface DataTransferReport<T>
7 {
8
9 /*
10 * 数据集通讯
11 */
12 T transfer();
13 }