⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mapperservlet.java

📁 利用mapxtreme java的实现的WebGis
💻 JAVA
字号:
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.Color;
import java.io.*;
import java.util.*;

// Needed in this servlet for MapJ support
import java.net.Socket;

// MapInfo classes
import com.mapinfo.mapj.*;
import com.mapinfo.util.*;
import com.mapinfo.unit.LinearUnit;
import com.mapinfo.mapxtreme.client.*;
import com.mapinfo.xmlprot.mxtj.ImageRequestComposer;

/**
 * This is a simple example of an HTTP Map Servlet that extends the HttpServlet
 * class and contains MapJ objects.  This servlet is designed to send
 * map images down to an applet (MapperClientApplet.java). 
 *
 * @see javax.servlet.http.HttpServlet , com.mapinfo.mapj.MapJ
 */
public class MapperServlet extends HttpServlet
{
	// TODO: Specify the physical path to the directory containing maps.
	// Or you can specify this value using an init parameter called 'mappath'.
	// Include a path separator at the end.
	private static String m_mapPath = "C:\\mapxtreme\\maps\\";

	// TODO: Specify the path & name of desired map definition to load.
	// Or you can specify this value using an init parameter called 'filetoload'.
	private static String m_fileToLoad = "c:\\data\\world.mdf";

	// TODO: Specify the URL of the MapXtremeServlet that will
	// service our mapping requests.
	// Or you can specify this value using an init parameter called 'mapxtremeurl'.
	private static String m_mxtURL =
		"http://localhost:8080/mapxtreme45/servlet/mapxtreme";

	// TODO (optional): Set m_debug to true if you want error messages to include
	// debugging information, or false otherwise.  Or you can set this variable
	// by setting a 'debug' init parameter to 'true'.
	private boolean m_debug = false;

	// TODO (optional): Set m_mapWidth & m_mapHeight to some initial value.
	// Or you can set this variable by setting 'mapwidth' and 'mapheight'.
	// NOTE: If you change the map dimensions, you may also want to change
	// the applet width and height settings, which are specified in the
	// HTML page that loads the applet (e.g. RunApplet.html). 
	// init parameters
	private int m_mapWidth = 500;
	private int m_mapHeight = 350;

	// Tools
	private final int NO_TOOL = 0;
	private final int ZOOM_IN_TOOL = 1;
	private final int ZOOM_OUT_TOOL = 2;
	private final int PAN_TOOL = 3;

	// Define constants to control various rendering options
	public static final int NUM_OF_COLORS = 256;
	public static final Color BACKGROUND_COLOR = Color.blue;

	/**
	* This method initializes the servlet and then reads and sets
	* initialization parameters
	*
	* @param config ServletConfig servlet initialization parameter
	*
	* @see com.mapinfo.mapj.MapJ
	*
	* @exception ServletException if detected when handling the request
	*/
	public void init(ServletConfig config)
	throws ServletException
	{
		super.init(config);

		// If the servlet set-up has provided initialization parameters,
		// use those parameters to override the hard-coded values
		// declared above.
		String strParam = getInitParameter("mappath");
		if (strParam != null) {
			m_mapPath = strParam;
		}

		strParam = getInitParameter("filetoload");
		if (strParam != null) {
			m_fileToLoad = strParam;
		}

		strParam = getInitParameter("mapxtremeurl");
		if (strParam != null  &&  strParam.length() > 0) {
			m_mxtURL = strParam;
		}

		strParam = getInitParameter("mapwidth");
		if (strParam != null) {
			m_mapWidth = Integer.valueOf(strParam).intValue();
		}

		strParam = getInitParameter("mapheight");
		if (strParam != null) {
			m_mapHeight = Integer.valueOf(strParam).intValue();
		}

		strParam = getInitParameter("debug");
		if (strParam != null  &&  strParam.equalsIgnoreCase("true") ) {
			m_debug = true;
		}
	}

	/**
	 *  service  -- handle both GET and POST requests.
	 *
	 * @param req HttpServletRequest that encapsulates the request to
	 * the servlet
	 * @param resp HttpServletResponse that encapsulates the response
	 * from the servlet
	 *
	 * @exception IOException if detected when handling the request
	 * @exception ServletException if the request could not be handled
	*/
	public void service (HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException
	{
		// Get the session object
		HttpSession session = req.getSession(true);
		if (req.getParameter("init") != null)
		{
			res.setContentType("text/html");
			PrintWriter out = new PrintWriter(res.getOutputStream());
			String thisServletName = HttpUtils.getRequestURL(req).toString();
			
			// Note: if using Servlet API 2.0, you must use the encodeUrl method.
			// For later APIs, use encodeURL instead.
			out.println(res.encodeURL(thisServletName));
			out.close();
		}
		else
		{
			if (m_debug)
			{
				debugSession(req, session);
			}
			// Draw the map and encode the URL
			try
			{
				renderMap(session, req, res);
			}
			catch (ServletException se)
			{
				log(se.getMessage());
				throw se;
			}
			catch (IOException ioe)
			{
				log(ioe.getMessage());
				throw ioe;
			}
			// only handle errors the map generation process caused
			catch (Exception e)
			{
				log(e.getMessage());
			}
		}
	}

	/**
	 *  This method returns an About string for this servlet
	 */
	public String getServletInfo()
	{
		return "A simple Map servlet";
	}

	/**
	 *  This establishes communications with the MapXtreme Java
	 *  servlet and then loads the map definition. A fully initialized MapJ
	 *  object is returned.
	 */
	public MapJ initMapJ()	throws Exception
	{
		// instantiate a MapJ and set the bounds
		MapJ myMap = new MapJ();    // this MapJ object
		myMap.setDeviceBounds(new DoubleRect(0, 0, m_mapWidth, m_mapHeight));

		// Query for image locations and load the geoset
		try
		{
			if (m_fileToLoad.endsWith(".gst"))
			{
				myMap.loadGeoset(m_fileToLoad, m_mapPath, null);
			}
			else {
				myMap.loadMapDefinition(m_fileToLoad); 
			}
		}
		catch(Exception e)
		{
			log("Can't load geoset: " + m_fileToLoad + "\n");
			throw e;
		}
		return myMap;
	}

	/**
		* This method sets previous state information, checks if any map
		* tools were used, resets the map extents if necessary, renders the map
		* and renders the map and then finally encodes the output HTML with a
		* link to the rendered gif file.
		*
		* @param session HttpSession session info for this client
		* @param req HttpServletRequest that encapsulates the request to
		* the servlet
		* @param resp HttpServletResponse that encapsulates the response
		* from the servlet
		*
		* @see javax.servlet.http.HttpSession
		* @see com.mapinfo.util , com.mapinfo.mapj.MapJ , com.mapinfo.util.graphics
		*/
	private void renderMap(HttpSession session,HttpServletRequest req,
				HttpServletResponse res)
	throws Exception
	{
		String reqParam;                   // to hold request parameter
		Double xStr = null;                // to hold x request params
		Double yStr = null;                // to hold y request params

		int tool = NO_TOOL;                // Zoom In, Out or Pan

		// Try to retrieve the user's previous MapJ object.
		MapJ myMap = (MapJ) session.getAttribute("mapinfo.mapj");
		if (myMap == null) {
			// This is probably the user's first time requesting a map.
			myMap = initMapJ();
		}

		// Check to see if which tool, if any, was set
		if ((reqParam = req.getParameter("tool"))!=null) {
			tool = Integer.valueOf(reqParam).intValue();
		}

		// Tool used, so transform map accordingly
		if (tool != NO_TOOL)
		{
			// Get the previous center point locations
			DoublePoint newpoint = myMap.getCenter();
			if ((reqParam = req.getParameter("ptx"))!=null) {
				xStr = new Double(reqParam);
			}
			if ((reqParam = req.getParameter("pty"))!=null) {
				yStr = new Double(reqParam);
			}
			if (xStr != null && yStr != null)
			{
				// Transform GIF coordinate to real world coordinate
				DoublePoint screenpoint = new DoublePoint(xStr.doubleValue(),
												  yStr.doubleValue());
				newpoint = myMap.transformScreenToNumeric(screenpoint);
			}

			double newZoom = myMap.getZoom();
			if (tool == ZOOM_IN_TOOL) {
				newZoom /= 2.0;
			}
			else if (tool == ZOOM_OUT_TOOL) {
				newZoom *= 2.0;
			}

			if (m_debug) {
				log("tool: " + tool + "  setting zoom to: " + newZoom + " at: " + newpoint);
			}

			// Reset the bounding rectangle, note - Pan handled by default
			myMap.setZoomAndCenter(newZoom, newpoint);
		} // End if tool used

		// Set up the renderer for this mapJ
		try 
		{
			MapXtremeImageRenderer rr = new MapXtremeImageRenderer(m_mxtURL);
			rr.render(ImageRequestComposer.create(
					myMap, NUM_OF_COLORS, BACKGROUND_COLOR, "image/gif"));

			//Output the map
			rr.toStream(res.getOutputStream());
		}
		catch(Exception e)
		{
			log(e.getMessage());
			throw e;
		}

		// Save state info for next time around
		session.setAttribute("mapinfo.mapj", myMap);
	}

	/**
	 * This method will output state information for this servlet client request
	 *
	 * @param req HttpServletRequest that encapsulates the request to
	 * the servlet
	 * @param resp HttpServletResponse that encapsulates the response
	 * from the servlet
	 */
	private void debugSession(HttpServletRequest req,
			HttpSession session)
	{
		log("Request and Session Data:");
		log("Session ID in Request: " + req.getRequestedSessionId());
		log("Session ID in Request from Cookie: " +
					req.isRequestedSessionIdFromCookie());
		
		// If using Servlet API 2.0, you must use the isRequestedSessionIdFromUrl 
		// method.	For later APIs, use isRequestedSessionIdFromURL instead. 
		log("Session ID in Request from URL: " +
					req.isRequestedSessionIdFromURL());
		log("Valid Session ID: " + req.isRequestedSessionIdValid());
		log("Session Data:");
		log("New Session: " + session.isNew());
		log("Session ID: " + session.getId());
		log("Creation Time: " + session.getCreationTime());
		log("Last Accessed Time: " + session.getLastAccessedTime());
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -