Android_WebView加载网页保存信息到Cookie
WebView加載網頁保存信息到Cookie
?
?
一.知識點
??? 1.WebView加載INTERNET網頁
?????? 2.Android Activity和網頁jsp之間傳遞參數
?????? 3.Jsp存儲數據到本地計算機中,通過Cookie實現設置默認值
二.代碼分析
1、PropertyActivity.java
package com.esri.arcgis.android.map;
?
import org.json.JSONArray;
import org.json.JSONObject;
?
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
?
public class PropertyActivity extends Activity {
??? private static final String TAG = "PropertyActivity";
??? private WebView webView;
??? private Handler handler = new Handler();
??? private Bundle bundle;
??? private Intent intent;
??? private String xStr = null;// X坐標
??? private String yStr = null;// Y坐標
??? private int dataType = 0;// 選擇的數據類型jsp頁面
??? private int selectType = 0;// 選擇的數據類型
?
??? @Override
??? protected void onCreate(Bundle savedInstanceState) {
?????? // TODO Auto-generated method stub
?????? super.onCreate(savedInstanceState);
?????? setContentView(R.layout.webview);
?
?????? // 獲得傳遞過來的參數
?????? intent = getIntent();
?????? bundle = intent.getExtras();
?????? xStr = String.valueOf(bundle.getDouble("xStr"));
?????? yStr = String.valueOf(bundle.getDouble("yStr"));
?
?????? selectType = bundle.getInt("dataType");
?????? if (selectType <= 3) {
?????????? dataType = 0;
?????? } else if (selectType > 3 && selectType <= 7) {
?????????? dataType = 1;
?????? } else {
?????????? dataType = selectType;
?????? }
?
?????? webView = (WebView) this.findViewById(R.id.webView);
?????? webView.getSettings().setJavaScriptEnabled(true); // 設置支持javaScript
?????? webView.getSettings().setSaveFormData(false); // 不保存表單數據
?????? webView.getSettings().setSavePassword(false); // 不保存密碼
?????? webView.getSettings().setSupportZoom(false); // 不支持頁面放大功能
?????? webView.addJavascriptInterface(new MyJavaScript(), "itcast");
//addJavascriptInterface方法中要綁定的Java對象及方法要運行在另外的線程中,不能運行在構造他的線程中
?????? webView.loadUrl("http://192.168.0.44:8090/JNDLS/property_add"
????????????? + dataType + ".jsp");
webView.setWebViewClient(new MyWebViewClient());
?
??? }????????????????????????????????????????????????
?
??? @Override
??? public boolean onKeyDown(int keyCode, KeyEvent event) {
?????? if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
?????????? webView.goBack();
?????????? return true;
?????? }
?????? return super.onKeyDown(keyCode, event);
??? }
?
??? private final class MyJavaScript {
?
?????? @SuppressWarnings("unused")
?????? public void backActivity(final int i) {
?????????? handler.post(new Runnable() {
????????????? public void run() {
????????????????? if (i == 1) {
???????????????????? PropertyActivity.this.setResult(RESULT_OK, intent);
????????????????? } else if (i == 0) {
???????????????????? PropertyActivity.this
??????????????????????????? .setResult(RESULT_CANCELED, intent);
????????????????? }
????????????????? PropertyActivity.this.finish();
????????????? }
?????????? });
?????? }
?
?????? @SuppressWarnings("unused")
?????? public void getParameter() {
?????????? handler.post(new Runnable() {
????????????? public void run() {
????????????????? String json = buildJson(xStr, yStr);
????????????????? webView.loadUrl("javascript:show('" + json + "')");
????????????? }
?????????? });
?????? }
?
//生成Json格式的數據
?
?????? private String buildJson(String x, String y) {
?????????? try {
????????????? JSONArray array = new JSONArray();
????????????? JSONObject item = new JSONObject();
????????????? item.put("x", x);
????????????? item.put("y", y);
????????????? item.put("selectType", selectType);
????????????? array.put(item);
?????? ?????? return array.toString();
?????????? } catch (Exception e) {
????????????? Log.e(TAG, e.toString());
?????????? }
?????????? return "";
?????? }
??? }
?
??? public class MyWebViewClient extends WebViewClient {
?????? public boolean shouldOverviewUrlLoading(WebView view, String url) {
?????????? view.loadUrl(url);
?????????? return true;
?????? }
??? }
}
???????
?
2.webwiew.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
??? android:orientation="vertical"
??? android:layout_width="fill_parent"
??? android:layout_height="fill_parent"
??? >
<WebView android:id="@+id/webView"
?????? android:layout_width="fill_parent"
?????? android:layout_height="fill_parent"/>
</LinearLayout>
3. property_add8.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
Cookie[] cookies=request.getCookies();
//判斷是否為空
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
??? Cookie c=cookies[i];
??? String name=c.getName();
??? String value=c.getValue();
??? request.setAttribute(name, value);
}
}
%>
?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
??? <head>
?????? <base href="<%=basePath%>">
?
?????? <title>添加變壓器屬性頁面</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">
?????? <script type="text/javascript">
function show(jsondata){
var jsonobjs = eval(jsondata);
for(var y=0; y<jsonobjs.length; y++){
window.document.getElementById("xzuobiao").value=jsonobjs[y].x;
window.document.getElementById("yzuobiao").value=jsonobjs[y].y;
window.document.getElementById("selectType").value=jsonobjs[y].selectType;
}
}
</script>
??? </head>
??? <body bgcolor="#F4BD66" text="#000000" style="margin: 0 0 0 0"
?????? onload="javascript:itcast.getParameter()">
?????? <form method="post" action="./propertyAddBYQ">
?????????? <table border="0" width="100%" id="personTable" cellspacing="0">
????????????? <tr>
????????????????? <td colspan="2" align="center">
???????????????????? <font color="green"><b>添加變壓器屬性頁面</b></font>
????????????????? </td>
??? ?????????? </tr>
????????????? <tr>
????????????????? <td>
???????????????????? <font color="green">變壓器名稱:</font>
????????????????? </td>
????????????????? <td>
???????????????????? <input type="text" name="byqmc" id="byqmc"
???????????????????????? value="${requestScope.byqmc}" />
????????????????? </td>
????????????? </tr>
????????????? <tr>
????????????????? <td>
???????????????????? <font color="green">變壓器容量:</font>
????????????????? </td>
????????????????? <td>
???????????????????? <input type="text" name="byqrl" id="byqrl"
???????????????????????? value="${requestScope.byqrl}" />
????????????????? </td>
????????????? </tr>
????????????? <tr>
????????????????? <td>
???????????????????? <font color="green">變壓器型號:</font>
????????????????? </td>
????????????????? <td>
???????????????????? <input type="text" name="byqxh" id="byqxh"
???????????????????????? value="${requestScope.byqxh}" />
????????????????? </td>
????????????? </tr>
????????????? <tr>
????????????????? <td>
???????????????????? <font color="green">備注:</font>
????????????????? </td>
????????????????? <td>
???????????????????? <textarea rows="3" cols="20" name="beizhu" id="beizhu"></textarea>
????????????????? </td>
????????????? </tr>
????????????? <tr>
????????????????? <td>
???????????????????? <font color="green">X:</font>
????????????????? </td>
????????????????? <td>
???????????????????? <input type="text" name="xzuobiao" id="xzuobiao"
???????????????????????? readonly="readonly" />
????????????????? </td>
????????????? </tr>
????????????? <tr>
????????????????? <td>
???????????????????? <font color="green">Y:</font>
????????????????? </td>
????????????????? <td>
???????????????????? <input type="text" name="yzuobiao" id="yzuobiao"
???????????????????????? readonly="readonly" />
????????????????? </td>
????????????????? <td></td>
????????????? </tr>
????????????? <tr>
????????????????? <td>
???????????????????? <input type="hidden" name="selectType" id="selectType" />
????????????????? </td>
????????????????? <td>
?
????????????????? </td>
????????????????? <td></td>
????????????? </tr>
????????????? <tr>
??? ????????????? <td>
???????????????????? <input type="submit" name="sub" id="sub" value="提交" />
????????????????? </td>
????????????????? <td>
???????????????????? <input type="button" name="cancel" id="cancel"
???????????????????????? onClick="window.itcast.backActivity(0)"value="取消" />
????????????????? </td>
????????????????? <td></td>
????????????? </tr>
?????????? </table>
?????? </form>
??? </body>
</html>
//程序解析:
//1.WebView加載網頁傳遞參數
//首先,在webview.xml中添加組件WebView,在PropertyActivity.java中進行了一些參數的設置,通過WebView.loadUrl()方法加載到網頁property_add8.jsp后,頁面通過JS變量在body中加載與之綁定的JAVA對象new MyJavaScript()的getParameter()方法,方法中將要傳遞到頁面的參數生成Json格式的數據,再次通過WebView.loadUrl()方法加載頁面JS方法show(),將參數傳遞到頁面JS方法中,然后對數據進行處理。
// Activity中webView.addJavascriptInterface(new MyJavaScript(), "itcast");方法將new MyJavaScript()類和itcast變量進行了綁定,在jsp頁面中可以通過window.itcast打點調用MyJavaScript()中的方法,如同JAVA操作,比如window.itcast.backActivity(0)。
//2.存儲網頁參數到Cookie,再次打開網頁設置默認值
?
?
4.Servlet部分代碼1
?
?????? public static void setBianYaQiCookies(HttpServletRequest request,
???????????????????? HttpServletResponse response) {
?
????????????? //創建一個Cookie對象,名稱為第一個參數,存儲的信息為第二個參數
????????????? Cookie cookie1 = new Cookie("byqmc", request.getParameter("byqmc"));
????????????? Cookie cookie2 = new Cookie("byqrl", request.getParameter("byqrl"));
????????????? Cookie cookie3 = new Cookie("byqxh", request.getParameter("byqxh"));
?
????????????? //把Cookie寫入到用戶本地計算機中
????????????? response.addCookie(cookie1);
????????????? response.addCookie(cookie2);
????????????? response.addCookie(cookie3);
?????? }
}
?
?
5. Servlet部分代碼2
//取出用戶機器中的Cookie
Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++){
??? Cookie c=cookies[i];
??? String name=c.getName();
??? String value=c.getValue();
??? request.setAttribute(name, value);
}
?
//Cookie存儲在用戶本地計算機上的數據
//代碼解析:
//用戶打開jsp頁面填寫完信息提交請求,請求到達Servlet中獲取頁面參數創建Cookie對象,存入本地計算機中。
在用戶打開jsp頁面前,首先從用戶本地計算機中取出Cookie,通過EL表達式在頁面相應位置顯示默認值,比如
<input type="text" name="byqmc" id="byqmc" value="${requestScope.byqmc}" />
?
//注意:如果要保存到Cookie中的值包含漢字的話,需要進行以下處理:
存:
Cookie cookie1 = new Cookie("byqmc", URLEncoder.encode( request.getParameter("byqmc"),?? "UTF-8"));
? cookie1.setMaxAge(36000);
response.setCharacterEncoding( "UTF-8 ");?
?? ? response.addCookie(cookie1);
取:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page language="java" import="java.net.URLDecoder"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
?Cookie c=cookies[i];
?String name=c.getName();
?String value=URLDecoder.decode(cookies[i].getValue(),?? "UTF-8");
?request.setAttribute(name, value);
}
}
%>
?//注釋:當漢字存放到Cookie中時進行了編碼,每個編碼之間都用%分隔。使用java.net.URLEncoder進行編碼,使用java.net.URLDecoder進行解碼。
倘若在JSP頁面中寫JAVA代碼,導入包時,pageEncoding編碼只能寫一個。
轉載于:https://www.cnblogs.com/southginger/archive/2011/10/09/2203648.html
總結
以上是生活随笔為你收集整理的Android_WebView加载网页保存信息到Cookie的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET 安全认证(二)——灵活运
- 下一篇: 安装两个硬盘时应如何跳线?