Sun, May 4, 2008
リクエストされたパスの取得方法(Java Servlet)
markdownのようないわゆるライトウェイトなマークアップ言語を使って ServletにランタイムにテキストからHTMLに変換してやれば、管理が楽になるのではないか... と思い実現方法を調査中...
Step1 リクエストされたパスを把握する
テキストファイルは、サーブレットアプリケーションのホームディレクトリ?以下の
任意の場所に配置できるようにしたい。
したがって、サーブレット側で、リクエストされたパスをまずは把握する必要がある。
JavaServletでリクエストされたパスを取得するには、
以下のメソッドを使う。
(これは、jythonのパッケージに入っていたコードを参考にしています。)
private String getRealPath(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();
}
}
String rpath=getServletContext().getRealPath(spath);
return rpath;
}
ソースコード
このコードを使って、
リクエストされたパス情報を表示するサーブレットを作成した。
対象とするファイル拡張子は htmlとする(web.xmlに記述)。
TestServlet.java
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet{
private String getRealPath(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();
}
}
String rpath=getServletContext().getRealPath(spath);
return rpath;
}
public void doPost(
HttpServletRequest request,
HttpServletResponse response){
doGet(request,response);
}
public void doGet(
HttpServletRequest request,
HttpServletResponse response){
response.setContentType("text/html");
try{
PrintWriter pw=response.getWriter();
pw.println("<html>");
pw.println("<body>");
pw.println(getRealPath(request));
pw.println("</body>");
pw.println("</html>");
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>TestServelt</servlet-name>
<servlet-class>test.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServelt</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>