2013-08-23 50 views
2

我創建了名爲MainContent的servlet。我有這樣的映射用「/」創建servlet url-pattern

<servlet> 
    <display-name>MainContent</display-name> 
    <servlet-name>MainContent</servlet-name> 
    <servlet-class>ge.test.servlet.MainContent</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>MainContent</servlet-name> 
    <url-pattern>/main</url-pattern> 
</servlet-mapping> 

所以,當我去的鏈接: //本地主機:8080/MyAppl /主我進入的servlet doGet()方法。然後我創建RequestDispatcher到index.jsp。

一切正常!

RequestDispatcher rd = context.getRequestDispatcher("/index.jsp?language="+ lang); 
rd.forward(request, response); 

一切正常!

問:

現在我需要改變的url-pattern。我需要類似的東西 - :當我進入本地主機:8080/MyAppl/我需要重定向到我的servlet。 所以我創造這樣的事情:

<url-pattern>/</url-pattern>

OK,它的作品!我被重定向到servlet。 但是這裏發生了一些錯誤。當Servlet向前創建RequestDispatcher時,我的index.jsp中沒有圖像和css。 當我在螢火蟲控制檯中看到的,我見過的錯誤:

Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8080/MyApp/font/font_big.css". localhost/:15 
Resource interpreted as Image but transferred with MIME type text/html: "http://localhost:8080/MyApp/IMG/company.gif". 

我怎樣才能解決呢?

+0

您所遇到的問題是,所有的資源路徑的開始/。你需要添加一些東西來處理資源(spring有一個資源servlet),並使用通用的URL模式來標識資源(例如,所有資源都以「/ Resourcde」開頭),然後在「 /「映射在您的web.xml文件 – DwB

+0

這演示了春天的解決方案:http://stackoverflow.com/questions/6047150/using-spring-resourceservlet-to-serve-multiple-resources-simultaneously – DwB

+0

我不使用春天。我只使用servlet和JSP。你能舉個例子嗎,怎麼做? – grep

回答

2

是的,像@DwB指出的那樣,'/'上下文是有問題的URL模式,它會導致你的問題。

使用

<servlet-mapping> 
    <servlet-name>MainServlet</servlet-name> 
    <url-pattern></url-pattern> 
</servlet-mapping> 

代替。這是「servlet 3.0的方式」來做到這一點。

來源

[1] http://www.coderanch.com/t/366340/Servlets/java/servlet-mapping-url-pattern

[2] How can I map a "root" Servlet so that other scripts are still runnable?

+0

因此,使用空作爲特殊的url模式。 – mico

+0

是的!這樣可行! – grep