默认你是知道cookie的,不懂的请移步http://blog.csdn.net/wei_chong_chong/article/details/52297011
案例就是本地的登录界面与网页的登录信息如何同步的问题:做混合开发的时候经常遇到的问题是,本地实现登录界面,登录成功后,使用webView加载网页,这时网页会提示需要登录。这显然是不友好的。
如何把本地的登录信息与网页的登录同步呢?或者网页登录成功后,又如何同步到本地呢?本地如何获取网页的登录信息呢?这里你可以得到答案
下面就来实现这个功能。
这里会遇到两个问题。
1.客户端登录时如何取出cookie信息
2.如何把取出的cookie信息与webview同步传递给服务器
写一个获取cookie的类,本地登录获取cookie
package com.example.androidtest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
//WevView Cookie同步问题
public class HttpCookie extends Thread {
private Handler handler;
private String ASP_SessionId;
public HttpCookie(Handler handler){
this.handler = handler;
}
@Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.8.227:8080/manyiApp/WebCookieLoginCheckServlet");
List<NameValuePair> list = new ArrayList<NameValuePair>();
try {
list.add(new BasicNameValuePair("name", "nates"));
list.add(new BasicNameValuePair("age", "21"));
Date sessionTime = new Date();
post.setEntity(new UrlEncodedFormEntity(list));
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode()==200){
AbstractHttpClient absClient = (AbstractHttpClient) client;
List<Cookie> cookies = absClient.getCookieStore().getCookies();
if (!cookies.isEmpty()) {
for(Cookie cookie:cookies){
Log.i("TAG", cookie.toString());//获取cookie信息并打印
Message message = new Message();
message.obj = cookie;
handler.sendMessage(message);
//return;
}
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
通过调用
HttpCookie mCookie = new HttpCookie(handler);
mCookie.start();
就可以运行获取cookie信息了并通过handler发送获取的cookie信息
下面是获取handler中的cookie信息,并给webview设置cookie信息
package com.example.androidtest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webView;
private Handler handler = new Handler(){
@SuppressLint("NewApi") public void handleMessage(android.os.Message msg) {
Log.i("TAG", "GethandlerCookies-----"+msg.obj.toString());
CookieSyncManager.createInstance(MainActivity.this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie("http://192.168.8.227:8080/manyiApp", msg.obj.toString());//这样设置url就可以同步manyApp目录下所有页面的cookie信息了
CookieSyncManager.getInstance().sync();
//webView.getSettings().setJavaScriptEnabled(true);//是支持JavaScript语言
webView.loadUrl("http://192.168.8.227:8080/manyiApp/Login.jsp");
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.myWebView);
webView.setWebViewClient(new MyWebViewClient());// webView.setWebViewClient()网页加载默认是使用浏览器的,这里需要设置一下
webView.setWebChromeClient(new WebChromeClient(){
@Override
public void onReceivedTitle(WebView view, String title) {
// TODO Auto-generated method stub
super.onReceivedTitle(view, title);
Log.i("TAG", title);//获取网页title
}
});
HttpCookie mCookie = new HttpCookie(handler);
mCookie.start();//获取cookie信息
}
/*
* 去掉WebView显示的网页中的进度条和网址使更像客服端应用程序
*
* */
class MyWebViewClient extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);//覆盖浏览器打方式,(不使用浏览器打开页面 )
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
CookieManager cookieManager = CookieManager.getInstance();
String CookieStr = cookieManager.getCookie(url);
//Log.e("TAG", "Cookies = " + CookieStr);这里可以实现,在网页端登录后获取cookie信息并同步到本地登录
super.onPageFinished(view, url);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK&&webView.canGoBack()){
webView.goBack();//返回上个页面
return true;
}
return super.onKeyDown(keyCode, event);//退出整个应用程序
}
}
下面是Web服务器端代码
WebCookieLoginCheckServlet
package com.beijing.manyi.appservlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.xml.internal.txw2.Document;
/**
* Servlet implementation class WebCookieLoginCheckServlet
*/
public class WebCookieLoginCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WebCookieLoginCheckServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("utf-8");
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println("name:"+name+""+"age:"+age);
Cookie c=new Cookie(name, age);//将得到的数据存入cookie 第一个参数是cookies中 name的值,第二个参数是value得值
c.setMaxAge(600);
//存储
response.addCookie(c);
if(name.equals("nates")&&(age.equals("21"))){
// request.getSession().setAttribute("name", name);
request.getRequestDispatcher("loginsuccess.jsp").forward(request, response);
}else{
request.getRequestDispatcher("Login.jsp").forward(request, response);
}
}
}
Login.jsp页面,判断cookie信息,如果符合就不用登录了直接跳转到登录成功的页面response.sendRedirect("loginsuccess.jsp");
但是貌似没效果,js学的太烂,请大神指点哪里错了
<%@page import="javafx.scene.control.Alert"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().endsWith("nates")) {
response.sendRedirect("loginsuccess.jsp");
return;
}
}
}
%>
<body>
This is my Jsp pages
<form action="WebCookieLoginCheckServlet" method="post">
name:<input type="text" name="name"><br>age:<input
type="text" name="age"><br> submit:<input type="submit"
value="登录">
</body>
</html>