0

I have a few Questions regarding servlets:

  • In Ruby on Rails you use the MVC-Architecture, how is it solved with servlets?

  • What is the difference between a .jsp file and a servlet?

  • If I want to create a model with a form, where would I put that form, into a servlet or into a jsp file, or somewhere entirely different?

  • How do I change the URL's of my jsp files, because having an url like example.com/example.jsp for a .jsp file, and example.com/example for a servlet seems wrong

Thanks in advance

Soyong
  • 178
  • 2
  • 15

1 Answers1

0

In summary:

  • Servlets are basically your Controllers in MVC architecture
  • JSP files are your Views as it contains your HTML
  • Since JSP files contains your HTML, forms should go to JSP. You could put forms into your Servlet if that's what you need.
  • You could either render your JSP from your Servlet(s), or map your Servlet in web.xml so it catches every request, and then forward the request to the target page.

Given below is just an example from others:

In web.xml

<servlet-mapping>
    <servlet-name>YOUR_SERVLET</servlet-name>
    <url-pattern>/</url-pattern>
    <url-pattern>/*.html</url-pattern>
</servlet-mapping>

And then inside your Servlet

String includeJsp;

String query = req.getRequestURI();
if (query == null || query.isEmpty() || query.equals("/")) {
 // home - intro
 includeJsp = "/about-intro.jsp";
} else if (query.equals("/games.html")) {
 includeJsp = "/games.jsp";
} else {
  // TODO
}

// draw JSP
req.setAttribute("includeJspContent", "/pages"+includeJsp);
try {
 req.getRequestDispatcher("/index.jsp").include(req, resp);
} catch (ServletException e) {
 e.printStackTrace();
}

Reference:

ionizer
  • 1,661
  • 9
  • 22