Spring MVC – Hello World Example

Spring MVC – Hello World Example ”; Previous Next The following example shows how to write a simple web based Hello World application using the Spring MVC Framework. To start with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Web Application using the Spring Web Framework. Step Description 1 Create a Dynamic Web Project with a name HelloWeb and create a package com.tutorialspoint under the src folder in the created project. 2 Drag and drop the following Spring and other libraries into the folder WebContent/WEB-INF/lib.. 3 Create a Java class HelloController under the com.tutorialspoint package. 4 Create Spring configuration files web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder. 5 Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view file hello.jsp under this sub-folder. 6 The final step is to create the content of the source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } web.xml <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> HelloWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> hello.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> Following is the list of Spring and other libraries to be included in the web application. We can just drag these files and drop them in – WebContent/WEB-INF/lib folder. servlet-api-x.y.z.jar commons-logging-x.y.z.jar spring-aop-x.y.z.jar spring-beans-x.y.z.jar spring-context-x.y.z.jar spring-core-x.y.z.jar spring-expression-x.y.z.jar spring-webmvc-x.y.z.jar spring-web-x.y.z.jar Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now, try to access the URL − http://localhost:8080/HelloWeb/hello. If everything is fine with the Spring Web Application, we will see the following screen. You should note that in the given URL, HelloWeb is the application name and hello is the virtual subfolder, which we have mentioned in our controller using @RequestMapping(“/hello”). You can use direct root while mapping your URL using @RequestMapping(“/”), in this case you can access the same page using short URL http://localhost:8080/HelloWeb/, but it is advised to have different functionalities under different folders. Print Page Previous Next Advertisements ”;

Spring MVC – Static Pages

Spring MVC – Static Pages Example ”; Previous Next The following example shows how to write a simple web based application using Spring MVC Framework, which can access static pages along with dynamic pages with the help of a <mvc:resources> tag. To begin with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class WebController under the com.tutorialspoint package. 3 Create a static file final.htm under jsp sub-folder. 4 Update the Spring configuration file HelloWeb-servlet.xml under the WebContent/WEB-INF folder as shown below. 5 The final step is to create the content of the source and configuration files and export the application, which is explained below. WebController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WebController { @RequestMapping(value = “/index”, method = RequestMethod.GET) public String index() { return “index”; } @RequestMapping(value = “/staticPage”, method = RequestMethod.GET) public String redirect() { return “redirect:/pages/final.htm”; } } HelloWeb-servlet.xml <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:xsi = ” http://www.w3.org/2001/XMLSchema-instance” xmlns:context = “http://www.springframework.org/schema/context” xmlns:mvc = “http://www.springframework.org/schema/mvc” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean id = “viewResolver” class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> <mvc:resources mapping = “/pages/**” location = “/WEB-INF/pages/” /> <mvc:annotation-driven/> </beans> Here, the <mvc:resources…./> tag is being used to map static pages. The mapping attribute must be an Ant pattern that specifies the URL pattern of an http requests. The location attribute must specify one or more valid resource directory locations having static pages including images, stylesheets, JavaScript, and other static content. Multiple resource locations may be specified using a comma-separated list of values. Following is the content of Spring view file WEB-INF/jsp/index.jsp. This will be a landing page; this page will send a request to access the staticPage service method, which will redirect this request to a static page available in WEB-INF/pages folder. index.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring Landing Page</title> </head> <body> <h2>Spring Landing Pag</h2> <p>Click below button to get a simple HTML page</p> <form:form method = “GET” action = “/HelloWeb/staticPage”> <table> <tr> <td> <input type = “submit” value = “Get HTML Page”/> </td> </tr> </table> </form:form> </body> </html> final.htm <html> <head> <title>Spring Static Page</title> </head> <body> <h2>A simple HTML page</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now try to access the URL – http://localhost:8080/HelloWeb/index. If everything is fine with the Spring Web Application, we will see the following screen. Click on “Get HTML Page” button to access a static page mentioned in the staticPage service method. If everything is fine with your Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;

Spring MVC – Overview

Spring – MVC Framework Overview ”; Previous Next The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The Model encapsulates the application data and in general, they will consist of POJO. The View is responsible for rendering the model data and in general, it generates HTML output that the client”s browser can interpret. The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering. The DispatcherServlet The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration. Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet − After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers. All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications. Required Configuration We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet − <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> </web-app> The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application”s WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml. Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet. If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows − <web-app…> <!——– DispatcherServlet definition goes here—–> …. <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application”s WebContent/WEB-INF directory. <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> Following are some important points about HelloWeb-servlet.xml file − The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope. The <context:component-scan…> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc. The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp. Let us now understand how to create the actual components i.e., Controller, Model and View. Defining a Controller The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller”s default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL. We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows − @Controller public class HelloController{ @RequestMapping(value = “/hello”, method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request. Following are some important points to be noted regarding the controller defined above − You will define the required business logic inside a service method. You can call another method inside this method as per the requirement. Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute “message”. A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns “hello” as the logical view name. Creating JSP Views Spring MVC supports many types of views for different presentation technologies. These include – JSPs, HTML,

Spring MVC – Useful Resources

Spring MVC – Useful Resources ”; Previous Next The following resources contain additional information on Spring MVC. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Learn ASP.Net MVC and Entity Framework (Database First) Most Popular 20 Lectures 5 hours Trevoir Williams More Detail ASP.Net Core MVC Training Course 53 Lectures 3 hours Skillbakery More Detail Spring MVC Essentials: A Primary Course for Java Spring MVC 25 Lectures 3.5 hours TELCOMA Global More Detail .Net Developer Course Using ASP.NET MVC Core, C#, OOP, SQL Entity Framework Best Seller 89 Lectures 7.5 hours Mustafa Radaideh More Detail Spring MVC With Spring Boot and Project 94 Lectures 8 hours Packt Publishing More Detail ASP.NET Core MVC Webforms – A Project method from scratch 70 Lectures 6 hours Metla Sudha Sekhar More Detail Print Page Previous Next Advertisements ”;

Spring MVC – Dropdown

Spring MVC – Dropdown Example ”; Previous Next The following example describes how to use Dropdown in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes User, UserController under the com.tutorialspointpackage. 3 Create view files user.jsp, users.jsp under the jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. User.java package com.tutorialspoint; public class User { private String username; private String password; private String address; private boolean receivePaper; private String [] favoriteFrameworks; private String gender; private String favoriteNumber; private String country; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public boolean isReceivePaper() { return receivePaper; } public void setReceivePaper(boolean receivePaper) { this.receivePaper = receivePaper; } public String[] getFavoriteFrameworks() { return favoriteFrameworks; } public void setFavoriteFrameworks(String[] favoriteFrameworks) { this.favoriteFrameworks = favoriteFrameworks; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getFavoriteNumber() { return favoriteNumber; } public void setFavoriteNumber(String favoriteNumber) { this.favoriteNumber = favoriteNumber; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } UserController.java package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.ui.ModelMap; @Controller public class UserController { @RequestMapping(value = “/user”, method = RequestMethod.GET) public ModelAndView user() { User user = new User(); user.setFavoriteFrameworks((new String []{“Spring MVC”,”Struts 2″})); user.setGender(“M”); ModelAndView modelAndView = new ModelAndView(“user”, “command”, user); return modelAndView; } @RequestMapping(value = “/addUser”, method = RequestMethod.POST) public String addUser(@ModelAttribute(“SpringWeb”)User user, ModelMap model) { model.addAttribute(“username”, user.getUsername()); model.addAttribute(“password”, user.getPassword()); model.addAttribute(“address”, user.getAddress()); model.addAttribute(“receivePaper”, user.isReceivePaper()); model.addAttribute(“favoriteFrameworks”, user.getFavoriteFrameworks()); model.addAttribute(“gender”, user.getGender()); model.addAttribute(“favoriteNumber”, user.getFavoriteNumber()); model.addAttribute(“country”, user.getCountry()); return “users”; } @ModelAttribute(“webFrameworkList”) public List<String> getWebFrameworkList() { List<String> webFrameworkList = new ArrayList<String>(); webFrameworkList.add(“Spring MVC”); webFrameworkList.add(“Struts 1”); webFrameworkList.add(“Struts 2”); webFrameworkList.add(“Apache Wicket”); return webFrameworkList; } @ModelAttribute(“numbersList”) public List<String> getNumbersList() { List<String> numbersList = new ArrayList<String>(); numbersList.add(“1”); numbersList.add(“2”); numbersList.add(“3”); numbersList.add(“4”); return numbersList; } @ModelAttribute(“countryList”) public Map<String, String> getCountryList() { Map<String, String> countryList = new HashMap<String, String>(); countryList.put(“US”, “United States”); countryList.put(“CH”, “China”); countryList.put(“SG”, “Singapore”); countryList.put(“MY”, “Malaysia”); return countryList; } } Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name “command”, because the spring framework expects an object with name “command”, if you are using <form:form> tags in your JSP file. So when the user() method is called, it returns the user.jsp view. The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the “users” view will be returned from the service method, which will result in rendering the users.jsp. user.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>User Information</h2> <form:form method = “POST” action = “/HelloWeb/addUser”> <table> <tr> <td><form:label path = “username”>User Name</form:label></td> <td><form:input path = “username” /></td> </tr> <tr> <td><form:label path = “password”>Age</form:label></td> <td><form:password path = “password” /></td> </tr> <tr> <td><form:label path = “address”>Address</form:label></td> <td><form:textarea path = “address” rows = “5” cols = “30” /></td> </tr> <tr> <td><form:label path = “receivePaper”>Subscribe Newsletter</form:label></td> <td><form:checkbox path = “receivePaper” /></td> </tr> <tr> <td><form:label path = “favoriteFrameworks”>Favorite Web Frameworks</form:label></td> <td><form:checkboxes items = “${webFrameworkList}” path = “favoriteFrameworks” /></td> </tr> <tr> <td><form:label path = “gender”>Gender</form:label></td> <td> <form:radiobutton path = “gender” value = “M” label = “Male” /> <form:radiobutton path = “gender” value = “F” label = “Female” /> </td> </tr> <tr> <td><form:label path = “favoriteNumber”>Favorite Number</form:label></td> <td> <form:radiobuttons path = “favoriteNumber” items = “${numbersList}” /> </td> </tr> <tr> <td><form:label path = “country”>Country</form:label></td> <td> <form:select path = “country”> <form:option value = “NONE” label = “Select”/> <form:options items = “${countryList}” /> </form:select> </td> </tr> <tr> <td colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:select /> , <form:option /> and <form:options /> tags to render HTML select. For example − <form:select path = “country”> <form:option value = “NONE” label = “Select”/> <form:options items = “${countryList}” /> </form:select> It will render following HTML content. <select id = “country” name = “country”> <option value = “NONE”>Select</option> <option value = “US”>United States</option> <option value = “CH”>China</option> <option value = “MY”>Malaysia</option> <option value = “SG”>Singapore</option> </select> users.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>Submitted User Information</h2> <table> <tr> <td>Username</td> <td>${username}</td> </tr> <tr> <td>Password</td> <td>${password}</td> </tr> <tr> <td>Address</td> <td>${address}</td> </tr> <tr> <td>Subscribed to Newsletter</td> <td>${receivePaper}</td> </tr> <tr> <td>Favorite Web Frameworks</td> <td> <% String[] favoriteFrameworks = (String[])request.getAttribute(“favoriteFrameworks”); for(String framework: favoriteFrameworks) { out.println(framework); } %></td> </tr> <tr> <td>Gender</td> <td>${(gender==”M”? “Male” : “Female”)}</td> </tr> <tr> <td>Favourite Number</td> <td>${favoriteNumber}</td> </tr> <tr> <td>Country</td> <td>${country}</td> </tr> </table> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use the Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now, start the Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/user and we will see the following screen, if everything is fine with the Spring Web Application. After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with your Spring Web Application. Print Page Previous Next Advertisements ”;

Spring MVC – Upload

Spring MVC – File Upload Example ”; Previous Next The following example shows how to use File Upload Control in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes FileModel, FileUploadController under the com.tutorialspoint package. 3 Create view files fileUpload.jsp, success.jsp under the jsp sub-folder. 4 Create a folder temp under the WebContent sub-folder. 5 Download Apache Commons FileUpload library commons-fileupload.jar and Apache Commons IO library commons-io.jar. Put them in your CLASSPATH. 6 The final step is to create the content of the source and configuration files and export the application as explained below. FileModel.java package com.tutorialspoint; import org.springframework.web.multipart.MultipartFile; public class FileModel { private MultipartFile file; public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } } FileUploadController.java package com.tutorialspoint; import java.io.File; import java.io.IOException; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.FileCopyUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class FileUploadController { @Autowired ServletContext context; @RequestMapping(value = “/fileUploadPage”, method = RequestMethod.GET) public ModelAndView fileUploadPage() { FileModel file = new FileModel(); ModelAndView modelAndView = new ModelAndView(“fileUpload”, “command”, file); return modelAndView; } @RequestMapping(value=”/fileUploadPage”, method = RequestMethod.POST) public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException { if (result.hasErrors()) { System.out.println(“validation errors”); return “fileUploadPage”; } else { System.out.println(“Fetching file”); MultipartFile multipartFile = file.getFile(); String uploadPath = context.getRealPath(“”) + File.separator + “temp” + File.separator; //Now do something with file… FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename())); String fileName = multipartFile.getOriginalFilename(); model.addAttribute(“fileName”, fileName); return “success”; } } } HelloWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> <bean id = “multipartResolver” class = “org.springframework.web.multipart.commons.CommonsMultipartResolver” /> </beans> Here, for the first service method fileUploadPage(), we have passed a blank FileModel object in the ModelAndView object with name “command”, because the spring framework expects an object with name “command”, if you are using <form:form> tags in your JSP file. So, when fileUploadPage() method is called, it returns fileUpload.jsp view. The second service method fileUpload() will be called against a POST method on the HelloWeb/fileUploadPage URL. You will prepare the file to be uploaded based on the submitted information. Finally, a “success” view will be returned from the service method, which will result in rendering success.jsp. fileUpload.jsp <%@ page contentType=”text/html; charset = UTF-8″ %> <%@ taglib prefix = “form” uri = “http://www.springframework.org/tags/form”%> <html> <head> <title>File Upload Example</title> </head> <body> <form:form method = “POST” modelAttribute = “fileUpload” enctype = “multipart/form-data”> Please select a file to upload : <input type = “file” name = “file” /> <input type = “submit” value = “upload” /> </form:form> </body> </html> Here, we are using modelAttribute attribute with value=”fileUpload” to map the file Upload control with the server model. success.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>File Upload Example</title> </head> <body> FileName : lt;b> ${fileName} </b> – Uploaded Successfully. </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in the Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL– http://localhost:8080/HelloWeb/fileUploadPage and we will see the following screen, if everything is fine with the Spring Web Application. After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;

Bean Name Url Handler Mapping

Spring MVC – Bean Name Url Handler Mapping Example ”; Previous Next The following example shows how to use Bean Name URL Handler Mapping using the Spring Web MVC Framework. The BeanNameUrlHandlerMapping class is the default handler mapping class, which maps the URL request(s) to the name of the beans mentioned in the configuration. <beans> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> <bean class = “org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”/> <bean name = “/helloWorld.htm” class = “com.tutorialspoint.HelloController” /> <bean name = “/hello*” class = “com.tutorialspoint.HelloController” /> <bean name = “/welcome.htm” class = “com.tutorialspoint.WelcomeController”/> </beans> For example, using the above configuration, if URI /helloWorld.htm or /hello{any letter}.htm is requested, DispatcherServlet will forward the request to the HelloController. /welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController. /welcome1.htm is requested, DispatcherServlet will not find any controller and server will throw 404 status error. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes HelloController, WelcomeController under the com.tutorialspoint package. 3 Create view files hello.jsp, welcome.jsp under the jsp sub-folder. 4 The final step is to create the content of all source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class HelloController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“hello”); model.addObject(“message”, “Hello World!”); return model; } } WelcomeController.java package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class WelcomeController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“welcome”); model.addObject(“message”, “Welcome!”); return model; } } TestWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> <bean class = “org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”/> <bean name = “/helloWorld.htm” class = “com.tutorialspoint.HelloController” /> <bean name = “/hello*” class = “com.tutorialspoint.HelloController” /> <bean name = “/welcome.htm” class = “com.tutorialspoint.WelcomeController”/> </beans> hello.jsp <%@ page contentType = “text/html; charset = UTF-8” %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> welcome.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Welcome</title> </head> <body> <h2>${message}</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in the Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder by using a standard browser. Try a URL − http://localhost:8080/TestWeb/helloWorld.htm and we will see the following screen, if everything is fine with the Spring Web Application. Try a URL − http://localhost:8080/TestWeb/hello.htm and we will see the following screen, if everything is fine with the Spring Web Application. Try a URL http://localhost:8080/TestWeb/welcome.htm and we will see the following screen, if everything is fine with the Spring Web Application. Try a URL http://localhost:8080/TestWeb/welcome1.htm and we will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;

Spring MVC – Form Handling

Spring MVC – Form Handling Example ”; Previous Next The following example shows how to write a simple web based Hello World application using the Spring MVC Framework. To start with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes Student, StudentController under the com.tutorialspoint package. 3 Create view files student.jsp, result.jsp under the jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. Student.java package com.tutorialspoint; public class Student { private Integer age; private String name; private Integer id; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } } StudentController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.ui.ModelMap; @Controller public class StudentController { @RequestMapping(value = “/student”, method = RequestMethod.GET) public ModelAndView student() { return new ModelAndView(“student”, “command”, new Student()); } @RequestMapping(value = “/addStudent”, method = RequestMethod.POST) public String addStudent(@ModelAttribute(“SpringWeb”)Student student, ModelMap model) { model.addAttribute(“name”, student.getName()); model.addAttribute(“age”, student.getAge()); model.addAttribute(“id”, student.getId()); return “result”; } } Here, the first service method student(), we have passed a blank Studentobject in the ModelAndView object with name “command”. This is done because the spring framework expects an object with name “command”, if we use <form:form> tags in the JSP file. So, when the student() method is called, it returns student.jsp view. The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a “result” view will be returned from the service method, which will result in rendering result.jsp. student.jsp <%@taglib uri=”http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>Student Information</h2> <form:form method = “POST” action = “/HelloWeb/addStudent”> <table> <tr> <td><form:label path = “name”>Name</form:label></td> <td><form:input path = “name” /></td> </tr> <tr> <td><form:label path = “age”>Age</form:label></td> <td><form:input path = “age” /></td> </tr> <tr> <td><form:label path = “id”>id</form:label></td> <td><form:input path = “id” /></td> </tr> <tr> <td colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> result.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>Submitted Student Information</h2> <table> <tr> <td>Name</td> <td>${name}</td> </tr> <tr> <td>Age</td> <td>${age}</td> </tr> <tr> <td>ID</td> <td>${id}</td> </tr> </table> </body> </html> Once we are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the SpringWeb.war file in Tomcat”s webapps folder. Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Now, try a URL– http://localhost:8080/SpringWeb/student and you should see the following screen if everything is fine with the Spring Web Application. After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with your Spring Web Application. Print Page Previous Next Advertisements ”;

Spring MVC – Discussion

Discuss Spring MVC ”; Previous Next Spring MVC Framework is an open source Java platform that provides comprehensive infrastructure support for developing robust Java based Web applications very easily and very rapidly. Spring Framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. This tutorial is written based on the Spring Framework Version 4.1.6 released in March 2015 Print Page Previous Next Advertisements ”;

Spring MVC – Quick Guide

Spring MVC – Quick Guide ”; Previous Next Spring – MVC Framework Overview The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The Model encapsulates the application data and in general, they will consist of POJO. The View is responsible for rendering the model data and in general, it generates HTML output that the client”s browser can interpret. The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering. The DispatcherServlet The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration. Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet − After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers. All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications. Required Configuration We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet − <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> </web-app> The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application”s WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml. Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet. If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows − <web-app…> <!——– DispatcherServlet definition goes here—–> …. <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application”s WebContent/WEB-INF directory. <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> Following are some important points about HelloWeb-servlet.xml file − The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope. The <context:component-scan…> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc. The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp. Let us now understand how to create the actual components i.e., Controller, Model and View. Defining a Controller The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller”s default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL. We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows − @Controller public class HelloController{ @RequestMapping(value = “/hello”, method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request. Following are some important points to be noted regarding the controller defined above − You will define the required business logic inside a service method. You can call another method inside this method as per the requirement. Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute “message”. A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns “hello” as the logical view name. Creating JSP Views Spring MVC supports many types of views for different presentation technologies.