将4个servlet放在一个项目中

时间:2017-03-06 12:59:41

标签: java servlets

我不知道如何在一个项目中放置许多servlet。我应该为每个人创建单独的web.xml文件吗?我有4个名为index.html,index1.html,index2.html和index3.html的html文件 先谢谢

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     

 xmlns="http://java.sun.com/xml/ns/javaee"    
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee         
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"    
  version="3.0">
 <display-name>WM2_as03</display-name>


 <servlet>
<servlet-name>form</servlet-name>
<servlet-class>com.ccc.Task3</servlet-class>

 </servlet>
<servlet-mapping>
<servlet-name>form</servlet-name>
<url-pattern>/register</url-pattern>
 </servlet-mapping>

 <servlet>
 <servlet-name>newtask</servlet-name>
 <servlet-class>com.ccc.Task3</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>newtask</servlet-name>
<url-pattern>/taskkk</url-pattern>
</servlet-mapping>

<welcome-file-list>
  <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
     <welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
    </web-app>

2 个答案:

答案 0 :(得分:1)

创建1个web.xml文件并添加多个servlet:

<servlet>
  <servlet-name>Servlet1</servlet-name>
  <servlet-class>path_to.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Servlet1</servlet-name>
  <url-pattern>/s1</url-pattern>
</servlet-mapping>
 <servlet>
  <servlet-name>Servlet2</servlet-name>
  <servlet-class>path_to.Servlet2</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Servlet2</servlet-name>
  <url-pattern>/s2</url-pattern>
</servlet-mapping>

答案 1 :(得分:0)

改为使用web.xml

<servlet>
  <servlet-name>servletName</servlet-name>
  <servlet-class>packageName.servletName</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>servletName</servlet-name>
  <url-pattern>/yourServletUrl</url-pattern>
</servlet-mapping>

您可以使用自servlet 3.0以来的注释。

import javax.servlet.annotation.WebServlet;

@WebServlet(name = "servletName", urlPatterns = { "/yourServletUrl" })
public class servletName extends HttpServlet {

它更容易,更易读。