servlet+ajax实现json数据交互需要插件 Jquery、jar包:json-lib-2.2.3-jdk15.jar及其他jar包如下:
完成结果:【这种写法只能⽤数据库中id=1的第⼀条数据登录,是什么原因呢?还在实验中】
具体代码:
1、前台js+html代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录</title>
<!--引⼊js-->
<script src="./jquery-3.3.1.js"></script>
<script type="text/javascript">
function login(){
var uname = $("#uname").val();
var pwd = $("#pwd").val();
alert(uname);
$.ajax({
type : "post",
async : false, //异步请求(同步请求将会锁住浏览器,⽤户其他操作必须等待请求完成才可以执⾏)
url : "UserServlet", //请求发送到UserServlet处
data : {"uname":uname,"pwd":pwd},
dataType : "json", //返回数据形式为json
success : function(result) {
//请求成功时执⾏该函数内容,result即为服务器返回的json对象
for(var i=0;i<result.length;i++){
alert(result[i].id+result[i].uname+result[i].nickname+result[i].pwd);
//后期将获得的数据加⼊html
addLabel(result[i].id,result[i].uname,result[i].nickname,result[i].pwd)
}
//隐藏加载动画略
},
error : function(errorMsg) {
//请求失败时执⾏该函数
alert("请求数据失败!");
myChart.hideLoading();
}
});
}
//实现添加元素的函数
function addLabel(id,uname,nickname,pwd){
$("thead").append("<tr>")
$("thead").append("<td>"+id+"</td>");
$("thead").append("<td>"+uname+"</td>");
$("thead").append("<td>"+nickname+"</td>");
$("thead").append("<td>"+pwd+"</td></tr>");
}
</script>
<style type="text/css">
*{
margin:0 auto;
padding:0;
}
#container{
width:600px;
height:500px;
border:1px solid red;
border-radius:10%;
}
/**将⾏内元素设置为块元素,并分⾏控制**/
#cover_uname{
margin-top:200px;
width:300px;
height:50px;
display:block;
}
#cover_pwd{
width:300px;
height:50px;
display:block;
}
#cover_login{
width:60px;
height:50px;
display:block;
}
</style>
</head>
<body>
<div id="container">
<span id="cover_uname">账户:<input type="text" id="uname"/></span>
<span id="cover_pwd">密码:<input type="text" id="pwd"/></span>
<span id="cover_login"><button onclick="login()">登录</button></span>
</div>
<div id="content">
<table border="1" >
<thead><tr><td colspan="4" align="center">信息</td></tr></thead>
</table>
</div>
</body>
</html>
2、servlet代码:
package gc.servlet;
import gc.dao.UserDao;
import gc.json.ToJson;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author macbook
* @see⽤户登录控制/增删改查控制
*/
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UserServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json; charset=utf-8");
response.setHeader("cache-control", "no-cache");
PrintWriter out = Writer();
ToJson json = new ToJson();
UserDao dao = new UserDao();
//根据状态,进⾏判断
String uname = Parameter("uname");
String pwd = Parameter("pwd");
System.out.println(uname+pwd);
//login登录
String loginStatus = dao.login(uname, uname);
if(loginStatus.equals("fail")){
//调转到登录失败页⾯
response.sendError(404);
}else {
//说明获取到昵称,返回昵称和⽤户信息
out.AUserJson(uname));
System.out.AUserJson(uname));
}
//reg注册
//del删除
//update修改
//select查询
out.flush();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response);
}
}
3、其他队数据库操作的类和转化为json数据的类:
数据库信息的类:
package gc.util;
public class MySqlDBInfor {
public static String driverName = "sql.jdbc.Driver";
public static String url = "jdbc:mysql://127.0.0.1:3306/gc?useUnicode=true&characterEncoding=UTF-8";
public static String user = "root";
public static String pwd = "123456";
}
连接数据库的类:
package gc.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectDB {
static Connection connection = null;//1.
//数据库连接
public static Connection getConnectDB(){
try {
Class.forName(MySqlDBInfor.driverName);//2.
connection = Connection(MySqlDBInfor.url,MySqlDBInfor.user,MySqlDBInfor.pwd);//3.
jquery实现ajaxreturn connection;
} catch (Exception e) {
System.out.Message());
}
return connection;
}
//数据库连接关闭
public static void closeDB(){
try {
getConnectDB().close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see⽤于向数据库插⼊数据
* @param sql
* @return
*/
public static int updateData(String sql){
try {
Statement statement = getConnectDB().createStatement();
int a = uteUpdate(sql);
if(a>0)return 1;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
/**
* @see查询数据
* @param sql
* @return
*/
public static ResultSet queryData(String sql){
Statement statement;
try {
statement = getConnectDB().createStatement();
ResultSet set = uteQuery(sql);
return set;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();//出现异常就直接返回null
return null;
}
}
public static boolean insertData(String sql){
try {
Statement statement = getConnectDB().createStatement();
uteUpdate(sql)>0)return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws SQLException {
String sql = "select *from user;";
ResultSet set = ConnectDB.queryData(sql);
while (()) {
System.out.String("uname"));
}
}
}
操作类:
package gc.dao;
import gc.table.User;
import gc.util.ConnectDB;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
Connection connection = ConnectDB();
User user;
//查询账户
public List<User> selectUser(String sql){
PreparedStatement statement;
List<User> list = new ArrayList<User>();
ResultSet set;
try {
statement = connection.prepareStatement(sql);
set = uteQuery();
while (()) {
user = new User();
user.String("id"));
user.String("uname"));
user.String("pwd"));
user.String("nickname"));
list.add(user);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
//插⼊账户
//删除账户
//修改账户
//以上是基本操作,下⾯是servlet调⽤时的⼀些特例操作
/
/登录,密码账号争取,账号正确,密码不正确【由于不设置验证码,故必须⼆者均要正确才⾏,避免撞库】public String login(String uname,String pwd){
String sql = "select *from user;";
List<User> users = selectUser(sql);
for (int i = 0; i < users.size();) {
User user = (i);
if (Uname().equals(uname)&&Pwd().equals(pwd)) {
Nickname();
}else {
return "fail";
}
}
return "fail";
}
//测试
public static void main(String[] args) {
UserDao dao = new UserDao();
String sql = "select *from user;";
List<User> list = dao.selectUser(sql);
for (int i = 0; i < list.size(); i++) {
User user = (i);
System.out.Uname());
}
/
/测试json化的数据,已在ToJson类内进⾏测试使⽤时调⽤即可
}
}
将数据转化为json的类:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import gc.dao.UserDao;
import gc.table.User;
import gc.util.ConnectDB;
//将所有表的查询到的结果转化为json数据的类
public class ToJson {
//⾸先对表中某些字段的值进⾏统计,然后再交给本类
public void json(String countType,int countNum){
}
public void json(){
}
/
**
* 本类⽤于将json数据直接交给html的测试
*/
public List<FakeForms> getJsonTest(){
//1、获取数据库数据,并进⾏统计
//2、对数据进⾏json转化
//3、实现基带板类型统计,然后将之数据化
//4、x表⽰板卡类型,y表⽰统计
String sql = "select count(if(basebandBoard='BPN2',basebandBoard,null)) BPN2,count(if(basebandBoard='CCE1',basebandBoard,null)) CCE1,count(if(basebandBoard='BPP1',basebandBoard,null)) BPP1,count(if(basebandBoard='FA4',baseba Connection connection = ConnectDB();
List<FakeForms> fours = new ArrayList<>();
try {
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet set = uteQuery();
while (()) {
FakeForms fakeForms = new FakeForms();
fakeForms.String("BPN2"));
fakeForms.String("BPP1"));
fakeForms.String("CCE1"));
fakeForms.String("FA4"));
fakeForms.String("FA4A"));
fakeForms.String("FA6"));
fakeForms.String("PM10"));
fakeForms.setPM10B("PM10B");
fakeForms.String("SA0"));
fours.add(fakeForms);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return fours;
}
//获取⽤户json数据
public JSONArray getUserJson(){
UserDao dao2 = new UserDao();
String sql = "select *from user;";
List<User> list = dao2.selectUser(sql);
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < list.size(); i++) {
User user = (i);
//数据json化
JSONObject jsonObject = JSONObject.fromObject(user);
jsonArray.add(jsonObject);
}
//测试
//System.out.println(jsonArray);
return jsonArray;
}
//获取单个⽤户json数据
public JSONArray getAUserJson(String uname){
UserDao dao2 = new UserDao();
String sql = "select *from user where uname='"+uname+"';";
List<User> list = dao2.selectUser(sql);
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < list.size(); i++) {
User user = (i);
//数据json化
JSONObject jsonObject = JSONObject.fromObject(user);
jsonArray.add(jsonObject);
}
//测试
//System.out.println(jsonArray);
return jsonArray;
}
//测试
public static void main(String[] args) {
ToJson dao = new ToJson();
JSONArray array = new JSONArray();
List<FakeForms> fours = JsonTest();
for (int i = 0; i < fours.size(); i++) {
FakeForms four = (i);
//json化
JSONObject jsonObject = JSONObject.fromObject(four);
array.add(jsonObject);
System.out.BPN2());
System.out.String());
}
//下⾯是将查询出的结果进⾏json格式化
//下⾯是对User的数据json化
System.out.UserJson());
System.out.AUserJson("cisco"));
}
}
映射表:
package gc.table;
/
** 登录系统的账户表 **/
public class User {
private String uname;
private String pwd;
private String nickname;//昵称
/**
* @return the id
*/
public String getId() {
return id;
}
/
**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the uname
*/
public String getUname() {
return uname;
}
/**
* @param uname the uname to set
*/
public void setUname(String uname) {
this.uname = uname;
}
/**
* @return the pwd
*/
public String getPwd() {
return pwd;
}
/**
* @param pwd the pwd to set
*/
public void setPwd(String pwd) {
this.pwd = pwd;
}
/**
* @return the nickname
*/
public String getNickname() {
return nickname;
}
/**
* @param nickname the nickname to set
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
本篇⽂章主要⽤于记录json数据转化,注释中提到的功能多没实现,这⾥主要是记录JSON数据转化及前后交互,实现的过程。
基本思路:
前台发送json数据给servlet,同时请求servlet给予json数据。不考虑后台处理流程,就是这样的交互,双向交互的过程。那么具体细节呢?
⾸先html发送json数据请求,并请求json数据,此时servlet接收数据后,交由dao类/ToJson类进⾏处理,根据需要选择。⽽ToJson则会调⽤Dao类,实现代码重⽤,同时快速转化数据为json。即普通的数据请求,如增删改,使⽤dao即可,牵涉到json则交由Tojson处理。当数据到了dao这⾥,dao⼜去调⽤数据库连接对象进⾏操作。
按数据流向,我给他按【个⼈理解的数据分层】:
html/js ajax请求层
servlet 数据接收层/发送
dao/ToJson/table映射类数据处理/转化层
ConnectionDB 数据持久层
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论