新建一个Servlet 继承自 DefaultServlet ,
//DefaultServlet 来自于 catalina.jar, 可以在 tomcat 的 lib里找到
//DefaultServlet 来自于 catalina.jar, 可以在 tomcat 的 lib里找到
public class MyCharacterEncodingServlet extends DefaultServlet { /** * Return the relative path associated with this servlet. * * @param request The servlet request we are processing */ protected String getRelativePath(HttpServletRequest request) { // IMPORTANT: DefaultServlet can be mapped to ‘/’ or ‘/path/*’ but always // serves resources from the web app root with context rooted paths. // i.e. it can not be used to mount the web app root under a sub-path // This method must construct a complete context rooted path, although // subclasses can change this behaviour. // Are we being processed by a RequestDispatcher.include()? if (request.getAttribute(Globals.INCLUDE_REQUEST_URI_ATTR) != null) { String result = (String) request.getAttribute( Globals.INCLUDE_PATH_INFO_ATTR); if (result == null) { result = (String) request.getAttribute( Globals.INCLUDE_SERVLET_PATH_ATTR); } else { result = (String) request.getAttribute( Globals.INCLUDE_SERVLET_PATH_ATTR) + result; } if ((result == null) || (result.equals(""))) { result = "/"; } return (result); } // No, extract the desired path directly from the request String result = request.getPathInfo(); if (result == null) { result = request.getServletPath(); } else { result = request.getServletPath() + result; } if ((result == null) || (result.equals(""))) { result = "/"; } try{ result = new String(result.getBytes("ISO-8859-1″), "UTF-8″); } catch (Exception e) { // TODO: handle exception } return (result); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub super.doGet(request, response); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } }
然后在web.xml 中加入
(灰色部分路径以具体项目和需求为准)
<servlet> <servlet-name>chnURIServlet</servlet-name> <servlet-class>com.gzy.zjer.core.web.MyCharacterEncodingServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>chnURIServlet</servlet-name> <url-pattern>/UserFiles/*</url-pattern> </servlet-mapping>
发表于 20/11/2012 , 06:58 于分类 Java.