【问题标题】:How do JSP's and Servlets interact with each otherJSP 和 Servlet 如何相互交互
【发布时间】:2014-02-26 10:35:51
【问题描述】:

我正在 Eclipse 上创建 Java Web 应用程序,但不确定如何将 jsp 页面与 Servlet 链接。例如,如果您的 jsp 页面显示表单供用户输入他们的名字和年龄,然后一旦他们单击提交,就会重定向到 Servlet 来处理数据。

这里是 intro.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>
        <title>Hello World</title>
        <style>.error { color: red; } .success { color: green; }</style>
    </head>
    <body>
        <form action="intro" method="post">
            <h1>Hello</h1>
            <p>
                <label for="name">What's your name?</label>
                <input id="name" name="name">
                <span class="error">${messages.name}</span>
            </p>
            <p>
                <label for="age">What's your age?</label>
                <input id="age" name="age">
                <span class="error">${messages.age}</span>
            </p>
            <p>
                <input type="submit">
                <span class="success">${messages.success}</span>
            </p>
        </form>
    </body>
</html>

这里是 IntroductionServlet.java:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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("/intro")
public class IntroductionServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Preprocess request: we actually don't need to do any business stuff, so just display JSP.
        request.getRequestDispatcher("/WEB-INF/intro.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Postprocess request: gather and validate submitted data and display result in same JSP.

        // Prepare messages.
        Map<String, String> messages = new HashMap<String, String>();
        request.setAttribute("messages", messages);

        // Get and validate name.
        String name = request.getParameter("name");
        if (name == null || name.trim().isEmpty()) {
            messages.put("name", "Please enter name");
        } else if (!name.matches("\\p{Alnum}+")) {
            messages.put("name", "Please enter alphanumeric characters only");
        }

        // Get and validate age.
        String age = request.getParameter("age");
        if (age == null || age.trim().isEmpty()) {
            messages.put("age", "Please enter age");
        } else if (!age.matches("\\d+")) {
            messages.put("age", "Please enter digits only");
        }

        // No validation errors? Do the business job!
        if (messages.isEmpty()) {
            messages.put("success", String.format("Hello, your name is %s and your age is %s!", name, age));
        }

        request.getRequestDispatcher("/WEB-INF/intro.jsp").forward(request, response);
    }

}

根据我的理解,一旦单击提交按钮,form action = "intro" 应该将 intro.jsp 页面重定向到 IntroductionServlet。 但是,我在 Eclipse 中收到请求的资源不可用错误。它似乎改为搜索 intro.jsp 文件。我正在运行 Dynamic Web Module 3.0,所以我认为 web.xml 中不需要映射 servlet,因为我有“@WebServlet(”/intro")”标签。

基本上,我想知道如何在按下提交按钮后从文本字段中检索信息并将其用作我的应用程序中的变量。

【问题讨论】:

  • JSP(s) 被编译成 Servlet(s);每个 JSP is-a Servlet.
  • 将 intro.jsp 移动到 WebContent 文件夹并更改为 request.getRequestDispatcher("/intro.jsp") 是否有效?

标签: java eclipse jsp servlets web-applications


【解决方案1】:

您也可以通过手动定义您的 servlet 来提交您的表单, 我在我的应用程序中使用了它。 以下是代码:-

$("#SubmitButton").click(function()
            {       var HashedPass=Sha1.hash($("#userPassword").val());
                    $("#userPassword").val(HashedPass);
                    $('#loginForm').attr('method','post');
                    $('#loginForm').attr('action','SignupServlet');
                    $('#loginForm').submit();
            }); 

【讨论】:

  • 这会在 Servlet 中定义吗?
  • 如何将来自 jsp 页面的文本字段的值存储在 jsp 本身上。使用 request.getParameter() 一直给我 null
【解决方案2】:

你有没有试过这样(传统方式):

action="/IntroductionServlet"

关于你的第二个问题:一旦控件从jsp页面到达servlet,就可以通过servlet中的request.getparameter(textfieldname)访问textfield内容。

希望这是有用的。

【讨论】:

  • 我仍然无法控制从 jsp 页面到达 servlet。 action="/IntroductionServlet" 仍然给我“请求的资源不可用”错误
  • 有时可能不是程序的问题。您正在使用的 IDE 是什么?可能是日食?尝试清理服务器和 tomcat 工作目录。并在使用request.getContextPath()时去掉@webservlet注解。
【解决方案3】:

试试:

request.getRequestDispatcher("WEB-INF/intro.jsp").forward(request, response);

接收你应该使用的参数:

request.getParameter("<name of input text>");

发送参数:

request.setAttribute("myobject", myobjetc); 

并使用:

从 jsp 访问此变量
${myobject.atribute}

如果 servlet 不工作,将其添加到表单中(没有必要,但你可以尝试):

<form action="${pageContext.request.contextPath}/intro" method="POST"> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    相关资源
    最近更新 更多