2013-12-08 52 views
1

我使用Eclipse Java EE,我有tomcat 7.xx服務器和一個Java Servlet。我需要在Java Servlet中指定爲首頁「WebContent/mypage.html」。Java Servlet:指定起始頁wih @WebServlet註釋

我該如何使用@WebServlet註釋做到這一點?

這是我的web.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
    version="2.4"> 

    <welcome-file-list> 
    <welcome-file>/ricerca.htm</welcome-file> 
    </welcome-file-list> 

    <display-name>Searcher</display-name> 
    <description> 
     Searcher! 
    </description> 

    <servlet> 
     <servlet-name>Searcher</servlet-name> 
     <servlet-class>org.irlab.Searcher</servlet-class> 
    </servlet> 

    <servlet-mapping> 
     <servlet-name>Searcher</servlet-name> 
     <url-pattern>/Searcher</url-pattern> 
    </servlet-mapping> 
</web-app> 

我CONTEX根是:/本地主機:8181/Searcher3/

確定一個解決方案是這樣的:@WebServlet(URL模式= { 「/搜索器」 })在我寫的doGet方法中的dnd: request.getRequestDispatcher(「ricerca.htm」)。forward(request,response);

但是爲什麼web.xml不起作用?我需要添加一些Eclipse項目配置?

+0

您的web.xml無法正常工作,因爲它的格式不正確。看到一些模板[here](http://dominikdorn.com/2010/03/web-xml-web-fragment-xml-2-3-2-4-2-5-3-0/)。不要用自定義的'@ WebServlet'重新發明輪子。使用已經存在的實用程序。 –

+0

我已更新web.xml,但它仍然無法正常工作。 – Neptune

+0

請編輯您的問題並附上您所做的更新。 –

回答

4

我該如何使用@WebServlet註釋做到這一點?

index.html是默認歡迎頁面之一。您可以使用@WebServlet註釋將Servlet作爲歡迎頁面調用。您需要將您的Servlet urlPatterns映射爲/index.html。相比於doGet(..)方法,您可以使用RequestDispatcher.forward(..)轉發至mypage.html

@WebServlet(urlPatterns = {"/index.html"}) 
public class IndexServlet extends HttpServlet { 

    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 

     throws ServletException, IOException { 
     // forward to mypage.html 
     request.getRequestDispatcher("mypage.html").forward(request,response); 
    } 
} 
+0

@Neptune,對於Java EE 6,web.xml是可選的。你不需要web.xml。 – Masudul

+0

很好,這個工程。但是爲什麼我不能直接在urlPatterns中放置「mypage.tm」? – Neptune

+0

@Neptune,你可以做到這一點,比你的URL應該:'http:// localhost:8080/AppName/mypage.html'。如果像'index.html'這樣映射而不是'http:// localhost:8080/AppName /'就足夠了。 – Masudul

0

對此,您不需要自定義Servlet。只需添加

<welcome-file-list> 
    <welcome-file>mypage.html</welcome-file> 
</welcome-file-list> 

元素到您的web.xmlThis is documented here

+1

我已經做到了這一點,但不工作。我已經將Web.xml添加到WebContent/WEB-INF文件夾中,然後運行Eclipse項目但不起作用。 – Neptune

+0

@海王星你的意思是不工作?你有404嗎?應用程序不啓動?你有什麼要求,你會期望工作? –

+0

是的,我得到一個「HTTP狀態404」,不加載HTML頁面。 – Neptune