J2EE 프로젝트 에서 JSon 형식 데 이 터 를 사용 합 니 다.
1.json-lib-2.4-jdk15.jar(json 패키지,가 져 와 야 함)
2.comons-lang 2.5(패키지 의존,가 져 와 야 함)
3.comons-beanutils 1.8.0(패키지 의존,가 져 와 야 함)
4.comons-collections 3.2.1(패키지 의존,가 져 와 야 함)
5.commons-logging 1.1.1(패키지 의존,가 져 와 야 함)
6.ezmorph 1.0.6(가방 의존,가 져 와 야 함)
데모 프로 세 스:
index.jsp 페이지 의"json 테스트 버튼"을 누 르 면 jquery 호출 getJSon ajax 요청 을 통 해 JSonServlet,servlet 에서 DeptDAO 방법 으로 dept 표 의 모든 데 이 터 를 조회 하고 list 를 되 돌려 줍 니 다.list 를 json 형식 데이터 로 밀봉 하고 마지막 으로 callback 을 사용 하 며 index.jsp 페이지 의 해당 div 에 데 이 터 를 표시 합 니 다.
주요 코드 는 다음 과 같 습 니 다.
1.index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="jquery_lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
function jsonTest(){
$.getJSON("<%=request.getContextPath()%>/servlet/JsonServlet",null,callback);
function callback(data){
var resultObj = $("#result");
var showTable="<table>";
for(i=0;i<data.length;i++){
showTable+="<tr><td>"+data[i].deptno+"</td>";
showTable+="<td>"+data[i].dname+"</td>";
showTable+="<td>"+data[i].loc+"</td></tr>";
}
showTable+="</table>";
resultObj.html(showTable);
}
}
</script>
</head>
<body>
<input type="button" value="json " onclick="jsonTest()">
<div id="result"></div>
</body>
</html>
2.Dept.java(실체 클래스)
package com.czq.entitiy;
public class Dept {
private String deptno;
private String dname;
private String loc;
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
3.JsonServlet.java
package com.czq.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import com.czq.dao.DeptDAO;
import com.czq.entitiy.Dept;
public class JsonServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DeptDAO deptDAO=new DeptDAO();
ArrayList<Dept> deptList=deptDAO.findAll();
PrintWriter printWriter=response.getWriter();
JSONArray jsonArray=JSONArray.fromObject(deptList);
printWriter.print(jsonArray);
printWriter.flush();
printWriter.close();
}
}
4.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>JsonServlet</servlet-name>
<servlet-class>com.czq.servlet.JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JsonServlet</servlet-name>
<url-pattern>/servlet/JsonServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
5.DBHelp.java(데이터베이스 도구 클래스)
package com.czq.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBHelp {
private static final String url="jdbc:oracle:thin:@localhost:1521:orcl";
private static final String driver="oracle.jdbc.driver.OracleDriver";
private static final String userName="scott";
private static final String userPassWord="tiger";
public static Connection getConnection(){
try {
Class.forName(driver);
Connection connection=DriverManager.getConnection(url, userName, userPassWord);
if (null!=connection) {
return connection;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void closeResultSet(ResultSet resultSet) {
if (null!=resultSet) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closeStatement(Statement statement) {
if (null!=statement) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closeConnection(Connection connection) {
if (null!=connection) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
DBHelp.getConnection();
}
}
마지막 으로 소스 코드 를 첨부 합 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.