Issue
I am creating a java
servlet web applicaiton where I take user input at index.jsp
and shows result at result.jsp
page upon POST
action. Before submiting the form I validate user input. If any validation error is found than I want to redirect
user to the same index.jsp
page with the error messages. But the redirect
action results in a blank page. Here is what I have done so far -
Servlet class doPost
method -
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
//this is just a dto class
CovidQa covidQa = new CovidQa(name);
CovidTestValidator validator = new CovidTestValidator();
boolean hasError = validator.validate(covidQa, req);
if (hasError) {
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}
req.getRequestDispatcher("/result.jsp").forward(req, resp);
}
Validator's validate
method-
public boolean validate(CovidQa covidQa, HttpServletRequest request) {
boolean hasError = false;
if (covidQa.getName() == null || covidQa.getName().equals("")) {
request.setAttribute("nameErr", "Name can not be null");
hasError = true;
}
return hasError;
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Covid-19</servlet-name>
<servlet-class>CovidTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Covid-19</servlet-name>
<url-pattern>/Cov</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
-
<form action="Cov" method="post">
//input fields
<label>Name</label>
<input type="text"
id="name"
name="name">
<span>${nameErr}</span>
<button type="submit">Submit</button>
</form>
Solution
req.getRequestDispatcher()
doesn't return
from the method implicitly. If you don't mention return
explicitly, immediate lines also will be executed by the compiler.
As @BalusC commented the system got confused by executing two req.getRequestDispatcher()
statement consecutively.
Either you need to return
explicitly -
if (hasError) {
req.getRequestDispatcher("/index.jsp").forward(req, resp);
return;
}
req.getRequestDispatcher("/result.jsp").forward(req, resp);
Or, put the later one inside else
block -
if (hasError) {
req.getRequestDispatcher("/index.jsp").forward(req, resp);
} else {
req.getRequestDispatcher("/result.jsp").forward(req, resp);
}
Answered By - Erfan Ahmed