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错误。
答案 0 :(得分:0)
在服务器运行时,有许多方法可以调用它。我列出了其中的一些:
A。
假设上下文路径为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
,并以{{1}的身份访问},然后点击提交按钮。文件内容如下:
http://localhost:8080/TestDynamicProject/testservlet.html