请问如何写一个java 服务器端的servlet,然后可以当客户端发出http请求的时候,可以接受请求,读取数据库

并以json格式返回数据到客户端

首先你得知道servlet的工作原理,可以百度一下,如何写呢?首先需要新建一个web项目,然后新建一个servlet,注意一下mapping url就是访问的url也就是http://127.0.0.1:8080/项目名/你的mapping url:例如我写的例子:http://127.0.0.1:8080/webtest/
具体用到的jar包:
json-lib-2.3-jdk15.jar
commons-beanutils-1.7.0.jar
commons-httpclient-3.1.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
commons-collections-3.1.jar
ezmorph-1.0.3.jar

用到了jquery,可以看看
页面index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function(){
$("#button").bind("click",function(){
$.post("jsonServlet",null,function(e){
alert(e.name);
},"json")
});
});
</script>
</head>

<body>

<input type="button" id="button" value="点击我弹出json的值" />

</body>
</html>

后台servlet
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class jsonServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
//存的值是键值对的形式
json.put("name", "zhangsan");
//以json形式写到客户端
out.write(json.toString());
out.close();

}

}

web.xml 自动生成的
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.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>jsonServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>jsonServlet</servlet-name>
<url-pattern>/jsonServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-06-02
在用printwriter.write(json) 返回给客户端。
接受从客户端传来的param,如servlet.getParameter("name");
在定义一个String json = "";
json="这里要写你客户端json Store的格式"

printwriter.write(json);

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网