我正在学习如何使用servlet,我复制了我的书中的例子,但我一直得到404错误。下面是代码:
package servlet;
import java.io.IOException;
import` java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SampleServlet2
*/
@WebServlet("/SampleServlet2")
public class SampleServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String[] luckArray = {"超スッキリ","スッキリ","最悪"};
int index = (int) (Math.random()*3);
String luck=luckArray[index];
Date date= new Date();
SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日");
String today=sdf.format(date);
response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>スッキリ占い</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>"+today+"の運勢は「"+luck+"」です</p>");
out.println("</body>");
out.println("</html>");
}
}">
我真的不知道该怎么做,因为这本书没有包含404错误,所有关于servlet的主题都是旧的。
您的代码中没有问题。可能是您的服务器配置有问题。我使用Eclipse IDE和tomcat 9,你的代码工作得很好。