📄 htmlembeddedmapservlet.java
字号:
*
* @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
{
// Initialize a toolkit object, which will help us construct various HTML
// elements that make up a map page.
MapToolkit toolkit = new MapToolkit(new ServletFieldReader(req),
req.getLocale());
// Build a hashtable representing the type of request submitted
// (values of form fields, if any)
Hashtable ht = getFormFieldsHT(req, toolkit);
// See what type of request we received -- a request for a map
// image, or a request for an HTML page containing a map,
// or a request for a Layer Control page...
String strRequestType = (String)ht.get(FF_REQUEST_TYPE);
try {
if (strRequestType != null && strRequestType.equalsIgnoreCase("IMG")) {
// This servlet request was a request for a map image.
// Stream an image directly down to the client.
sendImageResponse(res, req);
}
else {
// This request is a request for an HTML page.
sendHTMLResponse(res, req, ht, toolkit, strRequestType);
}
}
catch (ServletException se) {
throw se;
}
catch (IOException ie) {
throw ie;
}
}
// Send an HTML page down to the browser.
private void sendHTMLResponse(HttpServletResponse res, HttpServletRequest req,
Hashtable ht, MapToolkit toolkit, String strRequestType)
throws ServletException, IOException
{
// this line is only necessary for the Netscape browser, so that all of
// the necessary response headers are set - for IE, all that is required
// is the setLocale() call below...
res.setContentType("text/html");
// Set the Locale of the response to that of the request. This will also
// set the charset of the response - especially important for double-byte
// languages.
// setLocale是Servlet2.2为实现国际化提供的新方法,它允许返回一个java.util.Locale对象,
// 给出客户的首选国家,或者设定应答国家。可以对content-language HTTP头自动设置相应的值
res.setLocale(req.getLocale());
HttpSession session = req.getSession(true);
// Initialize a string used to report error conditions
if (m_bDebug) {
m_debugMessage = getSessionInfo(req, session);
}
// Internationally friendly stream printer
PrintWriter out = res.getWriter();
// If it was not specified explicitly, determine the URL used to request
// this servlet, so we can re-use the same URL when we build the form.
if (m_thisServletURL == null) {
m_thisServletURL = req.getRequestURI();
// Make sure there are no ? arguments appended to the end of the URL
// (or ; characters either, which can happen after a session timeout).
int startArgs;
String[] badCharacters = {"?", ";"};
for (int i = 0; i < badCharacters.length; i++) {
startArgs = m_thisServletURL.indexOf(badCharacters[i]);
if (startArgs >= 0) {
// Remove the portion of the string, starting with
// the undesired character.
m_thisServletURL = m_thisServletURL.substring(0, startArgs);
}
}
}
// Verify that the root of the image URL ends with "/"
// (unless URL is blank):
if (m_mapImageURL != null &&
!m_mapImageURL.equals("") && !m_mapImageURL.endsWith("/")) {
m_mapImageURL = m_mapImageURL + "/";
}
// See what type of submit button the user clicked on to get here,
// such as: did they click "Apply" to come back from Layer Control page?
String strSubmitButton = (String)ht.get(HT_SUBMIT_BUTTON);
// Create a MapJ object.
MapJ myMap = null;
try {
// Try to retrieve the user's previous MapJ object.
myMap = (MapJ) session.getAttribute(MAPJ_ATTR);
if (myMap == null) {
myMap = initMapJ();
// Now test to see whether the user submitted the map page.
// If the session object did NOT contain a MapJ object, but the
// user DID submit the map page or the layer settings page, it
// means that the user acted after the session expired.
Double dZoom = (Double)ht.get(FF_OLD_ZOOM);
if (dZoom != null) {
// Although the user session had no previous MapJ object, the GET
// or POST request did contain a zoom form field (or, if the user
// clicked a link, a zoom parameter in the query string), indicating
// the user submitted the page after a previous session expired.
// You can ignore the session expiration, or you may want to
// redirect the user to an error page. For example, you could do:
//
// out.println(getErrorPage("Your previous session expired."));
// out.close();
// return;
//
// Or, if you want to automatically return the user to the same
// center position, zoom level, and map size that they were using
// before the session expired, make the following call:
applyHiddenFormFields(myMap, ht, session);
}
}
} catch (Exception e) {
}
// Determine the desired map size setting.
Boolean bSize = (Boolean)session.getAttribute("mapinfo.mapsize");
boolean bSmallMap; // true indicates we should display a small map.
if (bSize != null) {
// There was a setting, so use it.
bSmallMap = bSize.booleanValue();
} else {
// There was no setting; default to a small map.
bSmallMap = true;
}
// Now that we know what the previous map size setting was,
// see whether the user clicked on the link to toggle the map size.
if (strRequestType != null && strRequestType.equalsIgnoreCase("TS")) {
// Toggle the map Size.
bSmallMap = !bSmallMap;
setMapSize(myMap, bSmallMap);
}
session.setAttribute("mapinfo.mapsize", new Boolean(bSmallMap));
try {
if (strRequestType != null && strRequestType.equalsIgnoreCase("LS")) {
// The user clicked on the link to bring up the Layer Settings page.
out.println(getLayerSettingsPage(myMap, toolkit, session, res));
}
else {
// The user submitted a request for a map page.
// But before we generate the map page, see whether there are
// any changes that we need to apply to the map (e.g. if the
// user made changes on the Layer Control page, we should
// apply those changes now).
// Did the user click the Apply button from the Layer Settings page?
if (strSubmitButton != null) {
if (strSubmitButton.equals(FF_LS_APPLY)) {
// User clicked Apply on Layer Settings page; apply changes.
toolkit.applyLayerSettings(myMap);
}
// TODO: If you add your own submit buttons to the page,
// add an else if block to test for whether the user pressed
// your new button, and respond accordingly.
}
// If no errors have occurred, make any necessary adjustments (if any)
// to the map's zoom width and/or center point.
panAndZoomMap(myMap, ht, session);
// If m_bGenerateImageFile is true, create a new map image
// on the server, which the browser will download through a
// conventional URL (an URL to a static file).
if (m_bGenerateImageFile) {
renderMap(myMap, session);
}
// Generate a new page that will display the new map image
out.println(getMapPage(myMap, bSmallMap, toolkit, session, res));
}
// Save the MapJ object for the user's next request
session.setAttribute(MAPJ_ATTR, myMap);
// TODO: If you want to enhance the servlet by adding more HTML
// form fields, and if you want the servlet to "remember" the state
// of those form fields, you may need to add calls to session.putValue.
}
catch (FileNotFoundException e) {
// If the MapJ-related code failed because it could not find a file,
// output an error page.
out.println(getErrorPage( toolkit.getString("app.error_occurred",
"Error occurred while accessing Map Server:") + "<P>" + e.toString()));
// For servlet API 2.1 and later, you can use:
// log(e.toString(), e);
e.printStackTrace();
}
catch (ServletException se) {
out.close();
throw se;
}
catch (IOException ie) {
out.close();
throw ie;
}
catch (Exception e) {
// Handle any MapJ-related exceptions that resulted from
// a call to one of our methods (e.g. renderMap, panAndZoomMap).
out.println(getErrorPage( toolkit.getString("app.error_occurred",
"Error occurred while accessing Map Server:") + "<P>" + e.toString()));
// For servlet API 2.1 and later, you can use:
// log(e.toString(), e);
e.printStackTrace();
}
out.close();
}
// Stream an image of the MapJ map down to the browser.
private void sendImageResponse(
HttpServletResponse res, HttpServletRequest req) {
HttpSession session = req.getSession(true);
MapJ myMap = null;
try {
// Try to retrieve the user's previous MapJ object.
myMap = (MapJ) session.getAttribute(MAPJ_ATTR);
if (myMap == null) {
myMap = initMapJ();
}
} catch (Exception e) {
}
// Set the content type (e.g. to "image/gif")
String sMIME = getMIMEType();
res.setContentType(sMIME);
ServletOutputStream sos = null;
try {
sos = res.getOutputStream();
MapXtremeImageRenderer rr = new MapXtremeImageRenderer(m_mxtURL);
rr.render(
ImageRequestComposer.create(myMap, NUM_OF_COLORS, BACKGROUND_COLOR, sMIME));
rr.toStream(sos);
}
catch (Exception e) {
// For servlet API 2.1 and later, you can use: log(e.toString(), e);
e.printStackTrace();
}
try {
if (sos != null) {
sos.close();
}
} catch (Exception e) {
}
}
// return a string representing the MIME type for the selected image format;
// used when we call setContentType().
private String getMIMEType() {
switch (m_imageFormat) {
case IMAGE_FORMAT_JPG:
return "image/jpeg";
case IMAGE_FORMAT_PNG:
return "image/png";
case IMAGE_FORMAT_BMP:
return "image/bmp";
default:
return "image/gif";
}
}
// This method returns an About string for this servlet
public String getServletInfo() {
return "A simple mapping servlet";
}
// Instantiate a MapJ object and load a map (if a map file was specified).
public MapJ initMapJ() throws Exception {
// instantiate a MapJ
MapJ myMap = new MapJ();
if (m_jdbcContainer != null) {
// A JDBCMapDefContainer was specified; use it to load the map definition.
myMap.loadMapDefinition(m_jdbcContainer, m_mapName);
}
else {
// Try initializing the map from a file on the local filesystem
// (but only if one was specified; note that you could start out
// with no map definition, and then add layers one by one).
if (m_fileToLoad != null) {
File f = new File(m_fileToLoad);
if (f.exists() && m_mapPath == null) {
// No maps directory was specified; assume that map files
// are in the same directory as the .gst or .mdf file.
m_mapPath = f.getParent();
}
if (m_fileToLoad.endsWith(".gst")) {
// Load a geoset (.gst file) from the local filesystem.
myMap.loadGeoset(m_fileToLoad, m_mapPath, null);
}
else {
// Load an XML-based map definition from the local filesystem.
myMap.loadMapDefinition(m_fileToLoad);
}
}
}
// Set the device bounds to control the size of the image we output.
// Specify true for the smallSize argument, so that the map starts out
// at a small size, by default.
setMapSize(myMap, true);
return myMap;
}
// Set the dimensions of the map object, to either the
// "large" or "small" map size specified in constants, above.
private void setMapSize(MapJ myMap, boolean bSmallSize) {
if (bSmallSize) {
myMap.setDeviceBounds(
new DoubleRect(0, 0, MAP_WIDTH_SMALL, MAP_HEIGHT_SMALL));
}
else {
myMap.setDeviceBounds(
new DoubleRect(0, 0, MAP_WIDTH_LARGE, MAP_HEIGHT_LARGE));
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -