接口核心流程
- java
- 1.建立Dynamic Web Project項(xiàng)目(javaweb)
- 2.創(chuàng)建-包-servlet
- [ ] 3.javaweb加入頭部開(kāi)啟跨域
response.setHeader("Access-Control-Allow-Origin", "*");
- 4.請(qǐng)求
- doget 寫(xiě)get請(qǐng)求
- [ ] 接取數(shù)據(jù)庫(kù)信息
- [ ] 轉(zhuǎn)成json形式
- 傳到前臺(tái)
- dopost 寫(xiě)post請(qǐng)求
- doget 寫(xiě)get請(qǐng)求
- web
- 調(diào)取接口
- error問(wèn)題
dataType: "json"http://傳值類(lèi)型不對(duì)就算成功接取數(shù)據(jù)也會(huì)返回error
1.eclipse 創(chuàng)建項(xiàng)目
Dynamic Web Project
- 創(chuàng)建servlet
package com.niu;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletTest
*/
@WebServlet("/ServletTest")
public class ServletTest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletTest() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
/** * 當(dāng)多線(xiàn)程并發(fā)訪(fǎng)問(wèn)這個(gè)方法里面的代碼時(shí)郊霎,會(huì)存在線(xiàn)程安全問(wèn)題嗎
* * i變量被多個(gè)線(xiàn)程并發(fā)訪(fǎng)問(wèn),但是沒(méi)有線(xiàn)程安全問(wèn)題爷绘,因?yàn)閕是doGet方法里面的局部變量书劝,
* * 當(dāng)有多個(gè)線(xiàn)程并發(fā)訪(fǎng)問(wèn)doGet方法時(shí),每一個(gè)線(xiàn)程里面都有自己的i變量土至, 各個(gè)線(xiàn)程操作的都是自己的i變量购对,所以不存在線(xiàn)程安全問(wèn)題
* * 多線(xiàn)程并發(fā)訪(fǎng)問(wèn)某一個(gè)方法的時(shí)候,如果在方法內(nèi)部定義了一些資源(變量陶因,集合等) 那么每一個(gè)線(xiàn)程都有這些東西骡苞,所以就不存在線(xiàn)程安全問(wèn)題了
* */
String text = (String) request.getParameter("text");
System.out.println("結(jié)果已經(jīng)傳入后臺(tái):" + text);
String output = "后臺(tái)返回的結(jié)果加上前臺(tái)的結(jié)果" + text;
response.getWriter().write(output);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
package com.runoob.test;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
/**
* Servlet implementation class DatabaseAccess
*/
@WebServlet("/DatabaseAccess")
public class DatabaseAccess extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDBC 驅(qū)動(dòng)名及數(shù)據(jù)庫(kù) URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/myigou?useSSL=false";
// 數(shù)據(jù)庫(kù)的用戶(hù)名與密碼,需要根據(jù)自己的設(shè)置
static final String USER = "root";
static final String PASS = "23629423";
/**
* @see HttpServlet#HttpServlet()
*/
public DatabaseAccess() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Connection conn = null;
Statement stmt = null;
// 設(shè)置響應(yīng)內(nèi)容類(lèi)型
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("text/html;charset=UTF-8");
try{
// 注冊(cè) JDBC 驅(qū)動(dòng)器
Class.forName(JDBC_DRIVER);
// 打開(kāi)一個(gè)連接
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 執(zhí)行 SQL 查詢(xún)
stmt = conn.createStatement();
String sql;
sql = "SELECT address_id, addressinfo, addressarea FROM address";
ResultSet rs = stmt.executeQuery(sql);
JSONArray jsonData = JSONArray.fromObject(convertList(rs));
System.out.println(jsonData.toString());
PrintWriter out = response.getWriter(); //把json數(shù)據(jù)傳遞到前端楷扬,記著前端用ajax接收
out.print(jsonData);
// response.getWriter().write(rs);
// 展開(kāi)結(jié)果集數(shù)據(jù)庫(kù)
/*while(rs.next()){
// 通過(guò)字段檢索
// 通過(guò)字段檢索
int id = rs.getInt("address_id");
String name = rs.getString("addressinfo");
String url = rs.getString("addressarea");
// 輸出數(shù)據(jù)
out.println("ID: " + id);
out.println(", 站點(diǎn)名稱(chēng): " + name);
out.println(", 站點(diǎn) URL: " + url);
out.println("<br />");
}*/
/*out = response.getWriter();
*/
// 完成后關(guān)閉
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
// 處理 JDBC 錯(cuò)誤
se.printStackTrace();
} catch(Exception e) {
// 處理 Class.forName 錯(cuò)誤
e.printStackTrace();
}finally{
// 最后是用于關(guān)閉資源的塊
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
// ResultSet rs 轉(zhuǎn)json
private static List convertList(ResultSet rs) throws SQLException {
List list = new ArrayList();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
while (rs.next()) {
Map rowData = new HashMap();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
return list;
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
3.編寫(xiě)xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>gitTest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>com.niu.ServletTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/ajaxtest</url-pattern>
</servlet-mapping>
</web-app>
4.項(xiàng)目?jī)?nèi)ajax調(diào)取接口
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>測(cè)試用例</title>
<script type="text/javascript">
function ajaxtest(index) {
var datapar = {
"text" : $("#input" + index).val(),
"index" : index
};
var options = {
url : "ajaxtest",
type : "post",
data : datapar,
success : function(data) {
console.log(data);
var mytext = $("textarea[id*='output" + index + "']");
mytext.val(data);
}
};
$.ajax(options);}
</script>
</head>
<body>
<h2 id="time">測(cè)試?yán)?lt;/h2>
<table border="0" align="center">
<!-- **************************測(cè)試*********************************** -->
<tr align="center">
<td width="20%">
<div>
<textarea id="input2" placeholder="前端輸入">haha</textarea>
</div>
</td>
<td width="10%">
<div>
<button onClick=ajaxtest(2)>測(cè)試后臺(tái)</button>
</div>
</td>
<td width="55%">
<div>
<textarea id="output2" placeholder="后臺(tái)輸出"></textarea>
</div>
</td>
</tr>
</table>
</body>
</html>
5.項(xiàng)目外調(diào)取接口
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="js/jquery-2.1.4.min.js"></script>
<script>
var datapar = {
"text": "haha",
"index": 2
};
$.ajax({
type: "post",
// async: false,
url: "http://192.168.0.73:8080/servletTest/ajaxtest",
data: datapar,
// dataType: "json",
success: function (data) {
console.log(data)
},
error: function (error) {
console.log(error.responseText);
}
});
</script>
</body>
</html>