基于servlet的服务端与安卓客户端的通信(文本)

首先,先看一下服务端包的结构

基于servlet的服务端与安卓客户端的通信(文本)_第1张图片


首先是UserManager

package com.server.servelt;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.server.service.UserService;
import com.sun.mail.util.BASE64DecoderStream;

public class UserManager extends HttpServlet {
	private static final String CODE="UTF-8";
	public UserManager()
	{
		super();
	}
	public void destroy()
	{
		super.destroy();
	}
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException 
	{
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		//设置编码
		response.setContentType("text/html");
		response.setCharacterEncoding(CODE);
		request.setCharacterEncoding(CODE);
		
		//获取请求方法名,其中request_flag是我们安卓客户端请求的参数,详细介绍请参照servlet有关书籍
		String flag=request.getParameter("request_flag");
		System.out.println("flag="+flag);
		
		//预定义一个字符串,用来接收json
		String json="";
		if("login".equals(flag))
		{
			//此处的username和password也是安卓客户端访问网址的参数
			String username=request.getParameter("username");
			String password=request.getParameter("password");
			//调用UserService的login方法实现登录
			json=UserService.login(username, password);
		}
		//控制台输出,方便检验,无特殊含义
		System.out.println("json="+json);
		//利用输出流将登录信息(此处为success或是fail)反馈给客户端
		PrintWriter out=response.getWriter();
		out.write(json);
		out.flush();
		out.close();
	
	}
}

接着是上面调用到的 UserService
package com.server.service;

import com.server.dao.UserDao;
import com.server.util.JSONUtil;

public class UserService {
	public static String login(String username,Stri

你可能感兴趣的:(安卓,jsp,android,servlet,通信)