Java Web Service - java-json.jar包的使用以及JDBC的配置链接
Preface
- 本Sample是对上一篇java web service 的延续,主要说明创建java web service项目的简要过程
- 网上很多关于JDBC的链接sample都会在src/下创建dto(Data Transaction Objects)、model、webService、pojo(Plain Old Java Object)等几个package分属不同功能,本sample为简洁起见,将功能都放入了webService中
- 本文原创,允许转载但务必贴出本文链接
环境&工具
- Jersey JAX-RS 2.0 RI bundle 解压后将所有.jar文件放在WebContent>WEB-INF>lib下面
- json.jar 注:因为eclipse有特殊的喜好,在web servicejar 工程中,jar包的引用根据web容器而有所不同,对于tomcat,所有引用.jar必须放在web-info/lib/下
- mysql-connector-java-5.1.35.tar.gz注:需要向oracle出卖自己的email他才会让你下这个东西,之和后json.jar一样需要放在web-info/lib/下
- java version “1.8.0_40”
- tomcat 8.0
- eclipse Luna
- mysql 5.6.19
建立简单的get、post web service以及一个客户端
在mysql中创建database Library 并insert 一些数据
create database Library;
use Library
create table `Book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text NOT NULL,
`description` text NULL,
PRIMARY KEY(`id`)
);
insert into Book (title, description) values("Stardust", "Stardust is a novel by Neil Gaiman, usually published with illustrations by Charles Vess. Stardust has a different tone and style from most of Gaiman''s prose fiction, being consciously written in the tradition of pre-Tolkien English fantasy, following in the footsteps of authors such as Lord Dunsany and Hope Mirrlees. It is concerned with the adventures of a young man from the village of Wall, which borders the magical land of Faerie.");
insert into Book (title) values("testTitle2"),("testTitle3");
修改你的RestService类
内容如下:
package simpleRestWebService;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
@Path("/restService")
public class RestService {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response json_restResponse(InputStream incomingData) {
// json receiving variables
String receivedString = "";
JSONObject receivedJson = null;
// configuration of data source connection
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/Library";
String usr = "root";
String pwd = "123456";
// connection variables
PreparedStatement stmt = null;
Connection conn = null;
// temp variables
// returnCode will be send to client and be present in the console view
String returnCode = "SEARCH PROGRESS & RESULTS:";
// receive the json data as receivedJson(JSONObject)
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
receivedString += line;
}
try {
receivedJson = new JSONObject(receivedString);
returnCode += "\n\n- receive json data successfully...";
}
catch (JSONException e){
System.out.println("Error new Json - ");
}
}
catch (Exception e) {
System.out.println("Error Parsing: - ");
}
// load JDBC driver
try {
Class.forName(driver).newInstance();
returnCode += "\n\n- the driver is on...";
}
catch(Exception e) {
e.printStackTrace();
}
// connect to mysql database "Library" and search for book with "title" = "Stardust"
try {
conn = (Connection) DriverManager.getConnection(url, usr, pwd);
stmt = (PreparedStatement) conn.prepareStatement("select * from Book");
returnCode += "\n\n- 'select * from Book' is executed successfully...";
// A table of data representing a database result set, which is
// usually generated by executing a statement that queries the
// database.
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
returnCode += ("\n\ntitle:\t" + rs.getString("title"));
if (rs.getString("title").equals(receivedJson.getString("title"))) {
returnCode += "\t-that's it!";
}
else {
returnCode += ("\t-not the one I'm finding..." + rs.getString("title"));
}
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
// Close Statement and Connection
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return Response.status(200).entity(returnCode).build();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
String returnCode = "this is a test~";
return returnCode;
}
}
port 3306为mysql默认的端口,另外我将这边的流程和搜索过程以returnCode返回client
修改客户端
- 写一个小的json文件作为输入,如:
{
"title":"Stardust"
}
- 如果和之前的文件不是同一个,修改clientInputStream变量
- 我将in.readLine()的内容,即server返回的returCode收集后返回如下: