Set servlet as default home page in web.xml [duplicate]

痴心易碎 提交于 2021-02-07 18:20:05

问题


I've a servlet registered in web.xml as below.

<servlet>
    <servlet-name>Manager</servlet-name>
    <servlet-class>Manager</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Manager</servlet-name>
    <url-pattern>/RequestManager</url-pattern>
</servlet-mapping>

Basically I want to call this servlet as my default home page when I open http://localhost:8080/appname. So, I tried registering it as welcome file in same web.xml as below:

<welcome-file-list>
    <welcome-file>Manager</welcome-file>
</welcome-file-list>

But, when I run the project, I get an error saying "requested resource not available". However, if I write in the url with my servlet URL pattern, it works fine.


回答1:


Specify an empty string as servlet's URL pattern.

<servlet>
    <servlet-name>Manager</servlet-name>
    <servlet-class>Manager</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Manager</servlet-name>
    <url-pattern></url-pattern>
</servlet-mapping>

See also:

  • Difference between / and /* in servlet mapping url pattern

Unrelated to the concrete problem, the <welcome-file> should represent an URL path, not a servlet name. It'd have worked if you specifed <welcome-file>RequestManager</welcome-file>. But this affects all subfolders. Actually, the <welcome-file> has an entirely different meaning than "home page file" you've had in mind. It represents the default resource which should be served when a folder is been requested.




回答2:


You can use index.jsp to forward to your servlet.

<jsp:forward page="servlet_context">

and add index.jsp as welcome file in web.xml




回答3:


inside servlet class you can forward Control Using :

request.getRequestDispatcher("forward page URL").forward(req,res);

or else if you are using JSP then use

<% RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response); %>

or

<jsp:forward page="relative URL" />


来源:https://stackoverflow.com/questions/32020447/set-servlet-as-default-home-page-in-web-xml

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