Building a simple picture server with Tomcat

Posted by smokenwhispers on Tue, 11 Feb 2020 18:36:00 +0100

Prerequisite

  • Tomcat 7.0.90

Method 1: modify the configuration file

Add a sub label in < host > in the TOMCAT_HOME/conf/server.xml configuration file:

<Context docBase="C:\exambase\" path="/img"/>

Method 2: add Servlet

Create a new application, add the following Servlet, deploy the application and start Tomcat.

package com.lun.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

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


@WebServlet(name = "imgservlet", urlPatterns = { "/imgservlet/*" })
public class ImgServlet extends HttpServlet {
 
	private static final long serialVersionUID = -3351976768417931566L;

	private static final String IMG_PATH = "C:/exambase";
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
 
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String pathInfo = request.getPathInfo();
		try{
	 
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(String.format("%s%s", IMG_PATH, pathInfo)));
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			try {
				byte[] content = new byte[in.available()];
				in.read(content);
		 
				response.setContentType("image/png,image/jpeg,image/gif,image/bmp");
				out.write(content);
			}finally {
				in.close();
				out.close();
			}
		}catch(FileNotFoundException ex) {
			throw new IOException(String.format("%s Not Found.", pathInfo));
		}catch(Exception ex) {
			throw ex;			
		}
	}
}

Solve the problem of garbled code when the path contains Chinese

This test uses Tomcat/7.0.90. The character set of the default decoding URL is ISO-8859-1, and the URL sent by the browser is encoded with UTF-8. If the URL contains Chinese, garbled code will occur naturally.

Solution: in the Tomcat? Home / conf / server.xml configuration file

<Connector connectionTimeout="20000" port="8080"
	 protocol="HTTP/1.1" redirectPort="8443" />

Add a property urencoding = "UTF-8".

Reference material

  1. tomcat as a picture server
  2. Display pictures with Servlet
  3. Java Servlet @WebServlet Annotation Example
  4. Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?
  5. On the Web project built by Tomcat, the analysis of the problem of URL s in Chinese

Topics: Programming Tomcat Java xml