用Tomcat构建一个简单图片服务器

编程

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

方法二:添加Servlet

新建一应用,然后添加如下的Servlet,然后部署应用并启动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;

}

}

}

解决路径含中文时出现乱码问题

本次测试使用的是Tomcat/7.0.90,默认解码URL的字符集是ISO-8859-1,而浏览器发出URL是用UTF-8编码。若URL含中文,乱码现象自然而然会发生。

解决之道:在TOMCAT_HOME/conf/server.xml配置文件内的

<Connector connectionTimeout="20000" port="8080"

protocol="HTTP/1.1" redirectPort="8443" />

添加一属性URIEncoding="UTF-8"

参考资料

  1. tomcat服务器" title="图片服务器">图片服务器
  2. 使用Servlet显示图片
  3. Java Servlet @WebServlet Annotation Example
  4. Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?
  5. 关于使用Tomcat搭建的Web项目,出现 URL 中文乱码的问题解析

以上是 用Tomcat构建一个简单图片服务器 的全部内容, 来源链接: utcz.com/z/513383.html

回到顶部