无法将表单从JSP提交到Servlet

时间:2016-01-26 07:17:08

标签: forms jsp servlets http-status-code-404

我是JSP和Servlets的初学者。在我的应用程序文件夹结构如下:

Servlet Class: LearningJSP\src\servlet\UserDetailsServlet.

Jsp file : JSP\Inputform.jsp

代码如下:

package servlet;

import java.io.IOException;

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 UserDetails
 */

@WebServlet(urlPatterns = {"/userdetails"})

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserDetailsServlet()
    {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String name = request.getParameter("name");
        String surname = request.getParameter("surname");
        String age = request.getParameter("age");

        javabeans.UserDetailsValue userDetails = new javabeans.UserDetailsValue();
        userDetails.setAge(age);
        userDetails.setName(name);
        userDetails.setSurname(surname);

        request.setAttribute("message", "saved successfully.");
        request.getRequestDispatcher("/UserDetails.jsp").forward(request, response);
    }

}

InputForm.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>Form</title>
</head>
<body>
<h1>Please fill up the data for Registration.</h1>
<form action = "/userdetails" method = "GET">
<input type = "text" name = "name"><br>
<input type = "text" name = "surname"><br>
<input type = "text" name = "age"><br>
<input type = "submit" value = "Register"><br>
</form>
</body>
</html>

我正在

  

错误404:找不到资源。

我认为在JSP中的动作标记中存在一些错误,但在经过多次试验之后,我找不到我的错误。

请帮我找错。 提前致谢

3 个答案:

答案 0 :(得分:0)

尝试使用action = "../userdetails"

答案 1 :(得分:0)

您是否直接在WebContent文件夹下有request.getRequestDispatcher("/UserDetails.jsp").forward(request, response); 页面?如果没有,Exception就会从这里开始:

LearningJSP\WebContent\

因为此路径中不存在该文件:

F12
  

查看所有被调用资源的一个好练习是

  • 打开浏览器
  • 打开控制台(CTRL + E
  • 转到网络
  • 点击开始捕获(Chrome中的var usr = context.Get<User>("Doe");
  • 刷新页面以查看页面请求的所有资源。其中一个将具有404的状态。

all the resources requested by one page

答案 2 :(得分:-3)

Your Project Structure should be like this. Click this link

InputForm.jsp应该有form标签,如下所示:

UserDetailsS​​ervlet.java doGet方法应具有:  request.getRequestDispatcher("/JSP/UserDetails.jsp").forward(request, response); 注意:/JSP/UserDetails.jsp

这是我修改后的答案,如果解决方案有效,请给我正面投票。