【问题标题】:displaying servlet response in same html page without hiding form在同一个 html 页面中显示 servlet 响应而不隐藏表单
【发布时间】:2016-07-28 09:39:00
【问题描述】:

我有一个 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 页面中并隐藏表单。谢谢!。

【问题讨论】:

    标签: javascript java html forms servlets


    【解决方案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);
    

    然后你必须使用请求分发器将请求转发回 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> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2020-04-20
      • 1970-01-01
      相关资源
      最近更新 更多