I would like to render the same JSP for multiple Struts Actions. I'm having trouble because when rendering the JSP, the bean name is different depending on which Action was called. So, I can't call something like:
<c:out value="${myBean.myProperty}" />
because the bean isn't necessarily called myBean.
Currently, I've been getting around this by placing any common objects I'll need in the JSP into the HttpSession. For example:
public class SampleAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
String string = "TEST";
HttpSession session = request.getSession();
session.setAttribute("sampleString", string);
return mapping.findForward("sampleAction");
}
}
Then, in the JSP, I can simple reference "sampleString" and it won't change depending on the rendering Action.
Of course, the objects I'm using are much larger than a string, and I don't want to put objects in the session if I don't have to. Is there any way to just put an object into the page context or something, rather than the session, in order to share it among different JSPs?
I'm coming from the Rails world, so I'm very new to Struts and am finding myself a bit lost. I have to extend an existing application written in Struts. The program actually uses BeanAction to combine an ActionForm with an Action, so the example above isn't exactly what my code looks like.
Thanks for any help clearing up my confusion!
My first thought was to try implementing it as a custom tag, just like krosenvold said in his answer. But you said you are new to Struts, and I will assume you are new to JSP's and J2EE web development too. And custom tag's are not a very easy subject.
You could use a 'proxy' page to call via jsp:include your destination JSP. The jsp:include tag can have a body having jsp:param tags, in which you can map a common variable name to different references.
See here for an example in jsp:param in jsp:include.
By doing that, you will have a single page with you real code, and N proxies to handle referencing to your complex objects.
Using custom tags would work too, this is just another way of doing it, which I personally think is easier to implement for a non-SCWCD.
I think you want to use an interface that the three different action classes implement, so you can have the same jsp use the interface type. Note that this makes the three action classes "the same" wrt to that jsp, so I'm basically saying that's the route to go. If you cannot/will not use that then I'd probably use a custom jsp tag to encapsulate the common bits and have separate jsp's for each page call the same common tag.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am designing a simple web-based application. I am new to this web-based domain.I needed your advice regarding the design patterns like how responsibility should be distributed among Servlets, criteria to make new Servlet, etc.
Actually, I have few entities on my home page and corresponding to each one of them we have few options like add, edit and delete. Earlier I was using one Servlet per options like Servlet1 for add entity1, Servlet2 for edit entity1 and so on and in this way we ended up having a large number of servlets.
Now we are changing our design. My question is how you exactly choose how you choose the responsibility of a servlet. Should we have one Servlet per entity which will process all it's options and forward request to the service layer. Or should we have one servlet for the whole page which will process the whole page request and then forward it to the corresponding service layer? Also, should the request object forwarded to service layer or not.
A bit decent web application consists of a mix of design patterns. I'll mention only the most important ones.
Model View Controller pattern
The core (architectural) design pattern you'd like to use is the Model-View-Controller pattern. The Controller is to be represented by a Servlet which (in)directly creates/uses a specific Model and View based on the request. The Model is to be represented by Javabean classes. This is often further dividable in Business Model which contains the actions (behaviour) and Data Model which contains the data (information). The View is to be represented by JSP files which have direct access to the (Data) Model by EL (Expression Language).
Then, there are variations based on how actions and events are handled. The popular ones are:
Request (action) based MVC: this is the simplest to implement. The (Business) Model works directly with HttpServletRequest and HttpServletResponse objects. You have to gather, convert and validate the request parameters (mostly) yourself. The View can be represented by plain vanilla HTML/CSS/JS and it does not maintain state across requests. This is how among others Spring MVC, Struts and Stripes works.
Component based MVC: this is harder to implement. But you end up with a simpler model and view wherein all the "raw" Servlet API is abstracted completely away. You shouldn't have the need to gather, convert and validate the request parameters yourself. The Controller does this task and sets the gathered, converted and validated request parameters in the Model. All you need to do is to define action methods which works directly with the model properties. The View is represented by "components" in flavor of JSP taglibs or XML elements which in turn generates HTML/CSS/JS. The state of the View for the subsequent requests is maintained in the session. This is particularly helpful for server-side conversion, validation and value change events. This is how among others JSF, Wicket and Play! works.
As a side note, hobbying around with a homegrown MVC framework is a very nice learning exercise, and I do recommend it as long as you keep it for personal/private purposes. But once you go professional, then it's strongly recommended to pick an existing framework rather than reinventing your own. Learning an existing and well-developed framework takes in long term less time than developing and maintaining a robust framework yourself.
In the below detailed explanation I'll restrict myself to request based MVC since that's easier to implement.
Front Controller pattern (Mediator pattern)
First, the Controller part should implement the Front Controller pattern (which is a specialized kind of Mediator pattern). It should consist of only a single servlet which provides a centralized entry point of all requests. It should create the Model based on information available by the request, such as the pathinfo or servletpath, the method and/or specific parameters. The Business Model is called Action in the below HttpServlet example.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Action action = ActionFactory.getAction(request);
String view = action.execute(request, response);
if (view.equals(request.getPathInfo().substring(1)) {
request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
}
else {
response.sendRedirect(view); // We'd like to fire redirect in case of a view change as result of the action (PRG pattern).
}
}
catch (Exception e) {
throw new ServletException("Executing action failed.", e);
}
}
Executing the action should return some identifier to locate the view. Simplest would be to use it as filename of the JSP. Map this servlet on a specific url-pattern in web.xml, e.g. /pages/*, *.do or even just *.html.
In case of prefix-patterns as for example /pages/* you could then invoke URL's like http://example.com/pages/register, http://example.com/pages/login, etc and provide /WEB-INF/register.jsp, /WEB-INF/login.jsp with the appropriate GET and POST actions. The parts register, login, etc are then available by request.getPathInfo() as in above example.
When you're using suffix-patterns like *.do, *.html, etc, then you could then invoke URL's like http://example.com/register.do, http://example.com/login.do, etc and you should change the code examples in this answer (also the ActionFactory) to extract the register and login parts by request.getServletPath() instead.
Strategy pattern
The Action should follow the Strategy pattern. It needs to be defined as an abstract/interface type which should do the work based on the passed-in arguments of the abstract method (this is the difference with the Command pattern, wherein the abstract/interface type should do the work based on the arguments which are been passed-in during the creation of the implementation).
public interface Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
You may want to make the Exception more specific with a custom exception like ActionException. It's just a basic kickoff example, the rest is all up to you.
Here's an example of a LoginAction which (as its name says) logs in the user. The User itself is in turn a Data Model. The View is aware of the presence of the User.
public class LoginAction implements Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
return "home"; // Redirect to home page.
}
else {
request.setAttribute("error", "Unknown username/password. Please retry."); // Store error message in request scope.
return "login"; // Go back to redisplay login form with error.
}
}
}
Factory method pattern
The ActionFactory should follow the Factory method pattern. Basically, it should provide a creational method which returns a concrete implementation of an abstract/interface type. In this case, it should return an implementation of the Action interface based on the information provided by the request. For example, the method and pathinfo (the pathinfo is the part after the context and servlet path in the request URL, excluding the query string).
public static Action getAction(HttpServletRequest request) {
return actions.get(request.getMethod() + request.getPathInfo());
}
The actions in turn should be some static/applicationwide Map<String, Action> which holds all known actions. It's up to you how to fill this map. Hardcoding:
actions.put("POST/register", new RegisterAction());
actions.put("POST/login", new LoginAction());
actions.put("GET/logout", new LogoutAction());
// ...
Or configurable based on a properties/XML configuration file in the classpath: (pseudo)
for (Entry entry : configuration) {
actions.put(entry.getKey(), Class.forName(entry.getValue()).newInstance());
}
Or dynamically based on a scan in the classpath for classes implementing a certain interface and/or annotation: (pseudo)
for (ClassFile classFile : classpath) {
if (classFile.isInstanceOf(Action.class)) {
actions.put(classFile.getAnnotation("mapping"), classFile.newInstance());
}
}
Keep in mind to create a "do nothing" Action for the case there's no mapping. Let it for example return directly the request.getPathInfo().substring(1) then.
Other patterns
Those were the important patterns so far.
To get a step further, you could use the Facade pattern to create a Context class which in turn wraps the request and response objects and offers several convenience methods delegating to the request and response objects and pass that as argument into the Action#execute() method instead. This adds an extra abstract layer to hide the raw Servlet API away. You should then basically end up with zero import javax.servlet.* declarations in every Action implementation. In JSF terms, this is what the FacesContext and ExternalContext classes are doing. You can find a concrete example in this answer.
Then there's the State pattern for the case that you'd like to add an extra abstraction layer to split the tasks of gathering the request parameters, converting them, validating them, updating the model values and execute the actions. In JSF terms, this is what the LifeCycle is doing.
Then there's the Composite pattern for the case that you'd like to create a component based view which can be attached with the model and whose behaviour depends on the state of the request based lifecycle. In JSF terms, this is what the UIComponent represent.
This way you can evolve bit by bit towards a component based framework.
See also:
Examples of GoF Design Patterns in Java's core libraries
Difference between Request MVC and Component MVC
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
What components are MVC in JSF MVC framework?
JSF Controller, Service and DAO
In the beaten-up MVC pattern, the Servlet is "C" - controller.
Its main job is to do initial request evaluation and then dispatch the processing based on the initial evaluation to the specific worker. One of the worker's responsibilities may be to setup some presentation layer beans and forward the request to the JSP page to render HTML. So, for this reason alone, you need to pass the request object to the service layer.
I would not, though, start writing raw Servlet classes. The work they do is very predictable and boilerplate, something that framework does very well. Fortunately, there are many available, time-tested candidates ( in the alphabetical order ): Apache Wicket, Java Server Faces, Spring to name a few.
IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.
I have used the struts framework and find it fairly easy to learn. When using the struts framework each page of your site will have the following items.
1) An action which is used is called every time the HTML page is refreshed. The action should populate the data in the form when the page is first loaded and handles interactions between the web UI and the business layer. If you are using the jsp page to modify a mutable java object a copy of the java object should be stored in the form rather than the original so that the original data doesn't get modified unless the user saves the page.
2) The form which is used to transfer data between the action and the jsp page. This object should consist of a set of getter and setters for attributes that need to be accessible to the jsp file. The form also has a method to validate data before it gets persisted.
3) A jsp page which is used to render the final HTML of the page. The jsp page is a hybrid of HTML and special struts tags used to access and manipulate data in the form. Although struts allows users to insert Java code into jsp files you should be very cautious about doing that because it makes your code more difficult to read. Java code inside jsp files is difficult to debug and can not be unit tested. If you find yourself writing more than 4-5 lines of java code inside a jsp file the code should probably be moved to the action.
BalusC excellent answer covers most of the patterns for web applications.
Some application may require Chain-of-responsibility_pattern
In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.
Use case to use this pattern:
When handler to process a request(command) is unknown and this request can be sent to multiple objects. Generally you set successor to object. If current object can't handle the request or process the request partially and forward the same request to successor object.
Useful SE questions/articles:
Why would I ever use a Chain of Responsibility over a Decorator?
Common usages for chain of responsibility?
chain-of-responsibility-pattern from oodesign
chain_of_responsibility from sourcemaking
I've got a simple html page with four buttons. I know how to map the buttons so that the Action Class gets the value of whatever is selected and call a method based on each button in the Action Class. However, what should I do with the Action Form? Can I just leave it blank? It seems that struts requires you to map a bean, yet I'm not really sure what to put in the Action Form, since all that I'm trying to do is call methods in the Action Class.
The struts is what we call nowadays as "action-based" framework. Nowadays most frameworks are what we call "event-based" framework.
It was built to make your life easier when you need to fill huge html forms and then send it to the server.
It was not intended to make your life easier when pressing a button to execute some code on the server and then return with that specific small result.
The main idea of struts was that, big things and change the entire view.
This example (and mabye those ones, takes forever to download) how easier struts made the form-processing easier. see "5. Action (Controller)" of first link.
If not clear, in the time, when there were just servlets, you needed something like this to parse a form.
TL;DR; In the end the ActionForm is there just to help you with your html forms that otherwise you would need to parse by hand instead to receive them as well-formed java beans.
Purpose of ActionForm is to map your fields in your html forms to a corresposnding bean which can be mapped in your strus-config.xml inside the form-bean tag.
Can I just leave it blank? yes the ActionForm is not a required field in <action> tag.
I am working within a RESTful Web Framework that is natively script (JSP) based. The Framework has a routing mechanism that automatically sets a number Request attributes, which are then available in the JSPs (One of the attributes being a "Model" of the requested resource; which is basically just a HashMap).
The issue is 90% of the time, some amount of logic is required to be added to the JSP, be it more complex domain logic, retrieving other resource data (other Models), or scrubbing data for output.
I am looking at various establish web application design patterns for extracting domain logic out of the JSP, and keeping the JSP as logic-less as possible.
A few things to note:
Within the system im working in, the Model (the data pull from the database) is provided but the Framework (the previously mentioned HashMap); I could create my own Model wrappers around this data, but it's probably unnecessary.
JSP/Scripts are the end points for Requests - If I use a pattern that uses a Presenter/Controller-type object that returns a View bean (ViewModel?) which contains all the data the view will use, I will need to have a line in the JSP which calls the Presenter/Controller and instantiates the View bean.
Currently I've created a Presenter POJO for each Module (script), which has access to the Model (again, the Framework sets this as a Request attr), and simply instantiate it at the top of the JSP, and use it more or less like a bean.
If I understand it, correctly, I believe i've implemented the Presentation Model design pattern. [1]
Ex.
JSP looks like:
<% DemoPresenter demo = new DemoPresenter(request) %>
<%= demo.getTitle() %>
- or add it to pageContext to use w JSTL/EL -
<c:set var="demo" value="new DemoPresenter(request)"/>
${demo.title}
And the "Presenter/Controller" looks like:
public class DemoPresenter extends BasePresenter {
private String title;
public DemoPresenter(HttpServletRequest request) {
FrameworkModel model = request.getAttribute("frameworkProvidedResourceModel");
this.title = model.get("title").toUpperCase() + "!!!";
}
public getTitle() { return this.title; }
}
Any thoughts on using the Presenter obj directly in the JSP/Script, vs having it return a "logic-less" ViewModel bean that the Presenter populates w/ data? The advantage to this is I could have a single Presenter managed various "Views" of the same resource (such as Show-view, Edit-view, Summary-view, etc.) - Below is an example of how i could get various view models.
/blog/posts/1/show -> executes JSP which gets its ViewModel like so:
<% DemoDefaultViewModel default = new DemoPresenter(request).getViewModel(DemoDefaultViewModel.class); %>
/blog/posts/1/edit ->executes a JSP which gets its ViewModel like so:
<% DemoEditViewModel edit = new DemoPresenter(request).getViewModel(DemoEditViewModel.class); %>
I would like to keep a simple solution without too many extraneous pieces. I also can't get too fancy as I am working within a strict predefined framework - I just want to figure out a good way to move all my domain logic out of the JSP into more reusable, testable Java classes.
[1] http://martinfowler.com/eaaDev/PresentationModel.html
Check out struts.
I must admit to only having used the older version but the 'front controller' servlet idea seems to be what you're after . It is a special servlet to run common code and route requests.
It also has actions which can be tested outside of the web container.
The day I moved from pure JSP to struts was one of the best days of my web development life! The project started to feel organised and much easier to manage.
There are lots of MVC frameworks. For example Struts uses a front controller servlet to dispatch requests to a class (controller) depending on the resource used. The class processes the request and sends the result to the view (typically a jsp). The model is any class that represents your data. FYI, a Map is not a framework. Representing your data as a MAP only, will work, but is ugly and hard to maintain.
Without knowing your strict framework, generally accepted good practice would be to keep your business logic centralised and independent of any framework. Use your framework for plumbing only. Get your controller to mediate between your presentation and business logic, again this is just plumbing. Put your display data in the right scope (almost always the request scope) so you dont have to have scriptlets as in your example.
I am using Jersey to do the URL binding for my web application. Hence, I am using it as a very simple MVC. I can manage to have Jersey return my JSPs, however:
When I pass my model to the view, it is passed as "it" -- and I can access it on my JSP using tags, ala: ${it}, however, I want to use it as a JSP variable, via <%= it %>
Is there a way to do that?
I totally fail to see why you would ever do that, but anyway, the scriptlet equivalent of the EL expression
${it}
would be
<%=pageContext.findAttribute("it")%>
Update: as per the comments:
because I am experimenting with a new framework -- i want to pass in many html blobs and i want to access them via it.get("main"), it.get("footer"), etc
Just make it a Map<String, Something> or a Javabean class, then you'll be able to get them by
${it.main}, ${it.footer}, etc
where main, footer, etc are Map keys or Javabean properties. It'll return the value.
It's common to have many pages in a website that request the same model attributes, for example, a header that renders the current users name, or a column that needs a few server based pieces of information.
...
<body>
<mytaglib:header/>
...
<jsp:include page="footer.jsp"/>
...
</body>
The simplest solution is that every controller method you write that returns views that use the header, or footer also add all of attributes needed by components contained within it, but as the site grows it can become difficult to handle, particularly when you start dealing with pages that don't all have exactly the same components.
Is there a way to encapsulate the logic that adds to the model based on sub-pages or tags?
Well, you could do that in a few ways. The following pop in mind:
Put your logic in a Filter that places the information in request scope;
Spring has something similar to a Filter called an Interceptor. You can place your logic here and again save it in request scope.
Have the logic behind a custom tag that is inserted into your pages. There is a disadvantage to this because you must insert the tag in each JSP. If you are using a decorator filter like SiteMesh then you could place this once in your decorator JSPs and be done with it.
Have the logic in a parent controller that all your controllers will extend.
Do you use a framework in particular? If you only use servlets I would suggest you to create a base servlet class, if using spring I will suggest you to create a Base SPring MVC Controller. ANd you can set these attributes from the base class or use filters :)