J2EE项目中使用Json格式数据

在java中使用json,一共需要引入6个包:
1.json-lib-2.4-jdk15.jar(json包,必须导入)
2.commons-lang 2.5(依赖包,必须导入)
3.commons-beanutils 1.8.0(依赖包,必须导入)
4.commons-collections 3.2.1(依赖包,必须导入)
5.commons-logging 1.1.1(依赖包,必须导入)
6.ezmorph 1.0.6(依赖包,必须导入)
Demo流程:
点击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();
	}
}

最后附上源码

猜你喜欢

转载自czq5783095.iteye.com/blog/1670639