Spring MVC Exercise 1: Build and run "springMVCskeleton" sample application Acknowledgment: This exercise is based on the "Basic Spring Web MVC Example" tutorial from memestorm.com. Here’s a simple project, which doesn’t use all of Spring’s features, but serves as a good helloworld-like sample application. When you’re putting together a simple web application, you need a few essentials: • •
•
•
•
A dispatcher servlet , which will intercept incoming requests. A configuration that instructs the web container to route requests to the dispatcher servlet (ie. a servlet mapping) Controllers (the C in MVC) that can perform the business logic and route to particular views (the V) perhaps conveying information models (the M). A way for the dispatcher servlet to know which URLs to map to which controllers called a url mapping A way to determine, when a controller has done its job, how to get to the view - called a view resolver The simple application here, springMVCskeleton , doesn’t have a model at all, has a single controller (DispatchController ), and a single view (myview.jsp )
(1.1) Open, build, and run "springMVCskeleton" sample JSP application 0. Start NetBeans IDE. 1. Open springMVCskeleton NetBeans project. •
•
• •
•
Select File-> File->Open Open Project (Ctrl+Shift+O). (Ctrl+Shift+O) . The Open Project dialog box appears. Browse down to
/springmvc/samples directory. o Windows: If you unzipped the 4918_springmvc.zip file under C:\ directory, the directory to which you want to browse down should be C:\springmvc\samples. o Solaris/Linux: If you unzipped the 4918_springmvc.zip file under $HOME directory, the directory to which you want to browse down should be $HOME/springmvc/samples. springMVCskeleton.. Select springMVCskeleton Click Open Project Folder. Folder. Observe that the springMVCskeleton project node appears under Projects tab window.
2. Remove unresolved references and add Spring f ramework library files and commong logging library files to the project.
You probably don't need all the library files in this project. But for the sake of simplicity of the project, you are adding every library file to the project. • •
• •
•
•
•
•
•
•
•
•
•
• •
Right click spingMVCskeleton project and select Properties. Properties. Observe that Project Properties dialog box appears. Select Libraries under Categories on the left. Remove all broken references on the left by selecting them all and select Remove on the right. Browse down to /springmvc/lib/Springframework-1.2.9 directory. Select all the files and click Open button. Browse down to /springmvc/lib/dom4j1.6.1 directory. Select all the files and click Open button. Browse down to /springmvc/lib/logging-log4j-1.2.14 directory. Select all the files and click Open button. Browse down to /springmvc/lib/struts1.3.8 directory. Select all the files and click Open button. Browse down to /springmvc/lib/jstl directory. Select all the files and click Open button. Click OK button of the Project Properties dialog box to close it.
3. Build and run springMVCskeleton project. • • •
Right-click springMVCskeleton project and select Run Project. Project. Observe the output displayed in the Output window. (Figure-1.15below) Click this link. link.
Figure-1.15: Result is displayed
•
Observe the URL is http://localhost:8084/springMVCskeleton/send/actionName.. http://localhost:8084/springMVCskeleton/send/actionName
Figure-1.16: Result is displayed
(1.2) Studt the configuration files 1. web.xml The configuration in the web.xml specifies the following - Create the servlet for me, call it dispatch , and map all incoming URLs that start with send to the dispatch servlet. So for example, a URL such as http://.../skeleton1/ send /foobar /foobar would activate the dispatch servlet. foo log4jConfigLocation /WEB-INF/log4j.properties log4jRefreshInterval 1000 org.springframework.web.util.Log4jConfigListener org.springframework.web.context.ContextLoaderListener dispatch org.springframework.web.servlet.DispatcherServlet 1
dispatch /send/* index.jsp 2. dispatch-servlet.xml The rest of the configuration is done in the Spring MVC application configuration file. Spring automatically looks for it using the name of the servlet as a hint. Since our servlet is called dispatch , it looks for a file called dispatch-servlet.xml in your WEB-INF directory. This configuration file will have three bits to it: the controller(s), the url mapping and the view resolver. class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > dispatchController /WEB-INF/views/ .jsp 2. applicationContext.xml torm.B">
(1.3) Control flow 1. index.jsp is accessed Spring Skeleton Try accessing the controller by going to this ">this link. When you click the link in the index.jsp, the control goes to send/actionName send/actionName,, which will be handled by the DispatchServlet of the Spring MVC framework. 2. The actionName() method of the DispatchController class is now called to handle the request according to the configuration in the dispatch-servlet.xml dispatch-servlet.xml.. package com.memestorm.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import import import import import
org.apache.commons.logging.Log; org.apache.commons.logging.LogFactory; org.springframework.web.context.support.WebApplicationContextUtils; org.springframework.web.servlet.ModelAndView; org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.memestorm.B; public class DispatchController extends MultiActionController { public ModelAndView actionName(HttpServletRequest request, HttpServletResponse response) throws Exception { Log log = LogFactory.getLog(this.getClass()); log.info("Controller calling Earth. Come in Earth."); String msg = ((B) (WebApplicationContextUtils .getWebApplicationContext(getServletContext()).getBean("b"))) .getA().foo(); ModelAndView mav = new ModelAndView("myview"); mav.addObject("message", msg);
return mav; } } DispatchController.java The actionName() method selects myview as the View View to display. display. It also creates model object in which it added message. The viewResolver viewResolver selects /WEB-INF/views/myview.jsp as the view to display based on the configuration below. /WEB-INF/views/ .jsp Display the context senstive Javadoc on MultiActionContro ller. ller.
Trouble-shooting: If you don't see the Javadoc as shown above, you have not properly Trouble-shooting: configured the Javadoc of the Spring framework framework to the NetBeans. NetBeans. Please see here for instruction on how to configure Spring framework Javadoc to the NetBeans. 3. The /WEB-INF/views/myview.jsp is displayed.
<%@ page l anguage="java" contentType="text/html; contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <meta http-equiv= "Content-T "Content-Type" content="text/html; charset=ISO-8859-1"> Welcome! Hello, you're in myview.jsp!
The controller sent me some data, here i t is: <%=request.getAttribute("message") %> Note that it retrieves the value of the message attribute in the request scope and displays it.
Summary In this exercise, you learned how a controller is selected selected based on mapping configuration. You also learned learned how the controller selects a view.
return to the top
Exercise 2: Build and run "springMVCskeleton2" sample application The "springMVCskeleton2" sample application is a slightly modified version of the springMVCskeleton application. It uses the 2nd controller. controller.
(2.1) Open, build, and run "springMVCskeleton2" sample JSP application 1. Open springMVCskeleton2 NetBeans project. •
•
• •
Select File-> File->Open Open Project (Ctrl+Shift+O). (Ctrl+Shift+O) . The Open Project dialog box appears. Browse down to /springmvc/samples directory. Select springMVCskeleton2 springMVCskeleton2.. Click Open Project Folder. Folder. The springMVCskeleton2 project node appears under Projects tab window.
2. Resolve a reference problem as described above. above. 3. Build and run springMVCskeleton2 project. • • •
Right-click project node and select Run Project. Project. The browser gets displayed. Clicdk this link of the 2nd line.
•
Note that it is accessing http://localhost:8084/springMVCskeleton2/send/actionName2.
(2.2) Study the configuration files 1. dispatch-servlet.xml dispatchController2 dispatchController
/WEB-INF/views/ .jsp 2. web.xml foo log4jConfigLocation /WEB-INF/log4j.properties log4jRefreshInterval 1000 org.springframework.web.util.Log4jConfigListener org.springframework.web.context.ContextLoaderListener dispatch org.springframework.web.servlet.DispatcherServlet 1 dispatch
/send/* dispatch /send2/* index.jsp
(2.3) Control flow 1. index.jsp is displayed. Welcome. Try accessing the 1st controller by going to < a href="send/actionName href="send/actionName">this ">this link. Try accessing the 2nd controll er by going to this ">this link. When the link for send/actionName2 is clicked, the displatchController2 is used to handle the request according to the configuration below. dispatchController2 dispatchController 2. The actionName2() method of the com.memestorm.web.DispatchController2 class is invoked. package com.memestorm.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import import import import import
org.apache.commons.logging.Log; org.apache.commons.logging.LogFactory; org.springframework.web.context.support.WebApplicationContextUtils; org.springframework.web.servlet.ModelAndView; org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.memestorm.B; public class DispatchController2 extends MultiActionController { public ModelAndView actionName2(HttpServletRequest actionName2(HttpServletRequest request, HttpServletResponse response) throws Exception { Log log = LogFactory.getLog(this.getClass()); LogFactory.getLog(this.getClass()); log.info("Controller calling Earth. Come in Earth."); String msg = ((B) (WebApplicationContextUtils .getWebApplicationContext(getServletContext()).getBean("b"))) .getA().foo(); ModelAndView mav = new ModelAndView("myview2"); mav.addObject("message2", mav.addObject("message2", msg); return mav; } } The actionName2() method selects selects myview2 as the view to display. display. The viewResolver will select /WEB-INF/views/myview2.jsp as the page to display accoring to the configuration below. /WEB-INF/views/ .jsp 3. myview2.jsp is displayed <%@ page l anguage="java" contentType="text/html; contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<meta http-equiv= "Content-T "Content-Type" content="text/html; charset=ISO-8859-1"> Welcome! Hello, you're in myview2.jsp!
The controller sent me some data, here i t is: <%=request.getAttribute("message2") %>
Summary In this exercise, exercise, you learned how to use two different controllers.
return to the top
Exercise 3: Build and run "springMVCbanking" sample application Acknowledgment: This exercise is based on the "Spring Series, Part 3: Swing into Spring MVC" tutorial written by Naveen Balani.
(3.1) Open, build, and run "springMVCbanking" sample JSP application
1. Open springMVCbanking NetBeans project. •
•
• •
File->Open Open Project (Ctrl+Shift+O). (Ctrl+Shift+O) . The Open Project dialog box Select File-> appears. Browse down to /springmvc/samples directory. Select springMVCbanking springMVCbanking.. Click Open Project Folder. Folder. The springMVCbanking project node appears under Projects tab window.
2. Resolve a reference problem as described above. above. 3. Build and run springMVCbanking project.
•
Project. Right-click project and select Run Project. Observe that the login page is displayed. For User id field, enter admin admin.. For Password field, enter password password.. Click login button.
•
Observe that the Account Details page is displayed.
• • • •
(3.2) Study the configuration files 1. web.xml contextConfigLocation /WEB-INF/sampleBanking-services.xml context org.springframework.web.context.ContextLoaderServlet 1 sampleBankingServlet org.springframework.web.servlet.DispatcherServlet 2 sampleBankingServlet *.html index.jsp
/spring /WEB-INF/spring.tld 2. sampleBankingServlet-servlet.xml loginBankController
name="sessionForm"> true > loginCommand springexample.commands.LoginCommand login > accountdetail org.springframework.web.servlet.view.JstlView /jsp/
.jsp 3. simpleBanking-services.xml
(3.3) Control flow 1. index.jsp is displayed. <meta http-equiv= "Content-T "Content-Type" content="text/html; charset=ISO-8859-1"> Insert title here index.jsp The control is forwarded to login.html, which will be handled by DispatcherServlet DispatcherServlet.. Because of the following mapping configuration, it will be handled, it will be handled by the loginBankController.. loginBankController loginBankController
2. loginBankController's onSubmit() method is called. package springexample.contoller; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import import import import
springexample.commands.AccountDetail; springexample.commands.LoginCommand; springexample.services.AccountServices; springexample.services.AuthenticationService;
/** * @author naveenb */ public class LoginBankController extends SimpleFormController { public LoginBankController(){ } protected ModelAndView onSubmit(Object command) throws Exception{ LoginCommand loginCommand = (LoginCommand) command; authenticationService.authenticate(loginCommand); AccountDetail accountdetail = accountServices.getAccountSummary(loginCommand.getUserId()); return new ModelAndView(getSuccessView(),"accountdetail",accountdetail); } private AuthenticationService authenticationService; private AccountServices accountServices;
/** * @return Returns the accountServices. */ public AccountServices getAccountServices() { return accountServices; } /** * @param accountServices The accountServices to set. */ public void setAccountServices(AccountServices accountServices) { this.accountServices = accountServices; } /** * @return Returns the authenticationService. */ public AuthenticationService getAuthenticationService() { return authenticationService; } /** * @param authenticationService The authenticationService to set. */ public void setAuthenticationService( AuthenticationService authenticationService) {
this.authenticationService = authenticationService; } } Do the context senstive Javadoc on the S impleFormController class.
Based on the viewResolver configuration, the controller will select /jsp/accountdetail.jsp as the next view page. org.springframework.web.servlet.view.JstlView /jsp/ .jsp 3. /jsp/accountdetail.jsp is displayed. <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%> <%@ taglib prefix="spring" uri="/spring"%>
Login to Spring Example Account Banking Account Details