接口核心流程
- java
- 1.建立Dynamic Web Project项目(javaweb)
- 2.创建-包-servlet
- [ ] 3.javaweb加入头部开启跨域
response.setHeader("Access-Control-Allow-Origin", "*");
- 4.请求
- doget 写get请求
- [ ] 接取数据库信息
- [ ] 转成json形式
- 传到前台
- dopost 写post请求
- doget 写get请求
- web
- 调取接口
- error问题
dataType: "json"//传值类型不对就算成功接取数据也会返回error
1.eclipse 创建项目
Dynamic Web Project
- 创建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");
/** * 当多线程并发访问这个方法里面的代码时,会存在线程安全问题吗
* * i变量被多个线程并发访问,但是没有线程安全问题,因为i是doGet方法里面的局部变量,
* * 当有多个线程并发访问doGet方法时,每一个线程里面都有自己的i变量, 各个线程操作的都是自己的i变量,所以不存在线程安全问题
* * 多线程并发访问某一个方法的时候,如果在方法内部定义了一些资源(变量,集合等) 那么每一个线程都有这些东西,所以就不存在线程安全问题了
* */
String text = (String) request.getParameter("text");
System.out.println("结果已经传入后台:" + text);
String output = "后台返回的结果加上前台的结果" + 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 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/myigou?useSSL=false";
// 数据库的用户名与密码,需要根据自己的设置
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;
// 设置响应内容类型
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("text/html;charset=UTF-8");
try{
// 注册 JDBC 驱动器
Class.forName(JDBC_DRIVER);
// 打开一个连接
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行 SQL 查询
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数据传递到前端,记着前端用ajax接收
out.print(jsonData);
// response.getWriter().write(rs);
// 展开结果集数据库
/*while(rs.next()){
// 通过字段检索
// 通过字段检索
int id = rs.getInt("address_id");
String name = rs.getString("addressinfo");
String url = rs.getString("addressarea");
// 输出数据
out.println("ID: " + id);
out.println(", 站点名称: " + name);
out.println(", 站点 URL: " + url);
out.println("<br />");
}*/
/*out = response.getWriter();
*/
// 完成后关闭
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
// 处理 JDBC 错误
se.printStackTrace();
} catch(Exception e) {
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 最后是用于关闭资源的块
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
// ResultSet rs 转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.编写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.项目内ajax调取接口
<!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>测试用例</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">测试例子</h2>
<table border="0" align="center">
<!-- **************************测试*********************************** -->
<tr align="center">
<td width="20%">
<div>
<textarea id="input2" placeholder="前端输入">haha</textarea>
</div>
</td>
<td width="10%">
<div>
<button onClick=ajaxtest(2)>测试后台</button>
</div>
</td>
<td width="55%">
<div>
<textarea id="output2" placeholder="后台输出"></textarea>
</div>
</td>
</tr>
</table>
</body>
</html>
5.项目外调取接口
<!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>