GET参数在Java servlet类中无法访问

时间:2016-11-13 18:33:06

标签: java jsp servlets java-ee

我刚刚开始使用J2EE和servlet编程,并陷入了这个小麻烦。这是我的代码 - 我的servlet类代码     package PackageServer;

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;

public class PostServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public PostServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";

      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>First Name</b>: "
                + request.getParameter("first_name") + "\n" +
                "  <li><b>Last Name</b>: "
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
      out.println("<h1>Hello</h1>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
/*protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}*/

}

现在我在HTML文件中的params是first_name和last_name。我已经正确地将web xml文件中的url-pattern指定为我的servlet类的名称,但是当我运行我的项目时,服务器响应时找不到404,然后显示带有servlet输出的视图,其中first_name和last_name设置为空值。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

确保地址。例如,如果在Eclipse中进行本地测试,则可以是

http://localhost/[project-name]/[url-pattern]

http://localhost:8080/[project-name]/[url-pattern]

(验证您的服务器配置 - 是Tomcat吗?)

提供更多信息,例如web.xml文件是404错误的地方,如果是这样的话。

最后,使用WEB-INF外部的简单test.html文件进行测试,并使用浏览器直接打开它。这将确保您没有连接/服务器问题