Skip to content

Instantly share code, notes, and snippets.

@osima
Created November 12, 2010 07:30
Show Gist options
  • Select an option

  • Save osima/673840 to your computer and use it in GitHub Desktop.

Select an option

Save osima/673840 to your computer and use it in GitHub Desktop.
自前のDefaultServlet(StaticResourceServlet)
//
// デフォルトサーブレット
//
import java.util.regex.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyStaticResourceServlet extends HttpServlet {
static String BR = System.getProperty('line.separator')
def regex_endswith_slash = { '^/(.*)/$' }
def path_endswith_slash = { "/view.gsp?id=${it.group(1)}/index" }
@Override
public void doPost( HttpServletRequest request, HttpServletResponse response){ doGet(request,response) }
@Override
public void doGet( HttpServletRequest request, HttpServletResponse response){
String spath = getPathInfo(request)
Matcher m = null
// chk only slash
m = Pattern.compile(regex_endswith_slash()).matcher(spath)
if( m.matches() ){
def f_spath = path_endswith_slash(m)
//println 'Called HTML --------------------------'
//println f_spath
request.getRequestDispatcher(f_spath).forward( request,response )
return
}
String rPath = getServletContext().getRealPath("/");
def file = new File( new File(rPath), spath.replaceAll('^/','') )
//println "----------- ${file.absolutePath}"
if( ['js','css'].find{ file.name.endsWith(it) } ){
if( file.name.endsWith('css') )
//response.contentType = 'text/css'
response.contentType = 'text/css;charset=UTF-8'
if( file.name.endsWith('js') ){
//response.contentType = 'application/x-javascript'
response.contentType = 'application/x-javascript;charset=UTF-8'
}
def w = response.getWriter()
file.newReader('UTF-8').each{ w << it << BR }
w.close()
return
}
else if( ['ico'].find{ file.name.endsWith(it) } ){
response.contentType = 'image/x-icon'
outputAsBinary( response,file )
return
}
else{
outputAsBinary( response,file )
return
}
}
private void outputAsBinary( def response , def file ){
def out = response.outputStream
def is = file.newInputStream()
while( true ){
def data = is.read()
if( data==-1 ){ break }
out.write( data )
}
is.close()
out.close()
}
static private String getPathInfo(HttpServletRequest request){
String spath=(String)request.getAttribute("javax.servlet.include.servlet_path");
if (spath == null) {
spath = ((HttpServletRequest) request).getServletPath();
if (spath == null || spath.length() == 0) {
// Servlet 2.1 puts the path of an extension-matched
// servlet in PathInfo.
spath = ((HttpServletRequest) request).getPathInfo();
}
}
return spath;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment