1. 程式人生 > >getWriter() 和Response.getOutputStream衝突

getWriter() 和Response.getOutputStream衝突

package com.segsec.gisap.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletUtil {
	@SuppressWarnings("unchecked")
	public static void forward(String url, HttpServletRequest request, HttpServletResponse response) throws IOException{
		forward(url, request, response, "utf-8");
	}
	
	@SuppressWarnings("unchecked")
	public static void forward(String url, HttpServletRequest request, HttpServletResponse response, String encode) throws IOException{
		StringBuilder surl = new StringBuilder(url);
		Enumeration er = request.getParameterNames();
		if(er.hasMoreElements()){
			String name = (String) er.nextElement();
			surl.append("?").append(name).append("=").append(URLEncoder.encode(request.getParameter(name), encode));
		}
		while(er.hasMoreElements()){
			String name = (String) er.nextElement();
			surl.append("&").append(name).append("=").append(URLEncoder.encode(request.getParameter(name), encode));
		}
//		System.out.println("surl:" + surl);
		InputStream is = null;
		ServletOutputStream os = null;
		try {
			os = response.getOutputStream();
			URL u = new URL(surl.toString());
			is = u.openStream();
			byte[] buff = new byte[1024];
			int len;
			while((len = is.read(buff)) != -1){
				os.write(buff, 0, len);
			}
			os.flush();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			throw new IOException(e);
		}finally{
			try{
				if(is != null){
					is.close();
				}
			}catch (IOException e) {
				e.printStackTrace();
			}
			
			try{
				if(os != null){
					os.close();
				}
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

package com.segsec.gisap.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

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

import mapbar.MapbarInterface;
import mapbar.bean.Poi;

import com.general.FormatUtil;
import com.googlecode.jsonplugin.JSONUtil;
import com.segsec.gisap.dao.MenuDAO;
import com.segsec.gisap.util.Config;

/**
 * 通過省份名稱和查詢條件查詢地名
 * @author Administrator
 * 電召的按地址搜尋和 地圖搜尋;
 *
 */
public class SearchAddress extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private boolean searchAddress_use_agent = false;
	private String searchAddress_agent_url = "http://113.106.90.236/searchAddress";
	
	@Override
	public void init() throws ServletException {
		String configPath = Config.getConfigPath();
		String systemConfigFile = configPath + "config/system.properties";
		try {
			Properties properties = com.segsec.gisap.util.Util.loadProperties(systemConfigFile);
			searchAddress_use_agent = Boolean.valueOf(properties.getProperty("searchAddress_use_agent"));
			searchAddress_agent_url = properties.getProperty("searchAddress_agent_url");
			System.out.println("searchAddress_use_agent:" + searchAddress_use_agent);
			System.out.println("searchAddress_agent_url:" + searchAddress_agent_url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if(searchAddress_use_agent){
			ServletUtil.forward(searchAddress_agent_url, request, response);
			return;
		}
		/*
		 * 從客戶端取得 城市名稱,對應省份子表的名稱,查詢條件
		 */
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-json;charset=UTF-8");
    	PrintWriter pw=response.getWriter(); 
    	
		String tablename = request.getParameter("tablename");
		String restrict= FormatUtil.isoconversionutf8(request.getParameter("restrict"));
		String iscity=request.getParameter("iscity");
		String cityname=request.getParameter("cityname");
		int start=Integer.parseInt(request.getParameter("start"));
		int end=Integer.parseInt(request.getParameter("limit"));
		
		String str = request.getParameter("isMapbar");
		int isMapbar = 0;
		if(str != null) {
			try {
				isMapbar = Integer.parseInt(str);
			}catch(Exception e) {}
		}
		
		//如果是Mapbar
		if(isMapbar == 1) {
			int limit = end;
			List<Poi> ps = MapbarInterface.getPoiByKeyword(cityname, restrict, 1, limit);
			int size = ps.size();
			Map map = new HashMap();
			map.put("pagenumbercount", size);
			
			Map obj = null;
			String tmp = null;
			String[] lonlat = null;
			List list = new ArrayList();
			for(Poi p : ps) {
				obj = new HashMap();
				obj.put("name", p.getName());
				tmp = p.getStrlatlon();
				if(tmp != null) {
					lonlat = tmp.split(",");
				}
				if(lonlat != null && lonlat.length > 1) {
					obj.put("lon", lonlat[0]);
					obj.put("lat", lonlat[1]);
				}
				obj.put("addname", p.getAddress());
				obj.put("telephone", p.getPhone());
				list.add(obj);
			}
			map.put("list", list);
			try{
				String resp = JSONUtil.serialize(map);
				pw.println(resp);
				pw.flush();
			}catch(Exception ex){
				System.out.println("Query SearchAddress to Error"+ex);
			}finally{
				pw.close();
			}
		}else {
			MenuDAO dao = new MenuDAO();
			HashMap hm;
			if(iscity!=null&&cityname!=null){
				if(cityname.equals("全國")){
					 hm = dao.queryPOINTALL(tablename, restrict,start,start+end);
				}else if(iscity.equals("true")){
					 hm = dao.queryPOINTCity(tablename, cityname,restrict,start,start+end);
				}else{
					 hm = dao.queryPOINTPro(tablename, restrict,start,start+end);
				}
				 
			}else{
			  hm = dao.queryPOINT(tablename, restrict,start,start+end);
			}
			try{
		    /*AJAX 物件序列化一個Object 物件輸出到客戶端*/
			String obj=JSONUtil.serialize(hm);
			pw.println(obj);
			pw.flush();
			}catch(Exception ex){
				System.out.println("Query SearchAddress to Error"+ex);
			}finally{
				pw.close();
			}
		}
	}
	


}

win.findAddressStore
														.load({
															method : 'post',
															params : {
																start : 0,
																limit : 20,
																'tablename' : tablename,
																'restrict' : restrict,
																cityname : cityname,
																isMapbar : 1
															// isMapbar || 0
															},
															callback : function(r,opt,success) {
																btn.enable();
																if (!success) {
																	alert("查詢失敗!:"
																			+ tablename
																			+ "\n restrict:"
																			+ restrict);
																}
															}
														});