Java Servlet: Specify start page wih @WebServlet annotation

耗尽温柔 提交于 2021-02-10 05:06:54

问题


I work with Eclipse Java EE, I have tomcat 7.xx server and a Java Servlet. I need to specify in the Java Servlet as startpage "WebContent/mypage.html".

How can I do that with the @WebServlet annotation?

This is my 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> 

My contex root is: /localhost:8181/Searcher3/

Ok one solution is this: @WebServlet(urlPatterns = {"/Searcher"}) dnd in the doGet method i write: request.getRequestDispatcher("ricerca.htm").forward(request,response);

But why web.xml don't work? i need to add something to the Eclipse Project configuration?


回答1:


How can I do that with the @WebServlet annotation ?

index.html is one of the default welcome page. You can call Servlet as welcome-page using @WebServlet annotation. You need to mapped your Servlet urlPatterns as /index.html. Than at doGet(..) method you can forward to mypage.html using RequestDispatcher.forward(..).

 @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);
    }
 }



回答2:


You don't need a custom Servlet for that. Just add

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

element to your web.xml. This is documented here.



来源:https://stackoverflow.com/questions/20455442/java-servlet-specify-start-page-wih-webservlet-annotation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!