// 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.我做错了什么?
答案 0 :(得分:0)
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);
}
}
尝试一下,让我知道它是否适合你。请记住在尝试之前重新启动服务器。
答案 1 :(得分:0)
导致问题的是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。感谢大家的回复。