How to develop JSP/Servlets Web App using MVC pattern? - model-view-controller

I'm developing a JSP/Servlet web app (no frameworks). I want to use MVC pattern. I am going to design my project like this:
Controller: a servlet that reads a request, extracts the values,communicates with model objects and gives information to a JSP page.
View: JSP Pages.
Model: Java Classes / Java Beans .. etc.
The problem: Index.jsp is the starting point (default page) in my web site. So, the Index.jsp becomes the controller to parse the request. For example, the following request:
index.jsp?section=article&id=10
is parsed in index.jsp as following :
<div class="midcol">
<!-- Which section? -->
<%String fileName = request.getParameter("section");
if (fileName == null) {
fileName = "WEB-INF/jspf/frontpage.jsp";
} else {
fileName = "WEB-INF/jspf/" + fileName + ".jsp";
}
%>
<jsp:include page='<%= fileName%>' />
</div>
Here, I can't force the servlet to be a controller, because the index.jsp is the controller here since it's the starting point.
Is there any solution to forward the request from index.jsp to the servlet and then go back to index.jsp? Or any solution that achieves the MVC goal - the servlet should be the controller?
I'm thinking of making a FrontPageController servlet as default page instead of index.jsp, but I don't know if it's a perfect idea?

Get rid of index.jsp and just let the controller servlet listen on a specific url-pattern of interest. The controller itself should forward the request to the JSP page of interest using RequestDispatcher.
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
Alternatively you can let index.jsp forward or redirect to an URL which is covered by the controller servlet which in turn shows the "default" page (which seems to be frontpage.jsp).
That said, in a correct MVC approach, you should have no scriptlets in JSP files. Whenever you need to write some raw Java code inside a JSP file which can't be replaced reasonably by taglibs (JSTL and so on) or EL, then the particular Java code belongs in any way in a real Java class, like a Servlet, Filter, Javabean, etcetera.
With regard to the homegrown MVC approach, you may find this answer and this article useful as well.

Related

Spring MVC insert URL to another endpoint in the view

I'm migrating a Play! 1.2 web application and moving to Spring Boot + Spring MVC. Some views contain URLs to other endpoints. For example, I display the book title on the page and next to it I want to add the URL to go the book's details page (e.g. localhost/books/{id}).
In Play! 1.2 the controllers are static, and there is also a Router which can create the full URL for a method belonging to another controller (Router.getFullUrl("BookController.bookDetails", args)), but how do I achieve this with Spring MVC?
Best regards,
Cristian.
If you are trying to get the app/deployed name automatically in .jsp files to make the urls, then please make use of context path. An example below :
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
From your requirement "admin.myapp.com","admin-test.myapp.com" are server names right? Something like http://admin.myapp.com/book/{bookId},http://admin-test.myapp.com/book/{bookId}. In Spring app, relative path in jsp can be accessed using pageContext.request.contextPath
I also found the UriComponentsBuilder and ServletUriComponentsBuilder. They are similar to the Play! Framework router and provide methods for building URI's, handling parameters and the query etc. We chose to annotate the controllers' methods using constants and then use the same constants with the UriComponentsBuilder to build back the path and create the request query for GET requests.

Spring MVC 3.0 - restrict what gets routed through the dispatcher servlet

I want to use Spring MVC 3.0 to build interfaces for AJAX transactions. I want the results to be returned as JSON, but I don't necessarily want the web pages to be built with JSP. I only want requests to the controllers to be intercepted/routed through the DispatcherServlet and the rest of the project to continue to function like a regular Java webapp without Spring integration.
My thought was to define the servlet-mapping url pattern in web.xml as being something like "/controller/*", then have the class level #RequestMapping in my controller to be something like #RequestMapping("/controller/colors"), and finally at the method level, have #RequestMapping(value = "/controller/colors/{name}", method = RequestMethod.GET).
Only problem is, I'm not sure if I need to keep adding "/controller" in all of the RequestMappings and no matter what combo I try, I keep getting 404 requested resource not available errors.
The ultimate goal here is for me to be able to type in a web browser "http://localhost:8080/myproject/controller/colors/red" and get back the RGB value as a JSON string.
You are not correct about needing to add the entire path everywhere, the paths are cumulative-
If you have a servlet mapping of /controller/* for the Spring's DispatcherServlet, then any call to /controller/* will be handled now by the DispatcherServlet, you just have to take care of rest of the path info in your #RequestMapping, so your controller can be
#Controller
#RequestMapping("/colors")
public class MyController{
#RequestMapping("/{name}
public String myMappedMethod(#PathVariable("name") String name, ..){
}
}
So now, this method will be handled by the call to /controller/colors/blue etc.
I don't necessarily want the web pages to be built with JSP
Spring MVC offers many view template integration options, from passthrough to raw html to rich templating engines like Velocity and Freemarker. Perhaps one of those options will fit what you're looking for.

I do not want to map all my xhtml pages by a controller

But I want to use Spring security.
I think i have to use DispatcherServlet and its configuration in web.xml
I am developing an application that is nor jsp nor jsf project, i am going to make all connection based on javascript/ajax/jquery via server communication.
Thus i do not want to map my xhtml pages to a controller.
But i have a single controller with #RequestMapping(/auth/login) i only want it to run when i request /auth/login this is not the problem, it is working excellently.
But when i use
spring
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:META-INF/spring-servlet.xml
1
spring
/heythere/*
and call http://localhost:8080/app/myhtml.xhtml it tells me i have no mapping for this uri.
I do not want mapping, nor controller to run, only want to see the page.
But DispatcherServlet needs to map it, how can i tell DispatcherServlet not to map ordinary xhtml pages?
Option 1:
Inside your spring web mvc application context XML you should put something like:
<mvc:view-controller path="/myhtml.xhtml"/>
The downside is you'll have to do this per page.
Option 2:
Use a Resource Handler:
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources -->
<mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/static/**"/>
Your page would be visible like http://localhost:8080/app/static/myhtml.xhtml.
More info can be found in Spring's Doc.

Cannot access struts action data from nested JSP

I am working for first time with Struts 2 + Spring + Hibernate architecture. I took this project as reference for building it and it works. I can list DB tables in my index.jsp using struts tags, but this does not work from nested JSP loaded into DIV containers inside index.jsp.
index.jsp has a <div class="art-nav"></div> and loads there another jsp using js:
$(".art-nav").load("./menu.jsp");
The same struts tags that work in index.jsp to list DB tables do not work in menu.jsp. I am not sure if the problem is the way I am loading this JSP or if it is necessary to execute some action from Struts 2 before loading menu.jsp...
Basically the JSPs use AJAX and I am adapting them to this architecture and there is where I am facing the problems because of my lack of experience.
Thank you in advance for your help!
You should include the second jsp as follows:
<div class="art-nav">
<%# include file="/WEB-INF/jsp/menu.jsp"%>
</div>
If you load your jsp via javascript the response will not get forwarded to that jsp.
If you really want to load a jsp via javascript you should create a new action (menu.action) that returns a parsed jsp and include it in the existing html. (Though I personally do not really like that technique.)

MVC Pattern in Web App (JSP Language)

Hello i am developing a web app...i am using MVC architecture in my design.
i have one form add_Flat.jsp in which admin enter the flat details and it will be stored in database (MS-Access) no other jsp page would be open on submit button.just a message displayed on add_Flat.jsp.
How can i achieve this by using MVC pattern ? do i have to write different servlet for every jsp page ? and model class for database connectivity ?
How can i achieve this by using MVC pattern ?
Let the form submit to a servlet which sets the message in the request scope and forwards back to the JSP.
do i have to write different servlet for every jsp page ?
Not necessarily. You can write a single servlet which acts as a front controller, or just use an existing MVC framework like JSF, Spring MVC, etc.
and model class for database connectivity ?
A model class should not be aware about any DB connectivity. A model class should be a simple Javabean class.
See also:
Our servlets wiki page - Contains Hello World examples and links to in-depth answers on servlet related questions here.

Resources