java - 浏览器显示来自 Servlet 的 HTML 代码

标签 java jsp servlets

见过很多类似的问题,但没有找到解决方案。

问题:浏览器显示 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/

相关文章:

java - Struts2 在 JSP 中从 session 映射迭代

java - JPA。如何子类化现有实体并保留其 ID?

java - JSP - 身份验证和授权

java - 更新 jSTL 1.2 中捆绑的 taglib 标准版本

javascript - 输入框日期选择器不适用于 jQuery DataTables 的所有页面

servlets - CQ 中的 Sling Servlet - 资源不可修改

java - 重定向来自过滤器的响应会抛出 IllegalStateException

java - Tomcat Servlet 和 MySQL

java - 找不到约束 'javax.validation.constraints.Size' 的 validator

java - 如何拆分字符串序列并将每个元素转换为 double