JavaWeb学习总结-05 Servlet 与页面的交互(02)
一 模拟请求数据
为了测试方便,把请求 json,txt, xml,html格式的文件放到了公网上面,可以通过以下地址请求:
http://wx.glab.cn/xpxiaowu4java/json/request.html http://wx.glab.cn/xpxiaowu4java/json/request.txt http://wx.glab.cn/xpxiaowu4java/json/request.xml http://wx.glab.cn/xpxiaowu4java/json/request.json
在升级的开发过程中,前台开发人员和后台的开发人员通常会先设计接口的交互格式,交互格式一般是xml, json,text格式的。约定好交互接口的数据个时候就可以互相开发,前台可以先用假数据进行测试开发,等后台开发人员开发好接口后,双方在进行联调。比如阿里云服务的api 就是这样。
https://help.aliyun.com/document_detail/28329.html?spm=5176.doc28328.6.120.3Vbf9z
打开Eclipse新建一个Web工程TestH5,在WebRoot 或 WebContent目录下新建一个文件夹json
测试环境:
JQuery jquery-3.1.0.js
Tomcat8
1 模拟请求html页面
新建 request.html页面,放置在 %/TestH5/WebRoot/json下面。
<!DOCTYPE html > <html> <head> <meta charset="utf-8" /> <style type="text/css"> p { border: 5px solid red; } a { text-decoration: none; } textarea:focus{ outline: none; //background-color: red; } </style> </head> <body> <p>这是一个段落</p> <p><a href="http://www.w3school.com.cn/index.html">这是一个链接</a></p> <textarea name="> </textarea> </body> </html>
测试访问本地服务器的web工程的request.html页面地址:
http://127.0.0.1:8080/TestH5/json/request.html
2 模拟请求JSON数据
新建 request.json,放置在 %/TestH5/WebRoot/json下面。
{ "RequestId": "4C467B38-3910-447D-87BC-AC049166F216", "name": "李四" }
测试访问本地服务器的web工程的request.json 地址:
http://127.0.0.1:8080/TestH5/json/request.json
3 模拟请求TXT数据
新建 request.txt,放置在 %/TestH5/WebRoot/json下面。
测试访问本地服务器的web工程的request.txt 地址:
http://127.0.0.1:8080/TestH5/json/request.txt
4 模拟请求XML数据
新建 request.xml,放置在 %/TestH5/WebRoot/json下面。
<?xml version="1.0" encoding="utf-8"?> <Response> <RequestId>4C467B38--447D-87BC-AC049166F216</RequestId> <username>王五</username> </Response>
测试访问本地服务器的web工程的request.xml 地址:
http://127.0.0.1:8080/TestH5/json/request.xml
Servlet 与页面的交互
前台页面使用JS的JQuery 库,使用Ajax模拟发送页面请求,具体参考 http://www.w3school.com.cn/jquery/ajax_ajax.asp,重点参考调用Ajax()方法中的dataType设置。
二 编写Servlet模拟发送不同类型的数据
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion></modelVersion> <groupId>com.gz</groupId> <artifactId>MavenWeb</artifactId> <packaging>war</packaging> <version>-SNAPSHOT</version> <name>MavenWeb Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version></version> <scope>test</scope> </dependency> <!-- WebSocket 编译需要引入的jar --> <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> <scope>compile</scope> </dependency> <!-- J2EE 编译需要引入的jar --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version></version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version></version> <scope>compile</scope> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6</version> </dependency> </dependencies> <build> <finalName>MavenWeb</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version></version> <configuration> <webXml>src/main/webapp/WEB-INF/web.xml</webXml> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://localhost:8080/MavenWeb/</url> <username>admin</username> <password>admin</password> </configuration> </plugin> </plugins> </pluginManagement> </build> <!-- 配置插件仓库 --> <repositories> <!-- restlet 插件仓库 --> <repository> <id>maven-restlet</id> <name>Public online Restlet repository</name> <url>http://maven.restlet.org</url> </repository> <repository> <id>maven2-repository.java.net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2/</url> </repository> <repository> <id>oschina Releases</id> <name>oschina Releases</name> <url>http://maven.oschina.net/content/groups/public</url> </repository> <repository> <id>nexus-osc</id> <name>Nexus osc</name> <url>http://maven.oschina.net/content/groups/public/</url> </repository> <repository> <id>nexus-osc-thirdparty</id> <name>thirdparty</name> <url>http://maven.oschina.net/content/repositories/thirdparty/</url> </repository> <!-- jesery插件仓库 --> <repository> <id>snapshot-repository.java.net</id> <name>Java.net Snapshot Repository for Maven</name> <url>https://maven.java.net/content/repositories/snapshots/</url> <layout>default</layout> </repository> </repositories> </project>
TestAjaxServlet.java
package com.mobile.action; import java.io.IOException;import java.io.PrintWriter;import java.util.HashMap;import java.util.Map; import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element; import com.alibaba.fastjson.JSONObject; public class TestAjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("--- TestAjaxServlet doGet"); doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); System.out.println("--- TestAjaxServlet doPost method=" + method); if (null != method) { if (method.toLowerCase().equals("sendRequest4Html".toLowerCase())) { handleRequestForHtml(request, response); } else if (method.toLowerCase().equals("sendRequest4Json".toLowerCase())) { handleRequestForJSON(request, response); } else if (method.toLowerCase().equals("sendRequest4Txt".toLowerCase())) { handleRequestForTxt(request, response); } else if (method.toLowerCase().equals("sendRequest4Xml".toLowerCase())) { handleRequestForXml(request, response); } else if (method.toLowerCase().equals("sendRequest4Jsonp".toLowerCase())) { handleRequestForJsonp(request, response); } }else{ handleRequestForJSON(request, response); } } private void handleRequestForTxt(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("--- handleRequestForTxt actions request "); response.setContentType("text/plain;charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println("<h1>你好 ,中秋快乐 ,333!!</h1>"); out.println("<h2>Hello, I am a servlet.</h2>"); out.println("<h3>Hello, I am a servlet.</h3>"); out.flush(); out.close(); } private void handleRequestForJsonp(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("--- handleRequestForJsonp actions request "); response.setContentType("application/javascript;charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); StringBuilder scriptTmp = new StringBuilder(); scriptTmp.append("sayHello('老王');"); // scriptTmp.append("alert('lisi');\n"); String scriptStr = scriptTmp.toString(); out.println(scriptStr); // out.println("alert('hello')"); out.flush(); out.close(); } private void handleRequestForHtml(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("--- handleRequestForHtml actions request "); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println("<h1>你好 ,中秋快乐 ,333!!</h1>"); out.println("<h2>Hello, I am a servlet.</h2>"); out.println("<h3>Hello, I am a servlet.</h3>"); out.flush(); out.close(); } private void handleRequestForXml(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("--- handleRequestForXml actions request "); response.setContentType("text/xml;charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); /* * StringBuilder temp = new StringBuilder(); * temp.append("<QuerySimpleResponse>"); * temp.append("<Score>0</Score>"); * temp.append("</QuerySimpleResponse>"); out.println(temp.toString()); */ out.println(getXml()); out.flush(); out.close(); } private String getXml() { Document doc = DocumentHelper.createDocument(); Element responseEle = doc.addElement("response"); responseEle.addAttribute("id", "12345678"); Element nameEle = responseEle.addElement("username"); Element ageEle = responseEle.addElement("age"); nameEle.setText("王五"); ageEle.setText("30"); return doc.asXML(); } private void handleRequestForJSON(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("--- handleRequestForJSON actions request "); String years = request.getParameter("years"); String username = request.getParameter("username"); System.out.println("years=" + years); System.out.println("username=" + username); response.setContentType("application/json;charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject userObj = new JSONObject(); userObj.put("name", "李四"); userObj.put("gender", "male"); userObj.put("address", "北京"); /*try { Thread.sleep(1000 * 10); } catch (InterruptedException e) { e.printStackTrace(); }*/ out.println(userObj.toJSONString()); out.flush(); out.close(); } }
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app > <display-name>MavenWeb</display-name> <servlet> <servlet-name>TestAjaxServlet</servlet-name> <display-name>TestAjaxServlet</display-name> <description></description> <servlet-class>com.mobile.action.TestAjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestAjaxServlet</servlet-name> <url-pattern>/TestAjaxServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
JSONP测试页面代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/jquery-3.1.0.js"> </script> <script type="text/javascript"> function sayHello(name) { alert('hello 我是本地函数,可以被跨域调用,远程js带来的数据:' + name); } function sendRequest4JSONP(){ var inputDataObj ={}; inputDataObj.method="sendRequest4Jsonp"; inputDataObj.username="wangwu"; inputDataObj.years = ; $.ajax( { type : "post", dataType : "jsonp", data: inputDataObj, jsonpCallback: "sayHello", url : "http://127.0.0.1:8080/MavenWeb/TestAjaxServlet", success : function(result) { console.log(typeof(result)); console.log( "result="+ result ); $("#resultDisplay").html( result); }, // error : function(XMLHttpRequest, textStatus, errorThrown) { alert('throw error! ,errorThrown='+errorThrown); } }); } $(document).ready(function() { $("p").click(function() { $(this).hide(); }); $("#sendRequest4JSONP").click(function() { sendRequest4JSONP(); }); }); </script> <style> p { width: 100px; height: 100px; background-color: red; } </style> </head> <body> <p> 这是段落,这是段落,这是段落,</p> <div> <form id="register" action="#" method="post"></form> <input type="button" value="clearInfo" id="clearInfo" /> <input type="button" value="sendRequest4JSONP" id="sendRequest4JSONP" /> <div id="resultDisplay"></div> </div> </body> </html>
本地AJAX测试页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> p { width: 100px; height: 100px; background-color: red; } </style> </head> <body> <p> 这是段落,这是段落,这是段落,</p> <div> <form id="register" action="#" method="post"></form> <input type="button" value="clearInfo" id="clearInfo" /> <input type="button" value="sendRequest4JSONP" id="sendRequest4JSONP" /> <input type="button" value="sendRequest4JSON" id="sendRequest4JSON" /> <input type="button" value="sendRequest4Xml" id="sendRequest4Xml" /> <hr/> <h1> <output id="resultDisplay"></output> </h1> </div> <script type="text/javascript" src="js/jquery-3.1.0.js"> </script> <script type="text/javascript"> function sayHello(name) { alert('hello 我是本地函数,可以被跨域调用,远程js带来的数据:' + name); } function sendRequest4JSONP(){ var inputDataObj ={}; inputDataObj.method="sendRequest4Jsonp"; inputDataObj.username="wangwu"; inputDataObj.years = ; $.ajax( { type : "post", dataType : "jsonp", data: inputDataObj, jsonpCallback: "sayHello", url : "http://127.0.0.1:8080/MavenWeb/TestAjaxServlet", success : function(result) { console.log(typeof(result)); console.log( "result="+ result ); $("#resultDisplay").html( result); }, // error : function(XMLHttpRequest, textStatus, errorThrown) { alert('throw error! ,errorThrown='+errorThrown); } }); } function sendRequest4Json(){ var inputDataObj ={}; inputDataObj.method="sendRequest4Json"; inputDataObj.username="wangwu"; inputDataObj.years = ; $.ajax( { //(默认: "GET",请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法 type : "post", //同步,异步请求设置, 默认是true:异步 ;false:同步请求。 async: true , //响应返回的数据格式 json,html,xml,text dataType : "json", data: inputDataObj, url : "/MavenWeb/TestAjaxServlet", //请求超时时间 //timeout: 1 , success : function(result) { var jsonStr = JSON.stringify( result); console.log( jsonStr ); console.log( typeof result ); var name = result.name; console.log("name=" + name ); var jsonStr = JSON.stringify( result); $("#resultDisplay").html( jsonStr); }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert('ajax throw error! ,errorThrown='+errorThrown); console.log('ajax throw error! errorThrown=' + errorThrown ); } }); } function sendRequest4Xml(){ var inputDataObj ={}; inputDataObj.method="sendRequest4Xml"; inputDataObj.username="wangwu"; inputDataObj.years = ; $.ajax( { type : "post", async: true , dataType : "xml", data: inputDataObj, url : "/MavenWeb/TestAjaxServlet", success : function(result) { // console.log( result.toString() ); // console.log(typeof(result)); //xml var idVal = $(result).find("response").attr("id"); $(result).find("response"); console.log('idVal='+ idVal ); var username = $(result).find("response username").text(); console.log("username=" + username); var displayResult = ''; $(result).find("response").each(function(i){ var username=$(this).children("username").text(); var age = $(this).children("age").text(); console.log("step1 username="+username +",age=" + age); displayResult = "username="+username +",age=" + age ; }); console.log( "displayResult="+displayResult ); $("#resultDisplay").html( displayResult ); }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert('ajax throw error! ,errorThrown='+errorThrown); console.log('ajax throw error! errorThrown=' + errorThrown ); } }); } $(document).ready(function() { $("p").click(function() { $(this).hide(); }); $("#sendRequest4JSONP").click(function() { sendRequest4JSONP(); }); $("#sendRequest4JSON").click(function() { console.log("step1 send request !!!"); sendRequest4Json(); console.log("step2 send request !!!"); }); $("#sendRequest4Xml").click(function(){ sendRequest4Xml(); }); }); </script> </body> </html>
二 Ajax传值中文 ,避免乱码
1) 页面发送 get 请求
function queryJson3(){ var timestamp = (new Date()).getTime(); var url ="/TestAliServlet?"; url = url +"timestamp="+timestamp +"&username="+ encodeURI(encodeURI('王五') ) ; $.ajax({ url:url , async: true, dataType:"json", success: function(data){ }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log("errorThrown="+errorThrown+"\n"); } }); }
2)后台代码处理
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); System.out.println("--- TestAliServlet ---"); String timestamp = request.getParameter("timestamp"); String username = URLDecoder.decode(username, "UTF-8"); System.out.println("* username2=" + username2); response.setContentType("application/json;charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject userObj = new JSONObject(); userObj.put("name", username); userObj.put("time", new Date()); userObj.put("age", age); out.println(userObj.toJSONString()); out.flush(); out.close(); }
3)页面中以json对象作为参数,发送get请求
function queryJson4(){ var url ="/TestAliServlet"; var inputDataObj ={}; inputDataObj.username="李四"; inputDataObj.age = ; inputDataObj.timestamp = (new Date()).getTime(); $.ajax( { type : "post", async: true , dataType : "html", data: inputDataObj, url : url, success : function(data) { }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert('ajax throw error! ,errorThrown='+errorThrown); } }); }
三 通过超链接传递中文参数
资料参考:
http://zhidao.baidu.com/question/585211909.html?fr=iks&word=content+type&ie=gbk
http://kb.cnblogs.com/page/139725/
ajax乱码解决方案:
http://www.jb51.net/article/31791.htm
跨域访问
http://www.cnblogs.com/2050/p/3191744.html
JavaWeb学习总结-05 Servlet 与页面的交互(02)的更多相关文章
- JavaWeb学习总结-05 Servlet 学习和使用(01)
一 Servlet的原理 1 Servlet 的创建 当Servlet容器启动web应用时,需要立即加载Servlet时: Servlet容器启动web应用时,将按照指定的顺序初始化Servlet,需 ...
- 动态include是通过servlet进行页面信息交互的
动态include是通过servlet进行页面信息交互的
- javaweb学习总结(六)——Servlet开发(二)
一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个<init-param>标签为servlet配置一些 ...
- javaweb学习总结(六)——Servlet开发(二)(转)
转载自 http://www.cnblogs.com/xdp-gacl/p/3763559.html 一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文 ...
- JavaWeb学习总结-04 Servlet 学习和使用
一 Servlet 1 Servlet概念 Servlet时运行在服务器端的Java程序. Servlet的框架核心是 javax.servlet.Servlet 接口. 所有自定义的Servlet都 ...
- JavaWeb学习笔记之Servlet(一)
1. 引子: 当我们开始进入JavaWeb开发的学习时,我们就必须要和Servlet和HTTP这两个词进行打交道了,尤其是Servlet.即使到了后面使用JSP (我们知道JSP其本身就是一个Serv ...
- JavaWeb学习笔记:Servlet
Servlet JavaWeb 概念 Java Web应用由一组Servlet.HTML页面.类.以及其他能够被绑定的资源构成. 他能够在各种供应商提供的实现Servlet规范的Servlet容器中执 ...
- JavaWeb学习篇之----Servlet
今天来继续学习JavaWeb的相关知识,之前都是都介绍一些基本知识,从今天开始我们来说一下如何在服务器编写程序,这里就需要来介绍一下Servlet的相关知识了.Servlet就是一个能够运行在服务器端 ...
- javaweb学习总结(五)——Servlet开发(一)
一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...
随机推荐
- Java 的世界,我不懂:奇葩的 json 序列化
先上张图,代表我心中的十万头草泥马: 写这么长的代码,头回见数组和单个实体共用同一个 json 节点的! 恐怕只有 java 社区的大牛B 才能做出这等事.. 由 Apache 发布: http:// ...
- java并发:线程同步机制之Volatile关键字&原子操作Atomic
volatile关键字 volatile是一个特殊的修饰符,只有成员变量才能使用它,与Synchronized及ReentrantLock等提供的互斥相比,Synchronized保证了Synchro ...
- hbase-site.xml 配置详解
hbase.rootdir 这个目录是region server的共享目录,用来持久化HBase.URL需要是'完全正确'的,还要包含文件系统的scheme.例如,要表示hdfs中的'/hbase'目 ...
- 深入理解计算机系统(2.7)---二进制浮点数,IEEE标准(重要)
2.6我们进行了二进制整数运算的最后一役,本次LZ将和各位一起进入浮点数的世界,这里没有无符号,没有补码,但是有各种各样的惊奇.倘若你真正的进入了浮点数的世界,一定会发现它原来是这么有意思,而不是像之 ...
- XSS attack
<html> <form action="" method="post"> <input type="text" ...
- oracle 学习笔记
--2.2 进入和退出oracle数据库--在windows中输入cmd打开命令窗口 然后输入 sqlplu / as sysdba--验证数据库是否安装成功 --select status from ...
- go -- 返回的json怎么去掉字段为空的字段啊
- android获得图片
首先是相册图片的获取: private final String IMAGE_TYPE = "image/*"; private final int IMAGE_CODE = 0; ...
- 1017关于EXPLAIN的语法
转自博客 http://blog.csdn.net/zhuxineli/article/details/14455029 explain显示了MySQL如何使用索引来处理select语句以及连接表.可 ...
- GBDT和RF的区别
去XX公司实习的时候,被问过,傻逼的我当时貌似都答错了,原谅全靠自学的我,了解甚少 RF随着树的增加不会过拟合 GBDT随着树的增加会过拟合 RF还会对特征进行random,例如特征的个数m=sqrt ...