Spring MVC – Generate JSON Example ”; Previous Next The following example shows how to generate JSON 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 TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java classes User, UserController under the com.tutorialspoint package. 3 Download Jackson libraries Jackson Core, Jackson Databind and Jackson Annotations from maven repository page. Put them in your CLASSPATH. 4 The final step is to create the content of all the source and configuration files and export the application as explained below. User.java package com.tutorialspoint; public class User { private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } 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 a Simple POJO User and in UserController we have returned the User. Spring automatically handles the JSON conversion based on RequestMapping and Jackson jar present in the classpath. 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 ”;
Category: springmvc
Spring MVC – Generate PDF
Spring MVC – Generate PDF Example ”; Previous Next The following example shows how to generate a PDF 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 TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes UserPDFView and PDFController under the com.tutorialspoint package. 3 Download the iText library − iText from the maven repository page. Put it in your CLASSPATH. 4 The final step is to create the content of the source and configuration files and export the application as explained below. PDFController.java package com.tutorialspoint; import java.util.HashMap; import java.util.Map; 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 PDFController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { //user data Map<String,String> userData = new HashMap<String,String>(); userData.put(“1”, “Mahesh”); userData.put(“2”, “Suresh”); userData.put(“3”, “Ramesh”); userData.put(“4”, “Naresh”); return new ModelAndView(“UserSummary”,”userData”,userData); } } UserExcelView.java package com.tutorialspoint; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.document.AbstractPdfView; import com.lowagie.text.Document; import com.lowagie.text.Table; import com.lowagie.text.pdf.PdfWriter; public class UserPDFView extends AbstractPdfView { protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String,String> userData = (Map<String,String>) model.get(“userData”); Table table = new Table(2); table.addCell(“Roll No”); table.addCell(“Name”); for (Map.Entry<String, String> entry : userData.entrySet()) { table.addCell(entry.getKey()); table.addCell(entry.getValue()); } document.add(table); } } 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”> <bean class = “org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping” /> <bean class = “com.tutorialspoint.PDFController” /> <bean class = “org.springframework.web.servlet.view.XmlViewResolver”> <property name = “location”> <value>/WEB-INF/views.xml</value> </property> </bean> </beans> views.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 id = “UserSummary” class = “com.tutorialspoint.UserPDFView”></bean> </beans> Here, we have created a PDFController and UserPDFView. iText library deals with the PDF file formats and will convert the data to a PDF document. 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 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. We can also try the following URL − http://localhost:8080/TestWeb/pdf and if all goes as planned, we will see the following screen. Print Page Previous Next Advertisements ”;
Spring MVC – Resource Bundle View Resolver Example ”; Previous Next The ResourceBundleViewResolver is used to resolve the view names using view beans defined in the properties file. The following example shows how to use the ResourceBundleViewResolver using the Spring Web MVC Framework. TestWeb-servlet.xml <bean class = “org.springframework.web.servlet.view.ResourceBundleViewResolver”> <property name = “basename” value = “views” /> </bean> Here, the basename refers to name of the resource bundle, which carries the views. The default name of the resource bundle is views.properties, which can be overridden using the basename property. views.properties hello.(class) = org.springframework.web.servlet.view.JstlView hello.url = /WEB-INF/jsp/hello.jsp For example, using the above configuration, if URI − /hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the views.properties. Here, “hello” is the view name to be matched. Whereas, class refers to the view type and URL is the view”s location. 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 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 a Java class HelloController under the com.tutorialspointpackage. 3 Create a view file hello.jsp under the jsp sub-folder. 4 Create a properties file views.properties under the src folder. 5 Download JSTL library jstl.jar. Put it 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. 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”; } } 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”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.ResourceBundleViewResolver”> <property name = “basename” value = “views” /> </bean> </beans> views.properties hello.(class) = org.springframework.web.servlet.view.JstlView hello.url = /WEB-INF/jsp/hello.jsp hello.jsp <%@ page contentType=”text/html; charset=UTF-8″ %> <html> <head> <title>Hello World</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 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 the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;
Spring MVC – Using log4j
Spring MVC – Integrate LOG4J Example ”; Previous Next The following example shows how to integrate LOG4J 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 the name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class HelloController under the com.tutorialspointpackage. 3 Download the log4j library LOG4J from the maven repository page. Put it in your CLASSPATH. 4 Create a log4j.properties under the SRC folder. 5 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.apache.log4j.Logger; 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{ private static final Logger LOGGER = Logger.getLogger(HelloController.class); @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { LOGGER.info(“printHello started.”); //logs debug message if(LOGGER.isDebugEnabled()){ LOGGER.debug(“Inside: printHello”); } //logs exception LOGGER.error(“Logging a sample exception”, new Exception(“Testing”)); model.addAttribute(“message”, “Hello Spring MVC Framework!”); LOGGER.info(“printHello ended.”); return “hello”; } } log4j.properties # Root logger option log4j.rootLogger = DEBUG, stdout, file # Redirect log messages to console log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n # Redirect log messages to a log file log4j.appender.file = org.apache.log4j.RollingFileAppender #outputs to Tomcat home log4j.appender.file.File = ${catalina.home}/logs/myapp.log log4j.appender.file.MaxFileSize = 5MB log4j.appender.file.MaxBackupIndex = 10 log4j.appender.file.layout = org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n 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” /> <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> Here, we have configured the LOG4J to log details on the Tomcat console and in the file present in &t; tomcat home → logs as myapp.log. 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/hello and we will see the following screen on Tomcat”s log. Print Page Previous Next Advertisements ”;
Spring MVC – Xml View Resolver Example ”; Previous Next The XmlViewResolver is used to resolve the view names using view beans defined in xml file. The following example shows how to use the XmlViewResolver using Spring Web MVC framework. TestWeb-servlet.xml <bean class = “org.springframework.web.servlet.view.XmlViewResolver”> <property name = “location”> <value>/WEB-INF/views.xml</value> </property> </bean> views.xml <bean id = “hello” class = “org.springframework.web.servlet.view.JstlView”> <property name = “url” value = “/WEB-INF/jsp/hello.jsp” /> </bean> For example, using the above configuration, if URI − /hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the view.xml. 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 TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class HelloController under the com.tutorialspointpackage. 3 Create a view file hello.jsp under the jsp sub-folder. 4 Download JSTL library jstl.jar. Put it in your CLASSPATH. 5 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”; } } 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”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.XmlViewResolver”> <property name = “location”> <value>/WEB-INF/views.xml</value> </property> </bean> </beans> views.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 id = “hello” class = “org.springframework.web.servlet.view.JstlView”> <property name = “url” value = “/WEB-INF/jsp/hello.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> 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 the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;
Spring MVC – Errors
Spring MVC – Error Handling Example ”; Previous Next The following example shows how to use Error Handling and Validators 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.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes Student, StudentController and StudentValidator under the com.tutorialspoint package. 3 Create view files addStudent.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; } } StudentValidator.java package com.tutorialspoint; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class StudentValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Student.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, “name”, “required.name”,”Field name is required.”); } } StudentController.java package com.tutorialspoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; 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; @Controller public class StudentController { @Autowired @Qualifier(“studentValidator”) private Validator validator; @InitBinder private void initBinder(WebDataBinder binder) { binder.setValidator(validator); } @RequestMapping(value = “/addStudent”, method = RequestMethod.GET) public ModelAndView student() { return new ModelAndView(“addStudent”, “command”, new Student()); } @ModelAttribute(“student”) public Student createStudentModel() { return new Student(); } @RequestMapping(value = “/addStudent”, method = RequestMethod.POST) public String addStudent(@ModelAttribute(“student”) @Validated Student student, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return “addStudent”; } model.addAttribute(“name”, student.getName()); model.addAttribute(“age”, student.getAge()); model.addAttribute(“id”, student.getId()); return “result”; } } 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 = “studentValidator” class = “com.tutorialspoint.StudentValidator” /> </beans> Here, for the first service method student(), we have passed a blank Studentobject 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 student() method is called, it returns addStudent.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 the result.jsp. In case there are errors generated using validator then same view “addStudent” is returned, Spring automatically injects error messages from BindingResult in view. addStudent.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <style> .error { color: #ff0000; } .errorblock { color: #000; background-color: #ffEEEE; border: 3px solid #ff0000; padding: 8px; margin: 16px; } </style> <body> <h2>Student Information</h2> <form:form method = “POST” action = “/HelloWeb/addStudent” commandName = “student”> <form:errors path = “*” cssClass = “errorblock” element = “div” /> <table> <tr> <td><form:label path = “name”>Name</form:label></td> <td><form:input path = “name” /></td> <td><form:errors path = “name” cssClass = “error” /></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> Here we are using <form:errors /> tag with path=”*” to render error messages. For example <form:errors path = “*” cssClass = “errorblock” element = “div” /> It will render the error messages for all input validations. We are using <form:errors /> tag with path=”name” to render error message for name field. For example <form:errors path = “name” cssClass = “error” /> It will render error messages for the name field validations. 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 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/addStudent 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 ”;
Spring MVC – Radiobuttons
Spring MVC – RadioButtons Example ”; Previous Next The following example explains how to use RadioButtons in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and follow the subsequent 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; 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; } } 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()); model.addAttribute(“favoriteNumber”, user.getFavoriteNumber()); 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; } } 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 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 colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:radiobuttons />tag to render the HTML radiobuttons. For example − <form:radiobuttons path = “favoriteNumber” items=”${numbersList}” /> It will render the following HTML content. <span> <input id = “favoriteNumber1” name = “favoriteNumber” type = “radio” value = “1”/> <label for = “favoriteNumber1”>1</label> </span> <span> <input id = “favoriteNumber2” name = “favoriteNumber” type = “radio” value = “2”/> <label for = “favoriteNumber2”>2</label> </span> <span> <input id = “favoriteNumber3” name = “favoriteNumber” type = “radio” value = “3”/> <label for = “favoriteNumber3”>3</label> </span> <span> <input id = “favoriteNumber4” name = “favoriteNumber” type = “radio” value = “4”/> <label for = “favoriteNumber4”>4</label> </span> 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> </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 the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try the following 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 your Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Parameter Method Name Resolver Example ”; Previous Next The following example shows how to use the Parameter Method Name Resolver of a Multi Action Controller using the Spring Web MVC framework. The MultiActionController class helps to map multiple URLs with their methods in a single controller respectively. 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.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Add”); return model; } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Remove”); return model; } } <bean class = “com.tutorialspoint.UserController”> <property name = “methodNameResolver”> <bean class = “org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver”> <property name = “paramName” value = “action”/> </bean> </property> </bean> For example, using the above configuration, if URI − /user/*.htm?action=home is requested, DispatcherServlet will forward the request to the UserController home() method. /user/*.htm?action=add is requested, DispatcherServlet will forward the request to the UserController add() method. /user/*.htm?action=remove is requested, DispatcherServlet will forward the request to the UserController remove() method. 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 TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class UserController under the com.tutorialspoint package. 3 Create a view file user.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. UserController.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.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Add”); return model; } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Remove”); 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”> <property name = “caseSensitive” value = “true” /> </bean> <bean class = “com.tutorialspoint.UserController”> <property name = “methodNameResolver”> <bean class = “org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver”> <property name = “paramName” value = “action”/> </bean> </property> </bean> </beans> user.jsp <%@ page contentType=”text/html; charset=UTF-8″ %> <html> <head> <title>Hello World</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 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. Now, try a URL − http://localhost:8080/TestWeb/user/test.htm?action=home and we will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Properties Method Name Resolver Example ”; Previous Next The following example shows how to use the Properties Method Name Resolver method of a Multi Action Controller using Spring Web MVC framework. The MultiActionController class helps to map multiple URLs with their methods in a single controller respectively. 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.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Add”); return model; } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Remove”); return model; } } <bean class = “com.tutorialspoint.UserController”> <property name = “methodNameResolver”> <bean class = “org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver”> <property name = “mappings”> <props> <prop key = “/user/home.htm”>home</prop> <prop key = “/user/add.htm”>add</prop> <prop key = “/user/remove.htm”>update</prop> </props> </property> </bean> </property> </bean> For example, using the above configuration, if URI − /user/home.htm is requested, DispatcherServlet will forward the request to the UserController home() method. /user/add.htm is requested, DispatcherServlet will forward the request to the UserController add() method. /user/remove.htm is requested, DispatcherServlet will forward the request to the UserController remove() method. To start with it, 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 class UserController under the com.tutorialspoint package. 3 Create a view file user.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. UserController.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.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Add”); return model; } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Remove”); 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”> <property name = “caseSensitive” value = “true” /> </bean> <bean class = “com.tutorialspoint.UserController”> <property name = “methodNameResolver”> <bean class = “org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver”> <property name = “mappings”> <props> <prop key = “/user/home.htm”>home</prop> <prop key = “/user/add.htm”>add</prop> <prop key = “/user/remove.htm”>update</prop> </props> </property> </bean> </property> </bean> </beans> user.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Hello World</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 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. Now, try a URL − http://localhost:8080/TestWeb/user/add.htm and we will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Textbox
Spring MVC – Text Box Example ”; Previous Next The following example shows how to use Text boxes in forms 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 HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World Example chapter. 2 Create a Java classes Student, StudentController under the com.tutorialspoint package. 3 Create a view files student.jsp, result.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. 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”, because the spring framework expects an object with name “command”, if you are using <form:form> tags in your 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> Here, we are using <form:input /> tag to render an HTML text box. For example − <form:input path = “name” /> It will render following HTML content. <input id = “name” name = “name” type = “text” value = “”/> 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 HelloWeb.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/HelloWeb/student 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 should see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;