我正在训练营参加商业Java编程课程。
我想构建一个servlet基础网页来验证SSN。
验证SSN后,我会向用户显示有关SSN的信息。
但是,当我在Eclipse上运行servlet时,我收到了404页面。
我正在尝试调试,但我无法解决问题。
我的困惑在于将参数从doGet传递到doPost方法,然后通过doPost显示有关SSN的相关信息。
我没有使用HTML重定向,也没有重定向到另一个servlet。
这是一个独立的servlet。
以下代码:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
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("/AboutMe")
public class AboutMe extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println(" <meta charset=\"UTF-8\">");
out.println(" <title>About Me</title>");
out.println("</head>");
out.println("<body>");
out.println("<form action=\"AddEntry\" method=\"get\">");
out.println(" SSN: <input type=\"text\" name=\"ssn\" /> <br />");
out.println(" <input type=\"submit\" />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String SSN = request.getParameter("ssn");
//validate string
String message = "";
if ( SSN == null || SSN.trim().length() == 0 || SSN.trim().length() != 9 || !SSN.equals("123456789") ) {
message = "Enter SSN!";
} else {
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html>");
out.println("<head>");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println(" <meta charset=\"UTF-8\">");
out.println(" <title>Insert title here</title>");
out.println("</head>");
out.println("<body>");
out.println("<div id = name>");
out.println("FirstName LastName");
out.println("</div>");
out.println("</br>");
out.println("</br>");
out.println( "<p>The SSN is " + SSN + "! </p>" );
out.println("</br>");
out.println("</br>");
out.println("<p class = paragraph>");
out.println(" User information goes here." );
out.println( "</body></html>" );
}
}
}
答案 0 :(得分:0)
您的servlet仅按照@WebServlet("/AboutMe")
行处理/ AboutMe,但您的表单操作指向地址/ AddEntry。
将表单操作更改为/ AboutMe,方法POST 或为/ AddEntry添加处理程序(并将表单方法更改为POST)
@WebServlet(ulPatterns={"/AboutMe","/AddEntry"})