无法将一个servlet称为另一个servlet

时间:2013-12-24 06:47:28

标签: java servlets

Servlet1:

public void doPost(HttpServletRequest request, HttpServletResponse response){  
    try{  

    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  

    String n=request.getParameter("userName");  
    out.print("Welcome "+n);  

    Cookie ck=new Cookie("uname",n);//creating cookie object  
    response.addCookie(ck);//adding cookie in the response  

    //creating submit button  
    out.print("<form action='servlet2'>");  
    out.print("<input type='submit' value='go'>");  
    out.print("</form>");  

    out.close();  

        }catch(Exception e){System.out.println(e);}  
  }  

Servlet2:

public void doPost(HttpServletRequest request, HttpServletResponse response){  
    try{  

    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  

    Cookie ck[]=request.getCookies();  
    out.print("Hello "+ck[0].getValue());  

    out.close();  

         }catch(Exception e){System.out.println(e);}  
    }  

的web.xml:

<servlet>  
<servlet-name>s1</servlet-name>  
<servlet-class>FirstServlet</servlet-class>  
</servlet>  

<servlet-mapping>  
<servlet-name>s1</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>  

<servlet>  
<servlet-name>s2</servlet-name>  
<servlet-class>SecondServlet</servlet-class>  
</servlet>  

<servlet-mapping>  
<servlet-name>s2</servlet-name>  
<url-pattern>/servlet2</url-pattern>  
</servlet-mapping> 


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

    </welcome-file-list>
</web-app>

我无法从servlet1调用另一个servlet2我不知道在sservlet2中哪里出错了我们必须在servlet 1的代码中给出名称类或URL模式plz检查。我无法调用servlet 2按钮点击servlet1请帮帮我

1 个答案:

答案 0 :(得分:2)

你还没有在这里写过表格方法

out.print("<form action='servlet2'>");  
    out.print("<input type='submit' value='go'>");  
    out.print("</form>"); 

所以默认情况下它是get。所以你需要调用第二个servlet的doGet()或者像post一样编写表单方法out.print("<form action='servlet2' method='post'>");