如何在不使用jsp的情况下将参数从java servlet传递到html表单

时间:2014-05-20 19:46:51

标签: java servlets parameters html-form

我想将一些参数从我的java servlet传递给我要显示的html表单。我已经阅读了一些关于jsp的内容,但我想知道我是否可以直接使用这样的东西:

<script> var temp = "${param['CookieServlet0.First_Name']}"; </script>
<input type = "text" name = "First_Name" id = "First_Name" value = "temp" > <br>

其中First_Name是我的servlet CookieServlet0的参数。我知道代码示例是错误的,有没有办法解决它,以便我不必使用jsp?

编辑:好,因为没有办法我开始使用jsp,我已经检查了你们发送的关于JSTL的内容,我不需要它提供的额外内容所以我试图保持简单,因为我刚刚开始。所以我编写了下面的代码,但是我得到了java.lang.NullPointerException。它必须是非常明显的东西,但我看不出我做错了什么...我看到的所有教程都使用完全相同的命令......

java servlet:

 public void doGet( HttpServletRequest request,        // reaction to the reception of GET
                  HttpServletResponse response )
                  throws ServletException, IOException
   {

    String First_Name = request.getParameter("First_Name");
    String Last_Name = request.getParameter("Last_Name");
    String Phone_Number = request.getParameter("Phone_Number");
    String Address = request.getParameter("Address");

    PrintWriter output;
    Cookie cookies[];

    cookies = request.getCookies(); // get client's cookies

    if ( cookies.length != 0 ) {                                               
        String departure = cookies[0].getValue();
        String destination = cookies[1].getValue();

    }

    request.setAttribute("First_Name",First_Name);
    String strViewPage="formB.jsp";
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strViewPage);
    dispatcher.forward(request, response);
 }

formB.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>Insert title here</title>
</head>
<body>
<label for = "First Name"> First Name </label>
<input type = "text" name = "First_Name" id = "First1_Name" value = "${First_Name}" 
"> <br>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

不,除非您编写自己的解析器/注入器,否则无法直接执行此操作。 但是,使用bean会尽可能接近。只需使用<jsp:useBean>并将html替换为bean属性的值。

快速谷歌搜索产生了这个网站,其中包含有关如何使用bean和jsp的示例:http://www.roseindia.net/jsp/simple-jsp-example/UsingBeanScopeApplication.shtml

如果您想使用JSTL,正如Luiggi所说,这是一个很好的网站:http://www.journaldev.com/2090/jstl-tutorial-with-examples-jstl-core-tags

答案 1 :(得分:0)

尝试使用:

RequestDispatcher dispatcher = request.getRequestDispatcher(strViewPage);

而不是:

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strViewPage);