我有一个HTML页面,可以获得两个输入值,如下所示 LoginInfo类
<body>
<form method = "post" action = "LoginInfo">
Login Id: <input type = "text" name = "name"/> <br>
Password: <input type = "password" name = "password"/> <br> <input type = "submit" value = "Login"/>
</form>
</body>
我将这两个值传递给servelt页面,如下所示,
@WebServlet(urlPatterns = "/LoginInfo")
public class LoginInfo extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
return name;
}
}
并且servlet页面正在返回一些内容,我希望在表单下方的html页面中显示。现在我能够显示返回字符串,但表单消失了。我希望两个在同一个html页面中隐藏表单。谢谢!
答案 0 :(得分:1)
首先,为什么要在doPost方法中放置一个返回值?因为它是你的代码不应该编译
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
return name; // why?? it's not needed
}
其次要将值从Servlet传递给Jsp,您必须创建一个属性,例如像这样的请求属性
String name = request.getParameter("name");
request.setAttribute("name", name);
然后,您必须使用请求dispacther
将请求转发回JspRequestDispatcher disp = request.getRequestDispatcher();
disp.forward("nameofthepagewhereyourformis.jsp");
最后,您可以通过表达式语言检索Jsp中的属性。见下文
<body>
<form method = "post" action = "LoginInfo">
Login Id: <input type = "text" name = "name"/> <br>
Password: <input type = "password" name = "password"/> <br> <input type = "submit" value = "Login"/>
</form>
$(name) // attribute set in the servlet. At the bottom of the form as you wanted
</body>