见过很多类似的问题,但没有找到解决方案。
问题:浏览器显示 servlet 的代码,而不是执行此 servlet。
这是index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<a href="servlets/LoginServlet.java"> Link </a>
</body>
</html>
这是LoginServlet
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World");
out.flush();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
如果有任何帮助,我将不胜感激。
最佳答案
<a href="servlets/LoginServlet**.java**"> Link </a>
:P
您已在 web.xml 中映射/LoginServlet,但指向 a 链接中的源代码。
将您的链接映射到正确的 URL,即您在 web.xml 中的 URL:
<url-pattern>/LoginServlet</url-pattern>
所以链接必须是:
<a href="/LoginServlet" >Link </a>
因此,最终的 URL 将类似于:
http://localhost:8080/LoginServlet
关于java - 浏览器显示来自 Servlet 的 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24564684/