Question: What is RequestProcessor and RequestDispatcher?

Answer: The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client. The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like The ActionServlet Class The RequestProcessor Class The Action Class The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application. The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows. <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> </servlet>

All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/actionName.do The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>/do/*</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/do/action_Name The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed. Once the controller receives a client request, it delegates the handling of the request to a helper

logging before invoking business operation.action. The strut framework will create only a single instance of each Action class in your application.someAction" scope="request" name="someForm" validate="true" input="somejsp.ActionMapping class . public ActionForward execute(ActionMapping mapping.apache.apache.somepackage.struts. The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> The action forward mappings also can be specified in a global section. HttpServletRequest request. The action forward are specified in the configuration file. independent of any .jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp. HttpServletResponse response) throws Exception. In the Struts framework this helper class is descended of org.struts.jsp" redirect="true"/> </action> Once this is done the controller should determine which view to return to the client. The execute() method is called by the controller when a request is received from a client. Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime.action.class. The Action class decouples the client request from the business model. <action> path= "/somerequest" type="com. The ActionForward class represents a destination to which the controller may send control once an action has completed. the Struts Action class contains several methods.apache. Instead of specifying an actual JSP page in the code.struts.ActionForward class. <action> path= "/somerequest" type="com.action. but most important method is the execute() method. It acts as a bridge between a client-side user action and business operation. This helper knows how to execute the business operation associated with the requested action.somepackage. This decoupling allows for more than one-to-one mapping between the user request and an action. you can declaratively associate as action forward through out the application.Action class. ActionForm form. The controller creates an instance of the Action class if one doesn¶t already exist. Each Action element is represented in memory by an instance of the org. The execute method signature in Action class has a return type org. The Action class also can perform other functions such as authorization.

String) getNamedDispatcher public RequestDispatcher getNamedDispatcher(java. HTML file.specific action mapping. The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.lang.lang. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response.lang.jsp" /> </global-forwards> public interface RequestDispatcher Defines an object that receives requests from the client and sends them to any resource (such as a servlet. which is used as a wrapper around a server resource located at a particular path or given by a particular name. but a servlet container can create RequestDispatcher objects to wrap any type of resource.a String specifying the pathname to the resource Returns: a RequestDispatcher object that acts as a wrapper for the resource at the specified path See Also: RequestDispatcher. getContext(java.jsp" /> <forward name="Failure" path="/someotherjsp.String name) Returns a RequestDispatcher object that acts as a wrapper for the named servlet. Parameters: path . <global-forwards> <forward name="Success" path="/action/somejsp. The servlet container creates the RequestDispatcher object. or JSP file) on the server. The resource can be dynamic or static. getRequestDispatcher public RequestDispatcher getRequestDispatcher(java. A servlet instance can determine its name using ServletConfig.a String specifying the name of a servlet to wrap Returns: .getServletName(). Parameters: name . This interface is intended to wrap servlets. Servlets (and JSP pages also) may be given names via server administration or via a web application deployment descriptor. This method returns null if the ServletContext cannot return a RequestDispatcher for any reason.

getServletName() Question: Why cant we overide create method in StatelessSessionBean? Answer: From the EJB Spec : . or simply manipulated as a stream of data. Struts instantiates each Action class once.. ServletConfig. A properly-designed application will exploit this further by routing related operations through a single Action. because they are not part of any particular object's state. Make sure that instance-level.lang. There are three exceptions in which serialization doesnot necessarily read and write to the stream. either as arguments in a method invocation from a client to a server or as return values from a method invocation.String). 3. locally defined state is serialized properly. Implement the Serializable interface. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. Serialization ignores static fields. There are four basic things you must do when you are making a class serializable.a RequestDispatcher object that acts as a wrapper for the named servlet See Also: RequestDispatcher. Question: Is struts threadsafe?Give an example? Answer: Struts is not only thread-safe but thread-dependant. Serialization is the mechanism used by RMI to pass objects between JVMs. The response to a request is handled by a light-weight Action object. The return type of a create method must be the enterprise Bean's remote interface type. Question: Can we Serialize static variable? Answer: Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes. Make sure that superclass state is serialized properly. stored to a file. This core strategy conserves resources and provides the best possible throughput. Base class fields are only handled if the base class itself is serializable. You should implement these methods and write the logic for customizing . This interface contains two methods namely readExternal and writeExternal. 3. The class should implement Externalizable interface. getContext(java. The home interface of a stateless session bean must have one create method that takes no arguments. and allows other requests to be threaded through the original object. Override equals( )and hashCode( ). 2. In the first section of this book. rather than an individual servlet. which can then be sent through a socket.A Session bean's home interface defines one or morecreate(. it is possible to have control over serialization process. These are 1. 4. They are: 1.) methods. 2. Transient fields..

perform() is the method called by the ActionServlet. Question: What are the various Struts tag libraries? Answer: Struts is very rich framework and it provides very good and user friendly way to develop web application forms.roseindia. (Source: http://www..For the application using tiles * Nested tag library . checkboxes. text boxes. See more at http://www. The resourcebundle. radio buttons etc. depending on which one is available.1.apache.xml is is an xml file used to configure tiles with the struts application. The org.For using the nested beans in the application Question: What do you understand by DispatchAction? Answer: DispatchAction is an action that comes with Struts 1. resourcebundle.xml is used to declare sets of validations that should be applied to Form Beans.action.1 or later. This is typically where your business logic resides.. the method signature changed in perform.properties file.net/struts/using-tiles-defs-xml. or at least the flow control to your JavaBeans and EJBs that handle your business logic.xml file? Answer: tiles-def.struts. the Struts v1. The file validation. that lets you combine Struts actions into one class. Question: What is the difference between perform() and execute() methods? Answer: Perform method is the method which was deprecated in the Struts Version 1.DispatchAction class allows multiple operation to mapped to the different functions in the same Action class. including forms.shtml.. Fpr more information please visit http://www.perform() is now deprecated.net/struts/address_struts_validator. Action.Tags to output standard HTML.com/catalog/javarmi/chapter/ch10.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action.xml file.x.Tags for accessing JavaBeans and their properties. .properties file is used to configure the message (error/ other messages) for the struts applications. * HTML tag library . each with their own method. Struts provide many tag libraries to ease the development of web applications. to support declarative exception handling. You can define the layout / header / footer / body content for your View. Now execute just throws Exception. iteration capabilities and flow management * Tiles or Template tag library . * Logic tag library . Action.roseindia..the serialization process .shtml. As we already mentioned. validation.html) Question: What are the uses of tiles-def.oreilly. In Struts 1. These tag libraries are: * Bean tag library . however.Tags for generating conditional output.

}</SCRIPT> <html:submit onclick="set('save'). Cool. But do you have to use a property named dispatch? No. The only catch is that the dispatch methods must use the same signature as perform. The Struts Dispatch Action [org.">SAVE</html:submit> <html:submit onclick="set('create'). String dispatch = myForm.">DELETE</html:submit> Then. ServletException { ... if ("create".dispatch. To convert an Action that was switching on a dispatch field to a DispatchAction.struts. HttpServletResponse response) throws IOException. ActionForm form.getDispatch(). ActionForm form.. it would be handy to also have them handled by the same Struts Action.value=target. in the Action you can setup different methods to handle the different operations. and RegDelete Actions. and invoke the indicated method. Since all of these operations are usually handled by the same JSP page. you simply need to create methods like this public ActionForward create( ActionMapping mapping. you don't. if ("save". since in practice you usually end up doing that anyway.">SAVE AS NEW</html:submitl> <html:submit onclick="set('delete). HttpServletResponse response) throws IOException. ServletException { ... HttpServletRequest request...For example: A package might include separate RegCreate. A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform.forms[0]. public ActionForward save( ActionMapping mapping. RegSave. So a mapping for our example might look like this: . The base perform method will check a dispatch field for you. which just perform different operations on the same RegBean object. but without messy branching logic.equals(dispatch)) { .equals(dispatch)) { . This is a very modest requirement.. and branch to one or the other depending on which value is passed in the dispatch field. The only other step is to specify the name of of the dispatch property as the "parameter" property of the action-mapping. HttpServletRequest request. <html:hidden property="dispatch" value="error"/> <SCRIPT>function set(target) {document.apache.actions] is designed to do exactly the same thing.

An action mapping can contain a reference to a form bean that the action can use. you would change the mapping to <action path="/reg/dispatch" type="app.action. Localization becomes virtually impossible. Here is the configuration example: .ActionServlet class or of a subclass of that class. But why use a JavaScript button in the first place? Why not use several buttons named "dispatch" and use a different value for each? You can.<action path="/reg/dispatch" type="app. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL.RegDispatch" name="regForm" scope="request" validate="true" parameter="o"/> Again. An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. Servlet. Question: What is Struts actions and action mappings? Answer: A Struts action is an instance of a subclass of an Action class. An action servlet is the primary component of the controller. in general. as in o=create. An action can perform tasks such as validating a user name and password.struts.apache. An action mapping is a configuration file entry that. Taglibs). and can additionally define a list of local forwards that is visible only to this action. Question: How Struts relates to J2EE? Answer: Struts framework is built on J2EE technologies (JSP.html). (Source: http://husted. This means if the page designers want to label the button something different.RegDispatch" name="regForm" scope="request" validate="true" parameter="dispatch"/> If you wanted to use the property "o" instead.reg. but the value of the button is also its label. which implements a portion of a Web application and whose perform or execute method returns a forward. Question: Can I setup Apache Struts to use multiple configuration files? Answer: Yes Struts can use multiple configuration files. they have to coordinate the Action programmer. An action servlet must be an instance of an org.reg. associates an action name with an action. but it is itself not part of the J2EE standard. very cool.com/struts/tips/002.

xml. The .<servlet> <servlet-name>banking</servlet-name> <servlet-class>org.apache. to be easily implemented using continuations-capable JavaScript. <bean:write> is a commonly used tag which enables the programmers to easily present the data. /WEB-INF/struts-help.ActionServlet </servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.html ) Question: What are the difference between <bean:message> and <bean:write>? Answer: <bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle. But there are some disadvantages of the Struts: a) High Learning Curve Struts requires lot of efforts to learn and master it.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> Question: What are the disadvantages of Struts? Answer: Struts is very robust framework and is being used extensively in the industry. It provides the ability to describe the order of Web pages that have to be sent to the client. Question: What is Struts Flow? Answer: Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow. benchmark and optimize.action. at any given point in time in an application. For any small project less experience developers could spend more time on learning the Struts. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. b) Harder to learn Struts are harder to learn.xml. <bean:write>: This tag is used to output property values from a bean. like multi-form wizards.net/struts-flow/index. Question: What is LookupDispatchAction? Answer: An abstract Action that dispatches to the subclass mapped execute method. /WEB-INF/struts-authentication.sourceforge. (Ref: http://struts.struts. This is useful in cases where an HTML form has multiple submit buttons with the same name.

View: JSP. ActionForward.apache. Question: What are the components of Struts? Answer: Struts is based on the MVC design pattern. Validation errors are either global to the entire ActionForm bean they are associated with.button name is specified by the parameter property of the corresponding ActionMapping. View and Controller.html). ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. a particular input field on the corresponding form). Example: <exception key="database. etc. ActionServlet etc.error. which contains a message key (to be looked up in an appropriate message resources database). or they are specific to a particular bean property (and. b) HTML Tags: HTML Tags provides tags for creating the view components like forms. ActionMapping. Question: What are Tag Libraries provided with Struts? Answer: Struts provides a number of tag libraries that helps to create view components easily. d) Nested Tags: Nested Tags helps to work with the nested context.jsp" . Question: What are difference between ActionErrors and ActionMessage? Answer: ActionMessage: A class that encapsulates messages. are part of View Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests. c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets.. and up to four placeholder arguments used for parametric substitution in the resulting message. Struts components can be categories into Model. These tag libraries are: a) Bean Tags: Bean Tags are used to access the beans and their properties. HTML etc.7/api/org/apache/struts/actions/LookupDispatchAction.2. Question: What are the core classes of the Struts Framework? Answer: Core classes of Struts Framework are ActionForm..xml or define the exception handling tags within <action>. http://struts. Model: Components like business logic / business processes and data are the part of Model. Question: How you will handle exceptions in Struts? Answer: In Struts you can handle the exceptions in two ways: a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config. (Ref. therefore. Each individual message is described by an ActionMessage object. buttons.org/1.duplicate" path="/UserExists. Action. Messages can be either global or they are specific to a particular bean property.</action> tag.

>: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive... Question: What do you understand by JSP Actions? Answer: JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine...account. <%@ include file = . . Answer: Both the tag includes the information from one page in another.. the changed content will not included in the output. There are six JSP Actions: <jsp:include/> <jsp:forward/> <jsp:plugin/> <jsp:usebean/> <jsp:setProperty/> <jsp:getProperty/> Question: What is the difference between <jsp:include page = .. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon. >: This is like a function call from one jsp to another jsp. >?.type="mybank. If the included file changed then the new content will be included in the output. This approach is useful to for modularizing the web application. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client... followed by the action name followed by one or more attribute parameters. In this case in the included file changes. > and <%@ include file = . The differences are as follows: <jsp:include page = . This approach is used when the code from one jsp file required to include in multiple jsp files.DuplicateUserException"/> b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.

println("Welcome").sendRedirect(url). and browser creates a new request to go the redirected page. print. or application.?. a) Embedding of Java code in HTML pages b) Platform independence c) Creation of database-driven Web applications d) Server-side programming capabilities Answer :. Question: Identify the advantages of JSP over Servlet. Find out your answer.Embedding of Java code in HTML pages Write the following code for a JSP page: <%@ page language = "java" %> <HTML> <HEAD><TITLE>RESULT PAGE</TITLE></HEAD> <BODY> <% PrintWriter print = request. > and response. The response.Question: What is the difference between <jsp:forward page = . The JSP implicit objects are: . a) A blank page will be displayed..sendRedirect kills the session variables. b) A page with the text Welcome is displayed c) An exception will be thrown because the implicit out object is not used d) An exception will be thrown because PrintWriter can be used in servlets only Answer :.getWriter(). %> </BODY> </HTML> Suppose you access this JSP file. These objects are created by Web container and contain information related to a particular request.. The target file can be an HTML file. Answer: The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. another JSP file. or a servlet. as long as it is in the same application context as the forwarding JSP file. sendRedirect sends HTTP temporary redirect response to the browser.A page with the text Welcome is displayed Question: What are implicit Objects available to the JSP Page? Answer: Implicit objects are the objects available to the JSP page. page.

Subtype of request The request triggering the execution of the JSP page.servlet. session javax.jsp.Throwable Accessible only from an error page.This file displays the user login screen --> and <!-. Variable Class Question: What are all the different scope values for the <jsp:useBean> tag? Answer:<jsp:useBean> tag is used to use any java object in the jsp page. Example: <!-.servlet.servlet. Syntax for the Expression tag is: <%= expression %> An expression tag contains a scripting language expression that is evaluated.jsp. The context for the JSP page.HttpSession The session object for the client.util.JspWriter The output stream.Date()%> .lang.PageContext manage the various scoped attributes.Date()).ServletContext components contained in the same application. and inserted where the expression appears in the JSP file. Provides a single API to pageContext javax.servlet. The following expression tag displays time on the output: <%=new java.servlet.ServletConfig Initialization information for the JSP page's servlet.util. Not typically response javax. Here are the scope values for <jsp:useBean> tag: a) page b) request c) session and d) application Question: What is JSP Output Comments? Answer: JSP Output Comments are the comments that can be viewed in the HTML source file. exception java.lang. javax.servlet.ServletRequest Subtype of The response to be returned to the client. Not typically used by JSP page authors.ServletResponse used by JSP page authors.Description The context for the JSP page's servlet and any Web application javax.Object current request. The instance of the JSP page's servlet processing the page java. config javax. converted to a String.toLocaleString() %> --> Question: What is expression in JSP? Answer: Expression tag is used to insert Java values directly into the output.servlet. out javax.This page was loaded on <%= (new java.http.

Example of hidden comment: <%-. A hidden comments does not appear in the generated output in the html. } %> <p>Values of Cnt are:</p> <p><%=getCount()%></p> </body> </html> Question: What is JSP Scriptlet? Answer: JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages.This is output comment --> Question: What is JSP declaration? Answer: JSP Decleratives are the JSP tag used to declare variables. You declare variables and functions in the declaration tag and can use anywhere in the JSP.getParameter("userName"). Example: <% //java codes String userName=null. return cnt. Java code written inside scriptlet executes every time the JSP is invoked. Declaratives are enclosed in the <%! %> tag and ends in semi-colon. .This is hidden comment --%> Example of output comment: <!-. private int getCount(){ //increment cnt and return the value cnt++. Here is the example of declaratives: <%@page contentType="text/html" %> <html> <body> <%! int cnt=0. Scriptlets begins with <% tag and ends with %> tag. while output comments appear in the generated output. These are hidden and output comments. userName=request.Question: What types of comments are available in the JSP? Answer: There are two types of comments are allowed in the JSP.

The jspInit() and jspDestroy() methods can be overridden within a JSP page. _jspService() method cann't be overridden.%> Question: What are the life-cycle methods of JSP? Answer: Life-cycle methods of the JSP are: a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method. and is called only once for a servlet instance. b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. . c) jspDestroy(): The container calls this when its instance is about to destroyed.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.