WebView加载网页保存信息到Cookie

 

 

一.知识点

    1.WebView加载INTERNET网页

       2.Android Activity和网页jsp之间传递参数

       3.Jsp存储数据到本地计算机中,通过Cookie实现设置默认值

二.代码分析

1PropertyActivity.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相关推荐

  1. python爬取qq群成员_Python selenium 加载并保存QQ群成员,去除其群主、管理员信息的示例代码...

    一位伙计自己开了个游戏室,想在群里拉点人,就用所学知识帮帮忙,于是就有了这篇文章,今天小编特此通过实例代码给大家介绍下Python selenium 加载并保存QQ群成员去除其群主.管理员信息的示例代 ...

  2. Python--selenium 加载并保存QQ群成员,去除其群主、管理员信息

    Python–selenium 加载并保存QQ群成员,去除其群主.管理员信息. 一位老哥自己开了个游戏,想在群里拉点人,就用所学知识帮帮忙,于是就有了这篇文章... 拙笔,拿来分享一下.纯属原创,其他 ...

  3. Android中使用x5内核加载网页的实现

    前言 联系方式 背景 SDK下载 SDK集成 使用 代码实现 前言 由于是使用的腾讯浏览服务,所以这里大部分介绍的是官网的一些东西,不过自己会做一些复杂使用部分的实现,不至于像官网上介绍的笼统. 联系 ...

  4. Qt 之QWebEngineVie框架简介及加载网页方法

    文章目录 基于Widget的QWebEngine架构 QWebEngineView 关于QWebEngineView下QWebEnginePage的疑问 QWebEnginePage page和pro ...

  5. Android Native APP开发笔记:使用WebView控件加载网页

    文章目录 目的 基础使用 处理网页导航 加载本地网页 Web和Native之间交互 调试Web应用 处理页面重绘 总结 目的 WebView是一个比较常用的控件,功能上也比较单一,就是用来加载网页的, ...

  6. 使用Hibernate加载或保存图像-MySQL

    本教程将引导您逐步了解如何使用Hibernate从数据库( MySQL )保存和加载图像. 要求 对于此示例项目,我们将使用: Eclipse IDE (您可以使用自己喜欢的IDE): MySQL ( ...

  7. PyTorch框架学习十九——模型加载与保存

    PyTorch框架学习十九--模型加载与保存 一.序列化与反序列化 二.PyTorch中的序列化与反序列化 1.torch.save 2.torch.load 三.模型的保存 1.方法一:保存整个Mo ...

  8. 安卓app单webview改为多webview加载网页

    这几天用csdn的手机版,觉得用户体验不错,和我们的产品类似,也是采用webview来加载的页面,区别是它他每加载一个页面,都会启用一个新的webview来加载.         我们安卓平台只有一个 ...

  9. win10浏览器加载很慢_win10加载网页很慢_win10打开浏览器加载网页很慢处理技巧...

    win10加载网页很慢_win10打开浏览器加载网页很慢处理技巧 在当下用电脑办公很普遍了,相当一部份用户经历了xp,win7/win8/系统,现在又出了个win10系统,随着硬件的老化与win7支持 ...

最新文章

  1. python2基础教程廖雪峰云-Python基础
  2. ACL 2021 | 结构化知识蒸馏方法
  3. ASP.NET GridView控件在列上格式化时间
  4. [LeetCode] NO. 8 String to Integer (atoi)
  5. BUAA软工第0次作业
  6. 真正的轻量级WebService框架——使用JAX-WS(JWS)发布WebService
  7. linkedblockingqueue 后 take 不消化_消化不良的症状原因有哪些?
  8. Github上最热门的11个Java开源项目你会了吗
  9. 安装pdfFactory Pro
  10. Android waitting for debugger
  11. PDF Converter OCR for Mac(PDF转换器和OCR识别工具)
  12. 基于SpringBoot的分销商城的设计与实现(论文+源码)_kaic
  13. 各大门户免费登录入口
  14. Matlab影像处理二
  15. 农产品进出口成都代办公司注册流程
  16. Photoshop脚本开发环境
  17. Discuz更改帖子标题的字符长度限制
  18. 唐骏的成功——可以复制的成功
  19. PCL:RANSAC算法拟合直线的两种实现方式
  20. SQL: 视图和表的区别

热门文章

  1. linux下随机数字的生成
  2. EasyPR-Java开源中文车牌识别系统工程部署
  3. 数据结构源码笔记(C语言):顺序查找
  4. 通过virtualbox最小化安装centos 6.3后无法上网解决办法
  5. 数据库知识点2——关系模型之基本概念
  6. (转)跟我一起写 Makefile(一)(陈皓)
  7. 三星电子电容器件识别
  8. CTFshow php特性 web111
  9. n数码问题,全排列的hash(转载
  10. matlab 暂停命令(pause和input)