问题:当我直接在浏览器中调用url(url-mapping)时它工作得很好但是当我使用post
方法从jsp文件调用servlet时,它不起作用但是会出错:
输入状态报告
消息/ Hello World / servlet
描述源服务器未找到目标资源的当前表示,或者不愿意透露存在该目标资源。
Jsp页面:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<form method="post" action="myservlet">
<input type="submit" value ="send">
</form>
</body>
</html>
Veb.hml:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>helloworld2</display-name>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>apress.helloworld.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Servlet代码:
package apress.helloworld;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
//System.out.println("Get Method Called");
try { response.setContentType("text/html");
`enter code here` PrintWriter printwriter = response.getWriter();
printwriter.println("<h2>");
printwriter.println("Hello World");
printwriter.println("</h2>");
}
catch
(IOException ex)
{ ex.printStackTrace(); }
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
try { resp.setContentType("text/html");
PrintWriter printwriter = resp.getWriter();
printwriter.println("<h2>");
printwriter.println("Hello World");
printwriter.println("</h2>");
}
catch
(IOException ex)
{ ex.printStackTrace(); }
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<form method="post" action="hello">
<input type="submit" value ="send">
</form>
</body>
</html>
在HTML表单中使用上面的代码action =“url-mapping”你必须提到servlet的url模式而不是servlet名称请参考你的web.xml