从servlet请求jsp中定义的变量?

时间:2016-05-01 20:11:08

标签: java jsp servlets

登录人员的用户名存在于索引页面上,代码正常。但是尝试从servlet访问变量用户名证明很难。有任何想法吗?

的index.jsp

   <html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
    <title><%=request.getParameter("username")%> - Cloud</title>  
      <link rel="stylesheet" href="css/bootstrap.css">
    </head>  
    <header class="page-header">

    <% String username = request.getParameter("username");%> // How can i get this variable?
    <h1 align="center" class="inline"><%=username%> - Files</h1>

    </header>

<body>  

Servlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
}

1 个答案:

答案 0 :(得分:1)

您必须通过jsp页面调用servlet

How to call servlet through a JSP page

这是oracle如何做到这一点的官方例子:

Jsp2Servlet.jsp

<HTML>
<HEAD> <TITLE> JSP Calling Servlet Demo </TITLE> </HEAD>
<BODY>
<!-- Forward processing to a servlet -->
<% request.setAttribute("empid", "1234"); %>
<jsp:include page="/servlet/MyServlet?user=Smith" flush="true"/>
</BODY>
</HTML>

MyServlet.java

public class MyServlet extends HttpServlet {

    public void doGet (HttpServletRequest request,
                   HttpServletResponse response) 
      throws IOException, ServletException {
      PrintWriter out= response.getWriter(); 
      out.println("<B><BR>User:" + request.getParameter("user"));
      out.println(", Employee number:" + request.getAttribute("empid") + "</B>");
      this.getServletContext().getRequestDispatcher("/jsp/welcome.jsp").
      include(request, response);
    }
}

的welcome.jsp

<HTML>
<HEAD> <TITLE> The Welcome JSP  </TITLE> </HEAD>
<BODY>

<H3> Welcome! </H3>
<P><B> Today is <%= new java.util.Date() %>.  Have a nice day! </B></P>
</BODY>
</HTML>

关键在于:

<jsp:include page="/servlet/MyServlet?user=Smith" flush="true"/>

在这个例子中,一个jsp调用一个servlet,一个servlet调用另一个jsp。该示例来自此页面: https://docs.oracle.com/cd/A87860_01/doc/java.817/a83726/basics4.htm