Sending data from servlet to jsp?

大城市里の小女人 提交于 2020-07-16 07:56:05

问题


I have a form in a jsp from which i am retrieving data to servlet via doPost method, suppose username and password now there is an empty textarea field inside the same form where i want to send the username from servlet,how do i do it?


回答1:


I don't really understand your case. But there're 2 common ways to send data from servlet to JSP:

Request attributes: you can use this if data is transferred along a same request.

request.setAttribute("username",obj);
request.getRequestDispatcher("url").forward(request,response);

In JSP:

<div>${username}</div>

Session attribute: use this to retain data during a session

Session session = request.getSession(true); //true: create session if not existed
session.setAttribute("username",obj);
response.sendRedirect("url"); //or use request dispatcher to forward the request

In JSP:

<div>${username}</div>



回答2:


Write your Servlet class like this

public class ServletToJSP extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //communicating a simple String message.
        String message = "Example source code of Servlet to JSP communication.";
        request.setAttribute("message", message);

        //Servlet JSP communication
        RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("jsp url");
        reqDispatcher.forward(request,response);
    }
}

jsp page

<%
    String message = (String) request.getAttribute("message");
    out.println("Servlet communicated message to JSP "+ message);
%>

enter code here



来源:https://stackoverflow.com/questions/51608047/sending-data-from-servlet-to-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!