Register   Login   About   Study   Enterprise   Share
AI / Internet Technology University (AITU)
Fast Login - available after registration







|

Top Links: >> 80. Technology >> Internet Technology Summit Program >> 4. Web Apps Frameworks >> 4.4. Spring with Apache Maven and Data Service Frameworks >> 4.4.4.Data Service Framework and Troubleshooting
Current Topic: 4.4.4.2.How DataService works: Extracts from ItsBaseServlet
You have a privilege to create a quiz (QnA) related to this subject and obtain creativity score...
4.4.4.2.How DataService works: Extracts from ItsBaseServlet
Similar to the Dispatcher in the Spring framework, ItsBaseServlet extends HttpServlet and via the doPost() method passes control to a proper service-action class.

ItsBaseServlet also implements ServletContextListener and HttpSessionListener interfaces, which makes this class responsible for initialization of application parameters, when application starts and for handling events of creation and destroy of a user session.

/**
* This class inits configuration parameters defined in web.xml (ServletContext)
* Must implement contextInitialized() and contextDestroyed() as beginning and ending of the application
* Must implement sessionCreated() and sessionDestroyed() as beginning and ending of a user session
* Overrides doGet() and doPost() of the servlet and via the doPost()
* Reads request parameters, including action, and calls a proper the action class - service
* @author Jeff Zhuk
*/
public class ItsBaseServlet extends HttpServlet implements ServletContextListener, HttpSessionListener {
public static String appName; // the name of the project
public static String pathToDeploy; // path to the directory where the project is deployed
// protected to allow creation sub-classes that will inherit
// these hard-coded values can be instead defined in the web.xml
protected String actionPackageName = "com.its.webactions."; // the name of the package for actions
protected String jspPath = "/jsp"; // the path to the folder with Java Server Pages called from actions
protected String urlPattern = "Lookup"; // url pattern provided in the web.xml for servlets
// more parameters

/**
* contextInitialized() is called automatically by a Servlet container (Tomcat) on application start
* @param ServletContextEvent - passed automatically to the method
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext(); // context is a map with web.xml parameters
appName = context.getInitParameter("appName");
pathToDeploy = context.getInitParameter("pathToDeploy");
// retrieve more parameters


}
/**
* The contextDestroyed() method is called on application exit
* @param ServletContextEvent - passed automatically to the method
*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
// usually closing DB pool and other cleaning actions
}
/**
* The sessionCreated() method is called by a Servlet container when a user starts a session
* @param HttpSessionEvent - passed automatically to the method
*/
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO: usually store user data

}
/**
* The sessiontDestroyed() method is called when session expired (timeout) or session.invalidate() is called
* @param HttpSessionEvent - passed automatically to the method
*/
@Override
public void sessionDestroyed(HttpSessionEvent hse) {
// TODO: usually storing session data to a DB
}

The major part of the work done by this class is getting a request and passing control to a proper service-action class.
How this is done?

The request can come as a URL or link, which means via the HTTP GET method.
The request can also be sent as a web form, via the HTTP POST method.
Anyway, the program should parse the request, find parameters and pass control to a service.
This happen in the doPost() method.
If the request comes to the doGet() method as a URL, it will be directed still to the doPost() method for processing.


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost();
}
Was it clear so far?


In the doPost() method, the program is looking for the action parameter.
This is the naming agreement in the Data Service framework.
The action parameter defines the service to be called.
For example, in the URL http://itofthefuture.com/BASE/Lookup?action=content, the action value is content and according to the naming agreement, the name of the service class is ContentAction.

All action classes must implement the BaseAction interface.
This implementation allows us to use polymorphism and call any service universally with two lines:
BaseAction service = (BaseAction) Class.forName(actionPackageName + serviceName).newInstance();
// each service-action must implement the BaseAction with the run method
// run the service, which usually generates important data and returns the name of a jsp
String[] serviceResults = service.run(request, response);

The service will return the name of the JSP page to present the data generated by the service.

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// reading parameters
String action = request.getParameter("action"); // the first part of the service name
if (action != null) {
// the name of the service class, for example, for the "content" action must be ContentAction
String serviceName = action + "Action";
// make sure that it starts with the upper case
serviceName = serviceName.substring(0,1).toUpperCase() + serviceName.substring(1);
try {
// create a new service object
BaseAction service = (BaseAction) Class.forName(actionPackageName + serviceName).newInstance();
// each service-action must implement the BaseAction with the run method
// run the service, which usually generates important data and returns the name of a jsp
String[] serviceResults = service.run(request, response);
// check if the first String is the name of a JSP
String pageName = serviceResults[0];
if(pageName != null && pageName.endsWith(".jsp")) {
RequestDispatcher rd = request.getRequestDispatcher(jspPath + "/" + pageName);
rd.forward(request, response);
}
} catch (Exception e) {
System.out.println("ERROR: service="+serviceName+" e=" + e);
}
}
}
}


One pre-requisite is to create all service-classes as implementations of the BaseAction interface with the names that consist of the action name and the “Action” word at the end. So, the name of the service class, for example, for the "content" action, must be ContentAction.
Here is a very simple BaseAction interface, which requires to implement the run() method.

public interface BaseAction {
public String[] run(HttpServletRequest request, HttpServletResponse response) throws Exception;
}

Assignments:
1. In Eclipse create a new Dynamic Web project 4.4.4.2.ItsBaseServlet
2. In the project WebContent/WEB-INF – create the web.xml file
3. Add to the file context-param sections with the parameters that are listed in the source above.
4. Add to the file the listener and servlet sections, check the sample from the previous lesson.
5. In the project Java Resource – src add the package com.its.util
6. Add to the package the BaseAction interface.
7. Add to the package the class ItsBaseServlet and provide (copy/paste or better type) the content above, including doGet(), doPost() and other methods, (you might need to fix red lines if any)
8. Reminder: to import necessary libraries just press CTRL-SHIFT-O (character o, not zero)
9. Make sure that necessary jar files are in the WebContent/WEB-INF/lib (check in the previous projects)
10. Make sure that the project works locally and send the project sources as a zip file (src and WebContent with web.xml, jsp, js, css, and whatever sources needed) to dean@ituniversity.us.
11. Create 4 QnA and send to dean@ituniversity.us
| Check Your Progress | Propose QnA | Have a question or comments for open discussion?
<br/>/**
<br/> * This class inits configuration parameters defined in web.xml (ServletContext)
<br/> * Must implement contextInitialized() and contextDestroyed() as beginning and ending of the application
<br/> * Must implement sessionCreated() and sessionDestroyed() as beginning and ending of a user session
<br/> * Overrides doGet() and doPost() of the servlet and via the doPost()
<br/> * Reads request parameters, including action, and calls a proper the action class - service
<br/> * @author Jeff Zhuk
<br/> */
<br/>public class ItsBaseServlet extends HttpServlet implements ServletContextListener, HttpSessionListener {
<br/>	public static String appName; // the name of the project
<br/>	public static String pathToDeploy; // path to the directory where the project is deployed
<br/>	// protected to allow creation sub-classes that will inherit 
<br/>	// these hard-coded values can be instead defined in the web.xml
<br/>	protected String actionPackageName = "com.its.webactions."; // the name of the package for actions
<br/>	protected String jspPath = "/jsp"; // the path to the folder with Java Server Pages called from actions
<br/>	protected String urlPattern = "Lookup"; // url pattern provided in the web.xml for servlets
<br/>	// more parameters
<br/>	
<br/>	/**
<br/>	 * contextInitialized() is called automatically by a Servlet container (Tomcat) on application start
<br/>	 * @param ServletContextEvent - passed automatically to the method
<br/>	 */
<br/>	@Override
<br/>	public void contextInitialized(ServletContextEvent sce) {
<br/>		ServletContext context = sce.getServletContext(); // context is a map with web.xml parameters
<br/>		appName = context.getInitParameter("appName");
<br/>		pathToDeploy = context.getInitParameter("pathToDeploy");
<br/>		// retrieve more parameters
<br/>		
<br/>		
<br/>	}
<br/>	/**
<br/>	 * The contextDestroyed() method is called on application exit
<br/>	 * @param ServletContextEvent - passed automatically to the method
<br/>	 */
<br/>	@Override
<br/>	public void contextDestroyed(ServletContextEvent sce) {
<br/>		// usually closing DB pool and other cleaning actions
<br/>	}
<br/>	/**
<br/>	 * The sessionCreated() method is called by a Servlet container when a user starts a session
<br/>	 * @param HttpSessionEvent - passed automatically to the method
<br/>	 */
<br/>	@Override
<br/>	public void sessionCreated(HttpSessionEvent arg0) {
<br/>		// TODO: usually store user data
<br/>		
<br/>	}
<br/>	/**
<br/>	 * The sessiontDestroyed() method is called when session expired (timeout) or session.invalidate() is called
<br/>	 * @param HttpSessionEvent - passed automatically to the method
<br/>	 */
<br/>	@Override
<br/>	public void sessionDestroyed(HttpSessionEvent hse) {
<br/>		// TODO: usually storing session data to a DB
<br/>	}
<br/>

The major part of the work done by this class is getting a request and passing control to a proper service-action class.
How this is done?

The request can come as a URL or link, which means via the HTTP GET method.
The request can also be sent as a web form, via the HTTP POST method.
Anyway, the program should parse the request, find parameters and pass control to a service.
This happen in the doPost() method.
If the request comes to the doGet() method as a URL, it will be directed still to the doPost() method for processing.

<br/>	/**
<br/>	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
<br/>	 *      response)
<br/>	 */
<br/>	protected void doGet(HttpServletRequest request,
<br/>			HttpServletResponse response) throws ServletException, IOException {
<br/>             doPost();
<br/>        }
<br/>






Was it clear so far?



In the doPost() method, the program is looking for the action parameter.
This is the naming agreement in the Data Service framework.
The action parameter defines the service to be called.
For example, in the URL http://itofthefuture.com/BASE/Lookup?action=content, the action value is content and according to the naming agreement, the name of the service class is ContentAction.

All action classes must implement the BaseAction interface.
This implementation allows us to use polymorphism and call any service universally with two lines:
BaseAction service = (BaseAction) Class.forName(actionPackageName + serviceName).newInstance();
// each service-action must implement the BaseAction with the run method
// run the service, which usually generates important data and returns the name of a jsp
String[] serviceResults = service.run(request, response);

The service will return the name of the JSP page to present the data generated by the service.
<br/>	/**
<br/>	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
<br/>	 *      response)
<br/>	 */
<br/>	protected void doPost(HttpServletRequest request,
<br/>			HttpServletResponse response) throws ServletException, IOException {
<br/>		HttpSession session = request.getSession();
<br/>		// reading parameters
<br/>		String action = request.getParameter("action"); // the first part of the service name
<br/>		if (action != null) {
<br/>// the name of the service class, for example, for the "content" action must be ContentAction
<br/>			String serviceName = action + "Action"; 
<br/>			// make sure that it starts with the upper case
<br/>			serviceName = serviceName.substring(0,1).toUpperCase() + serviceName.substring(1);
<br/>			try {
<br/>				// create a new service object
<br/>				BaseAction service = (BaseAction) Class.forName(actionPackageName + serviceName).newInstance();
<br/>				// each service-action must implement the BaseAction with the run method
<br/>				// run the service, which usually generates important data and returns the name of a jsp
<br/>				String[] serviceResults = service.run(request, response);
<br/>				// check if the first String is the name of a JSP
<br/>				String pageName = serviceResults[0];
<br/>				if(pageName != null && pageName.endsWith(".jsp")) {
<br/>					RequestDispatcher rd = request.getRequestDispatcher(jspPath + "/" + pageName);
<br/>					rd.forward(request, response);	
<br/>				}
<br/>			} catch (Exception e) {
<br/>				System.out.println("ERROR: service="+serviceName+" e=" + e);
<br/>			}	
<br/>		}
<br/>	}
<br/>}	
<br/>


One pre-requisite is to create all service-classes as implementations of the BaseAction interface with the names that consist of the action name and the “Action” word at the end. So, the name of the service class, for example, for the "content" action, must be ContentAction.
Here is a very simple BaseAction interface, which requires to implement the run() method.
<br/>public interface BaseAction {
<br/>	public String[] run(HttpServletRequest request, HttpServletResponse response) throws Exception;
<br/>}
<br/>

Assignments:
1. In Eclipse create a new Dynamic Web project 4.4.4.2.ItsBaseServlet
2. In the project WebContent/WEB-INF – create the web.xml file
3. Add to the file context-param sections with the parameters that are listed in the source above.
4. Add to the file the listener and servlet sections, check the sample from the previous lesson.
5. In the project Java Resource – src add the package com.its.util
6. Add to the package the BaseAction interface.
7. Add to the package the class ItsBaseServlet and provide (copy/paste or better type) the content above, including doGet(), doPost() and other methods, (you might need to fix red lines if any)
8. Reminder: to import necessary libraries just press CTRL-SHIFT-O (character o, not zero)
9. Make sure that necessary jar files are in the WebContent/WEB-INF/lib (check in the previous projects)
10. Make sure that the project works locally and send the project sources as a zip file (src and WebContent with web.xml, jsp, js, css, and whatever sources needed) to dean@ituniversity.us.
11. Create 4 QnA and send to dean@ituniversity.us

| Check Your Progress | Propose QnA | Have a question or comments for open discussion?

Have a suggestion? - shoot an email
Looking for something special? - Talk to me
Read: IT of the future: AI and Semantic Cloud Architecture | Fixing Education
Do you want to move from theory to practice and become a magician? Learn and work with us at Internet Technology University (ITU) - JavaSchool.com.

Technology that we offer and How this works: English | Spanish | Russian | French

Internet Technology University | JavaSchool.com | Copyrights © Since 1997 | All Rights Reserved
Patents: US10956676, US7032006, US7774751, US7966093, US8051026, US8863234
Including conversational semantic decision support systems (CSDS) and bringing us closer to The message from 2040
Privacy Policy