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

    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

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">Xfont>

                  td>

                  <td>

                     <input type="text" name="xzuobiao" id="xzuobiao"

                         readonly="readonly" />

                  td>

              tr>

              <tr>

                  <td>

                     <font color="green">Yfont>

                  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方法中,然后对数据进行处理。

// ActivitywebView.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

    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  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编码只能写一个。


你可能感兴趣的:(android,进阶)