1. When user clicks on the hyperlink, the JSP is directly invoked.
2. The servlet container parses the JSP and executes the resulting Java servlet.
3. The JSP contains embedded code and tags to access the Model JavaBeans. T
4. The Model JavaBeans contains attributes for holding the HTTP request parameters from the query string.
5. In addition it contains logic to connect to the middle tier or directly to the database using JDBC to get the additional data needed to display the page.
6. The JSP is then rendered as HTML using the data in the Model JavaBeans and other Helper classes and tags.
Problems with Model 1 Architecture
1. Model 1 architecture is easy.
2. There is some separation between content (Model JavaBeans) and presentation (JSP). This separation is good enough for smaller applications.
3. Larger applications have a lot of presentation logic. In Model 1 architecture, the presentation logic usually leads to a significant amount of Java code embedded in the JSP in the form of scriptlets. This is ugly and maintenance nightmare even for experienced Java developers.
4. In large applications, JSPs are developed and maintained by page authors. The intermingled scriptlets and markup results in unclear definition of roles and is very problematic.
Model 2 Architecture - MVC
The Model 2 JSP architecture is actually MVC applied to web applications and hence the two terms can be used interchangeably in the web world.
- The Controller Servlet handles the user’s request. (This means the hyperlink in the JSP should point to the controller servlet).
- The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters (and optionally also based on session attributes).
- The JavaBeans talks to the middle tier or directly to the database to fetch the required data.
- The Controller sets the resultant JavaBeans (either same or a new one) in one of the following contexts – request, session or application.
- The controller then dispatches the request to the next view based on the request URL.
- The View uses the resultant JavaBeans from Step 4 to display data.
Note that there is no presentation logic in the JSP. The sole function of the JSP in Model 2 architecture is to display the data from the JavaBeans set in the request, session or application scopes.
Advantages of Model 2 Architecture
1. Since there is no presentation logic in JSP, there are no scriptlets. This means lesser nightmares.
2. With MVC you can have as many controller servlets in your web application. In fact you can have one Controller Servlet per module. However there are several advantages of having a single controller servlet for the entire web application.
3. In a typical web application, there are several tasks that you want to do for every incoming request. For instance, you have to check if the user requesting an operation is authorized to do so. You also want to log the user’s entry and exit from the web application for every request. You might like to centralize the logic for dispatching requests to other views.
4. If you have several controller servlets, chances are that you have to duplicate the logic for all the above tasks in all those places.
5. A single controller servlet for the web application lets you centralize all the tasks in a single place. Elegant code and easier to maintain.
1. The Model View Controller design pattern is a technique used to separate Business logic/state (the Model) from User Interface (the View) and program progression/flow (the Control).
2. This pattern is very useful when it comes to modern web development:
–The majority of modern, high usage websites are dynamically driven.
–People well skilled at presentation (HTML writers) seldom know how to develop back-end solutions and visa versa.
–Separating business rules from presentation is good no matter what environment you develop in be it web or desktop.
The View:
The view is how data is represented to the user. For instance the view in a web application may be an HTML page, an image or other media
The Model:
The model represents the data in the system. For instance, a model might represent the properties associated with a user’s profile
The Controller:
The controller is the glue between the model and the view. It is responsible for controlling the flow of the program as well as processing updates from the model to the view and visa versa.
Benefits of MVC
1. Promotes Modularity
2. Multiple views
3. Abstraction
4. Allows application to be defined in a flow-chart, use-case or activity diagram which is more easily transferred to implementation.
1. Struts is an open source MVC framework developed by the Apache Jakarta project group.
2. Struts allows JSP/Servlet writers the ability to fashion their web applications using the MVC design pattern.
3. Struts allows you to configure a lot of the default framework objects through xml configuration files.
The components of MVC in Struts:
–The View is usually defined as a JSP or HTML page.
–The Model is usually defined as a Java object (sometimes called a bean).
–The Controller is defined by a Java object which extends the org.apache.struts.action.Action class. The Action class is at the heart of the Struts framework.
1. To define a model in Struts is simple. Just create a java class and provide some functions.
2. Your model classes should be coded independent of the Struts framework to promote maximum code reuse by other applications (i.e. if you have to reference javax.servlet.* class in your model, you are doing something wrong)
3. Struts provides some default Model components, the most important of which is ActionForm.
4. If you create a Model class by extending the Struts ActionForm class, Struts will
–Ensure your form bean is created when needed
–Ensure form submittal directly updates your form object with the inputted values
–Your controller object will be passed the form bean
5. Struts will only handle models in an automatic fashion if you extend org.apache.struts.action.ActionForm
6. Most likely you will have already built model object such as Customer, Employee, etc…
7. Because you don’t want to tie your existing model objects to the Struts framework by having to extend ActionForm, Struts provides a org.apache.struts.util.PropertyUtils class that has a static method called copyProperties
8. When your controller receives a form, it can simply call PropertyUtils.copyProperties(myModel, form) to copy all form properties to your original model object
Model: ActionForm
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
public class LogonForm extends ActionForm {
protected String userName;
protected String password;
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
//There would also be getters for these properties
}
Ø When this “LogonForm” is associated with a controller, it will be passed to the controller whenever it’s service is requested by the user.
Ø JSP pages acting as the view for this LogonForm are automatically updated by Struts with the current values of the UserName and Password properties.
Ø If the user changes the properties via the JSP page, the LogonForm will automatically be updated by Struts
Ø But what if the user screws up and enters invalid data? ActionForms provide validation…
Ø Before an ActionForm object is passed to a controller for processing, a “validate” method can be implemented on the form which allows the form to belay processing until the user fixes invalid input as we will see on the next slide...
Model: ActionForm
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
if (“”.equals(this.userName)) {
ActionErrors aes = new ActionErrors();
aes.add(new ActionError(“error.username.invalid”));
return aes;
}
}
Typically what will happen is Struts will see that errors are being returned and will forward the user to a jsp page that has been setup as the “failure” page. Usually, the errors result from bad input on a form, so the failure page will be set to the original form and any <html:errors> tags which are found are replaced with the contents of the ActionErrors returned from the validate method.
Ø The controller is the switch board of MVC.
Ø It directs the user to the appropriate views by providing the view with the correct model
Ø The task of directing users to appropriate views is called “mapping” in struts.
Ø Luckily, the Struts framework provides a base object called org.apache.struts.action.ActionServlet.
Ø The ActionServlet class uses a configuration file called struts-config.xml to read mapping data called action mappings
Ø The ActionServlet class reads the incoming URI and tries to match the URI against a set of action mappings to see if it can find a controller class which would be willing to handle the request
Ø This process is described in a diagram on the following page
Ø http://myhost/authorize.do Server configured to pass *.do extensions to org.apache.struts.action.ActionServlet via a web.xml configuration file ActionServlet object inspects the URI and tries to match it
against an ActionMapping located in the struts-config.xml file. Instance of appropriate Action class is found and it’s perform() method is called Action object handles the request and returns control to a view based where the user is within the flow of the application
Controller:
public class LogonAction extends Action {
public ActionForward perform(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
LogonForm myForm = (LogonForm) form;
if (myForm.getUserName().equals(“john”) &&
myForm.getPassword().equals(“doe”)) {
//return a forward to our success page
return mapping.findForward(”success”);
} else {
ActionErrors errors = new ActionErrors();
errors.add("password",
new ActionError("error.password.required"));
this.saveErrors(errors); //Action implements this method
//go back to the page that made the request
return (new ActionForward(mapping.getInput()));
}
}
}
Ø You might be wondering what mapping.findForward(“success”) means?
–The mapping object passed to the Controller’s perform() method is of type ActionMapping.
–When you setup your struts-config.xml file you can define forward tags that are available via the ActionMapping.findForward() method.
–In the previous example, our ActionMapping object would have been loaded with values from the <action-mapping> section defined for the LogonAction
Controller: ActionMapping
<action-mappings>
<action path="/logon"
type="org.apache.struts.example.LogonAction"
name="logonForm"
scope="request"
input="/logon.jsp">
</action>
<forward name="success” path="/msgBoard.jsp"/>
</action-mappings>
Ø The view in Struts is represented by JSP pages
Ø JSP pages allows developers to write java code, and access server side java objects in a web page
Ø Although this is good, we will distract ourselves from the reason we are using Struts and MVC.
–We want to let our web page authors create dynamic web pages without knowing how to program
Ø JSP solves this by introducing the concept of Tag Libraries
–Taglibs allow web designers the convenience of using HTML like tags
–It lets developers program the logic behind the tags
–The attributes of the tags are used as basic parameters that the developers will interpret, which could change the output generated by the tag
* Struts contains a series of taglibs designed to allow developers and web page authors the ability to communication one another to facilitate dynamic web content
The View: Example
<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html locale="true">
<head>
<title><bean:message key="logon.title"/></title>
<html:base/>
</head>
<body bgcolor="white">
<html:errors/>
<html:form action="/logon.do" focus="username">
<table border="0" width="100%">
<tr>
<th align="right">
<bean:message key="prompt.username"/>
</th>
<td align="left">
<html:text property="username" size="16" maxlength="16"/>
</td>
</tr>
<tr>
<th align="right">
<bean:message key="prompt.password"/>
</th>
<td align="left">
<html:password property="password"
size="16" maxlength="16"/>
</td>
</tr>
<tr>
<td align="right">
<html:submit property="submit"
value="Submit"/>
</td>
<td align="left">
<html:reset/>
</td>
</tr>
</table>
</html:form>
</body>
</html:html>
View: Internationalization
Ø Commonly referred to as i18n (I <followed by 18 letters> n)
Ø The ability to maintain a web app in several different languages
Ø Based on the language setup on the client side, the web app will auto-magic-ally
Ø This is achieve in Struts through Java Resource Bundles
Ø ResourceBundles are classes that support, among other things, String data.
Ø Instead of having to make a ResourceBundle class for each language supported by your web app, resource bundles can be described as text files
Ø If you had a set of strings in the French language you might make a file named MyStrings_fr.properties
MyResources.properties file:
helloworld.title=Hello World!
menu.file=File
menu.file.open=Open
menu.file.close=Close
menu.file.exit=Exit
menu.edit=Edit
menu.edit.copy=Copy
menu.edit.paste=Paste
MyResources_fr.properties file:
helloworld.title=Allô monde!
menu.file=Dossier
menu.file.open=Ouvrir
menu.file.close=Fermer
menu.file.exit=Sortie
menu.edit=Rédiger
menu.edit.copy=Copier
menu.edit.paste=Pâte