Spring MVC – Controller Class Name Handler Mapping Example ”; Previous Next The following example shows how to use the Controller Class Name Handler Mapping using the Spring Web MVC framework. The ControllerClassNameHandlerMapping class is the convention-based handler mapping class, which maps the URL request(s) to the name of the controllers mentioned in the configuration. This class takes the Controller names and converts them to lower case with a leading “/”. For example − HelloController maps to “/hello*” URL. <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.mvc.support.ControllerClassNameHandlerMapping”/> <bean class = “com.tutorialspoint.HelloController” /> <bean class = “com.tutorialspoint.WelcomeController”/> </beans> For example, using 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. /Welcome.htm is requested where W is capital cased, DispatcherServlet will not find any controller and the server will throw 404 status error. To start with it, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Form based Web Application using 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 and 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 the 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.mvc.support.ControllerClassNameHandlerMapping”/> <bean class = “com.tutorialspoint.HelloController” /> <bean 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 the application, use the Export → WAR File option and save the TestWeb.war file in 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/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/Welcome.htm and we will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;
Category: springmvc
Spring MVC – Radiobutton
Spring MVC – RadioButton Example ”; Previous Next The following example show how to use RadioButton in forms using the Spring Web MVC framework. To start with it, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using 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; 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; } } UserController.java package com.tutorialspoint; import java.util.ArrayList; import java.util.List; 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()); 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; } } Here, 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 colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:radiobutton /> tag to render HTML radiobutton. <form:radiobutton path = “gender” value = “M” label = “Male” /> <form:radiobutton path = “gender” value = “F” label = “Female” /> It will render following HTML content. <input id = “gender1” name = “gender” type = “radio” value = “M” checked = “checked”/><label for = “gender1”>Male</label> <input id = “gender2” name = “gender” type = “radio” value = “F”/><label for = “gender2″>Female</label> 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> </table> </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 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. Try a URL – http://localhost:8080/HelloWeb/user and we will see the following screen, if everything is fine with your Spring Web Application. After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Home
Spring MVC Tutorial PDF Version Quick Guide Resources Job Search Discussion 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 has been written based on Spring Framework version 5.1.34 released in Dec 2021. Audience This tutorial is designed for Java programmers with a need to understand the Spring MVC framework in detail along with its architecture and actual usage. This tutorial will bring you at intermediate level of expertise from where you can take yourself at higher level of expertise. Prerequisites Before proceeding with this tutorial you should have a good understanding of Java programming language. A basic understanding of Eclipse IDE is also required because all the examples have been compiled using Eclipse IDE. Questions and Answers Spring Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations – Study Spring Questions and Answers Print Page Previous Next Advertisements ”;
Spring MVC – Generate XML
Spring MVC – Generate XML Example ”; Previous Next The following example shows how to generate XML using the Spring Web MVC Framework. To begin 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 TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes User and UserController under the com.tutorialspointpackage. 3 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; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = “user”) public class User { private String name; private int id; public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public int getId() { return id; } @XmlElement public void setId(int id) { this.id = id; } } UserController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(“/user”) public class UserController { @RequestMapping(value=”{name}”, method = RequestMethod.GET) public @ResponseBody User getUser(@PathVariable String name) { User user = new User(); user.setName(name); user.setId(1); return user; } } 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” xmlns:mvc = “http://www.springframework.org/schema/mvc” 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <mvc:annotation-driven /> </beans> Here, we have created an XML Mapped POJO User and in the UserController, we have returned the User. Spring automatically handles the XML conversion based on RequestMapping. 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 TestWeb.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. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen. Print Page Previous Next Advertisements ”;
Spring MVC – Checkbox
Spring MVC – Checkbox Example ”; Previous Next The following example describes how to use a Single Checkbox in forms using the Spring Web MVC framework. 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 HelloWeb under a package com.tutorialspointas explained in the Spring MVC – Hello World Example chapter. 2 Create Java classes User, UserController under the com.tutorialspointpackage. 3 Create a view files user.jsp, users.jsp under 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; 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; } } UserController.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 UserController { @RequestMapping(value = “/user”, method = RequestMethod.GET) public ModelAndView user() { return new ModelAndView(“user”, “command”, new User()); } @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()); return “users”; } } 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 colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:checkboxes /> tag to render an HTML checkbox box. For example − <form:checkbox path=”receivePaper” /> It will render following HTML content. <input id=”receivePaper1″ name = “receivePaper” type = “checkbox” value = “true”/> <input type = “hidden” name = “_receivePaper” value = “on”/> 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> </table> </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. 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. We will see the following screen if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;
Spring – Questions and Answers ”; Previous Next Spring Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Spring Interview Questions This section provides a huge collection of Spring Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Spring Online Quiz This section provides a great collection of Spring Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Spring Online Test If you are preparing to appear for a Java and Spring Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Spring Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;