That's not entirely right. In contrary to what lot of basic servlet tutorials try to let you believe, the servlet should not be used to output pure HTML. This contradicts the MVC ideology. There the JSP should be used for.
In this particular case, you need to let the servlet set the message which you'd like to display in the JSP in the request scope and then forward the request/response to the JSP. In the JSP, you can use JSTL to dynamically control the HTML output and use EL ${}
to access and display the message.
Here's a kickoff example of how the servlet should look like:
public class WelcomeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String message = null;
if ((username.equals("kiran")) && (password.equals("kiran"))) {
message = "Welcome "+username+" thanks for login...";
} else {
message = "You are not the valid user...";
}
request.setAttribute("message", message);
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
and edit your login.jsp
to add the following:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:if test="${not empty message}">
<h1>${message}</h1>
</c:if>
The taglib declaration has to go in the top. The <c:if>
can just be positioned exactly there where you'd like to display the <h1>
.
See also:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…