<form action=“/sampleServlet” giving me excepti

2019-01-03 03:14发布

In my jsp if I call <form action="/sampleServlet" method="get" name="form1">, I get the following exception :

http 404 error--sampleServlet is not found.I set sampleServlet in web.xml file and url-pattern also set to /sampleServlet.

Why I am getting 404 (not found servlet.)?

3条回答
Bombasti
2楼-- · 2019-01-03 03:49

When you are using URL in HTML, without leading / they are relative to the current URL (ie current page displayed). With leading / they are relative to the website root :

<form action="/context-path/sampleServlet">

or

<form action="sampleServlet">

will do what you want.

I suggest you to add the context inside the action path dynamically. Example (in JSP) :

<form action="${pageContext.request.contextPath}/sampleServlet">

With this you will never have to change the path, for example, if you move your file or copy your code, or rename your context!

查看更多
唯我独甜
3楼-- · 2019-01-03 03:53

might help you

servlet configuration

<servlet>
    <servlet-name>sampleServlet</servlet-name>
    <servlet-class>test.sampleServlet</servlet-class>
  </servlet>
<servlet-mapping>
    <servlet-name>sampleServlet</servlet-name>
    <url-pattern>/sampleServlet/</url-pattern>
  </servlet-mapping>

Servlet Code :

package test;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class sampleServlet extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException{
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello Servlet Get</h1>");
        out.println("</body>");
        out.println("</html>"); 
    }
}

JSP code :

<html>
  <body>
     <form action="/sampleServlet/" method="GET">
      <input type="submit" value="Submit form "/>
     </form>
  </body>
</html>

you can click on submit button and after you can see servlet out put

查看更多
The star\"
4楼-- · 2019-01-03 03:54

Just use action="sampleServlet"

It will work for you.

查看更多
登录 后发表回答