猿问

<form action =“ / sampleServlet”给了我例外

在我的jsp中,如果我调用<form action="/sampleServlet" method="get" name="form1">,则会收到以下异常:


http 404错误-找不到sampleServlet。我在web.xml文件中设置了sampleServlet,并且url-pattern也设置为/ sampleServlet。


为什么我得到404(找不到servlet)?


肥皂起泡泡
浏览 613回答 3
3回答

米脂

当您使用HTML中的URL时,不带前导/,它们是相对于当前URL(即显示的当前页面)的。以/开头是相对于网站根目录的:<form action="/context-path/sampleServlet">要么<form action="sampleServlet">会做你想要的。我建议您在操作路径中动态添加上下文。示例(在JSP中):<form action="${pageContext.request.contextPath}/sampleServlet">有了它,您将无需更改路径,例如,如果您移动文件或复制代码,或重命名上下文!

喵喵时光机

可能会帮助你servlet配置<servlet>&nbsp; &nbsp; <servlet-name>sampleServlet</servlet-name>&nbsp; &nbsp; <servlet-class>test.sampleServlet</servlet-class>&nbsp; </servlet><servlet-mapping>&nbsp; &nbsp; <servlet-name>sampleServlet</servlet-name>&nbsp; &nbsp; <url-pattern>/sampleServlet/</url-pattern>&nbsp; </servlet-mapping>Servlet代码: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{&nbsp; &nbsp; public void doGet(HttpServletRequest request, HttpServletResponse response)&nbsp; &nbsp; throws IOException{&nbsp; &nbsp; &nbsp; &nbsp; PrintWriter out = response.getWriter();&nbsp; &nbsp; &nbsp; &nbsp; out.println("<html>");&nbsp; &nbsp; &nbsp; &nbsp; out.println("<body>");&nbsp; &nbsp; &nbsp; &nbsp; out.println("<h1>Hello Servlet Get</h1>");&nbsp; &nbsp; &nbsp; &nbsp; out.println("</body>");&nbsp; &nbsp; &nbsp; &nbsp; out.println("</html>");&nbsp;&nbsp; &nbsp; }}JSP代码:<html>&nbsp; <body>&nbsp; &nbsp; &nbsp;<form action="/sampleServlet/" method="GET">&nbsp; &nbsp; &nbsp; <input type="submit" value="Submit form "/>&nbsp; &nbsp; &nbsp;</form>&nbsp; </body></html>您可以单击提交按钮,然后您可以看到servlet输出

不负相思意

只需使用action =“ sampleServlet”它将为您工作。
随时随地看视频慕课网APP

相关分类

Java
我要回答