gpt4 book ai didi

java - 在服务器上运行时,我不断收到错误404

转载 作者:行者123 更新时间:2023-11-28 23:09:28 24 4
gpt4 key购买 nike

package com.davido.asuzor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SimpleServlet")
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello from Servlet GET method");
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h3>Hello in html</h3>");
}
}


我的tomcat成功连接,但是当我在服务器上运行代码时,出现错误404异常。

最佳答案

服务器运行时,可以通过多种方式调用它。我列出了其中一些:

一种。

假设上下文路径为http://localhost:8080/TestDynamicProject,则应在浏览器中输入URL http://localhost:8080/TestDynamicProject/SimpleServlet,然后按Enter。

B.

使用类似的Java程序

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

class Main {
public static void main(String[] args) {
System.out.println(getHTML("http://localhost:8080/TestDynamicProject/SimpleServlet"));
}

public static String getHTML(String urlToRead) {
try {
StringBuilder result = new StringBuilder();
InputStream stream = null;
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = conn.getInputStream();
}

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}

rd.close();
return result.toString();
} catch (Exception e) {
return e.getMessage().toString();
}
}
}


输出:

<h3>Hello in html</h3>


C。

从HTML或JSP页面访问它:例如,我在 testservlet.html文件夹下创建了 WebContent并以 http://localhost:8080/TestDynamicProject/testservlet.html的身份访问它,然后单击Submit按钮。文件内容如下:

<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="SimpleServlet">
<input type="Submit"/>
</form>
</body>
</html>

关于java - 在服务器上运行时,我不断收到错误404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com