Issue
This is the url of my project on localhost which is a login page:: "http://localhost:8080/OnlineExamination"
Here as soon as the login is valid, I want the url to be changed to "http://localhost:8080/OnlineExamination/home-page" so that it would prevent the user from taking him back to login page when the page reloads. How can I do this using JSP and Servlet? I have used a submit type input in which surrounding input by anchor tag resulted in not submitting the login form. Please Help!!
Solution
Redirect or Forward - which one should I choose?
Since you want the URL to be changed in the browser, you will have to send redirect instruction to the browser instead of forwarding the request to some other resource. Note that when you forward the request, the new resource will get everything from the request and the URL remains unchanged. On the other hand, in the case of redirect, the browser creates a new request for the new location (URL) which means nothing from the old request will be available to the new request.
How can I share some information between requests?
You will have to choose a bigger scope e.g. session
; simply put the information into the session and retrieve the same at the new location.
An illustration of the concept:
OnlineExamination.java
@WebServlet("/OnlineExamination")
public class OnlineExamination extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
// Code to check user credentials
// ...
// ...
request.getSession().setAttribute("loggedIn", true);
response.sendRedirect("OnlineExamination/home-page");
}
}
HomePage.java
@WebServlet("/OnlineExamination/home-page")
public class HomePage extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.write("" + request.getSession().getAttribute("loggedIn"));
}
}
This is a very basic code just for illustrating the concept. In a real project, you may choose some framework that can provide various ways to do all these.
Answered By - Arvind Kumar Avinash
Answer Checked By - Marie Seifert (JavaFixing Admin)