在同一个html页面中显示servlet响应而不隐藏表单

displaying servlet response in same html page without hiding form

本文关键字:响应 隐藏 表单 servlet 显示 html 同一个      更新时间:2024-02-29

我有一个HTML页面,它得到两个输入值,如下所示登录信息

<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页面中隐藏表单。谢谢!。

首先,为什么要在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);

然后你必须将请求转发回Jsp,并发送一个请求分配器

RequestDispatcher 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>