簡體   English   中英

使用Tomcat服務器8.5在Intellij Community Edition中運行servlet應用程序時出現問題

[英]Trouble running servlet application in Intellij Community Edition with tomcat server 8.5

// 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>welcome</servlet-name>
            <servlet-class>com.rippleworks.WelcomeServlet</servlet-class>
        </servlet>

        <servlet-mapping>
            <servlet-name>welcome</servlet-name>
            <url-pattern>/welcome</url-pattern>
        </servlet-mapping>
    </web-app>

// WelcomeServlet.java

package com.rippleworks;

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.PrintStream;

public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
        PrintStream out = new PrintStream(resp.getOutputStream());
        out.println("Hello students!");
    }
}

// index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>HEllo world!</h1>
</body>
</html>

我已將Intellij配置為使用本地tomcat安裝。 當我部署項目時,似乎只有index.jsp起作用。 / welcome路徑的http請求給出405。我做錯了什么?

servlet映射似乎是錯誤的。

  <servlet>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>com.rippleworks.WelcomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/welcome</url-pattern>
  </servlet-mapping>

和您的servlet:

public class WelcomeServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //do whatever you want here


    //forward request to index
    RequestDispatcher rd=req.getRequestDispatcher("index.jsp");    
    rd.forward(req,resp);  

    }
}

試試看,讓我知道它是否適合您。 嘗試之前,請記住重新啟動服務器。

是導致問題的super.doGet(..)。 從HttpServlet的源代碼中,默認實現是這樣,

public void doGet(..) {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_get_not_supported");
        if (protocol.endsWith("1.1")) {
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, msg);
        }
}

它將始終以錯誤響應。 刪除了對super方法的調用,現在可以正常使用了。

PS。 感謝大家的答復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM