JSP和Servlet如何相互交互

时间:2014-02-03 02:41:10

标签: java eclipse jsp servlets web-applications

我正在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“)”标记。

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您是否尝试过这样(传统方式):

action =“&lt;%= request.getContextPath()%&gt; / IntroductionServlet”

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

希望这很有用。

答案 2 :(得分:0)

尝试:

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">