所有,我是Java Web开发的新手,我正在尝试在我的测试中实现一个Servlet。但是我发现我创建的Servlet不起作用。我不知道我是否遗漏了什么。请帮我复习一下。谢谢。
到目前为止,我所做的是:
Dynamic Web Project
的{{1}}
SecondWeb
。Generate web.xml DD
的{{1}}
Servlet
。我使用值配置HelloServlet
com.example.servlets
和URL Mapping
。希望它适用于所有url模式
在根下。这是代码。
/HelloServlet
我还加了/*
加入了测试。
package com.example.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class for Servlet: HelloServlet
*
*/
public class HelloServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write("Hello, world!");
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
我期望的是,我希望在访问网址index.jsp
或<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Title</title>
</head>
<body>
<% java.util.Date d = new java.util.Date(); %>
<h1>
Today's date is <%= d.toString() %> and this jsp page worked!
</h1>
</body>
</html>
时,可以将Hello world
字符串添加到index.jsp
响应HTML
中。但似乎http://localhost:8080/SecondWeb
不起作用。为什么?感谢。
答案 0 :(得分:1)
我发现了这个问题,我必须在Servlet
中添加Web.xml
配置。如下根元素:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.servlets.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>