如果值是动态的,如何获取输入值作为String?

时间:2018-12-30 16:47:51

标签: jsp

我想将用户填写其姓名的Input Element的值传递给另一个jsp文件,以便当用户按下登录按钮时,home.jsp将包括他的姓名。使用预定义的值可以工作,使用jquery则不需要。我需要输入元素,因为我想使用数据库表的元素检查凭据(已经可以使用)

我尝试在第一种形式的内部和外部创建另一个具有预定义值作为String的输入元素。很好。

login.jsp看起来像这样。 我希望这包括解决问题所需的一切

<h3>User Login</h3>
            <hr>
            <form class="form-horizontal" method="POST" action="/demo/login-user">
                    <div class= "alert alert-danger">                           
                        </div>
                <div class="form-group">
                    <label class="control-label col-md-3">Name</label>
                    <div class="col-md-7">
                        <input type="text" class="form-control" name="name"
                            value="${user.name}" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-md-3">Password</label>
                    <div class="col-md-7">
                        <input type="password" class="form-control" name="password"
                            value="${user.password}" />
                    </div>
                </div>
                <div class="form-group ">
                    <input type="submit" class="btn btn-primary" value="Login" />
                </div>
                </form>

<form action="home.jsp" method="post">
   <%
session.setAttribute("userId", "dave"); //dave should be the ${user.name} value
    %>
</form>

home.jsp

<body>
<%String userid = session.getAttribute("userId").toString(); %>
<h1>Hello, <%=userid%></h1>
</body>

预期结果是,如果用户输入(正确)凭据,home.jsp页面将加载“ Hello,NAME”。

修改

意识到它不是jquery,而是表达语言?另一个线程建议我使用     request.getParameter("name"); 但这抛出了一个空指针。

1 个答案:

答案 0 :(得分:0)

我认为您有一个Servlet用于映射/demo/login-user

在该Servlet的doPost方法调用中

request.getSession().setAttribute("userid", request.getParameter("name"));

这样,您可以在所有jsp文件中使用session.getAttribute("userId")来登录用户名。

您应该从<form action="home.jsp" method="post"> <% session.setAttribute("userId", "dave"); //dave should be the ${user.name} value %> </form>删除最后一部分(login.jsp

相关问题