将两个jsp页面传递给servlet

时间:2016-12-11 10:48:56

标签: jsp servlets

大家好,我是网络新手。这是问题所在。 我有两个JSP页面,我希望使用一个servlet来获取所有数据。

1.jsp
<form action="2.jsp">
    <input type="text" name="jsp1">
</form>


2.jsp
<form action="servlet">
    <input type="text" name="jsp2">
</form>

servlet.java
request.getParameter("jsp1");
request.getParameter("jsp2");

1 个答案:

答案 0 :(得分:0)

您不能同时发送2个请求 但是如上所述,您需要从第一页向第二页发送参数,然后您需要从第二页(包括第一页的参数)发送参数到servlet(以下示例不是完美的解决方案,但如上所述) 这是一个例子:

的index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title></title>
</head>
<body>

<form method="post" action="index2.jsp">
  <input type="text" name="text1" />
  <input type="text" name="text2" />
  <input type="submit" value="send" />


</form>

</body>
</html>

index2.jsp

<%@ page import="java.util.Enumeration" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
<form method="post" action="servlet">
    <%

        String page1="";

        Enumeration<String>names=request.getParameterNames();

        while (names.hasMoreElements())
        {
            String name=names.nextElement();
            String value=request.getParameter(name);


            page1+=name+"="+value+"&";


        }

        if(page1.length()>0)
            page1=page1.substring(0,page1.length()-1);


    %>


    <input type="hidden" name="page1" value="<%=page1%>" />
    <input type="text" name="text3" />
    <input type="text" name="text4" />
    <input type="submit" value="send" />


</form>

</body>

Servlet:

package mypackage;

import java.io.IOException;


public class TestServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        String page1=request.getParameter("page1");
        String text3=request.getParameter("text3");
        String text4=request.getParameter("text4");

        System.out.println(" page1 "+page1);
        System.out.println(" text3 "+text3);
        System.out.println(" text4 "+text4);

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        doPost(request,response);
    }
}

web.xml:

 <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>mypackage.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>servlet</url-pattern>
    </servlet-mapping>