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 ”;
Category: springmvc
Spring MVC – Checkboxes
Spring MVC – Checkboxes Example ”; Previous Next The following example explains how to use Multiple Checkboxes 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; 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; } } 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″})); 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()); 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, 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 colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:checkboxes /> tag to render HTML checkboxes. <form:checkboxes items = “${webFrameworkList}” path = “favoriteFrameworks” /> It will render following HTML content. <span> <input id = “favoriteFrameworks1” name = “favoriteFrameworks” type = “checkbox” value = “Spring MVC” checked = “checked”/> <label for = “favoriteFrameworks1”>Spring MVC</label> </span> <span> <input id = “favoriteFrameworks2” name = “favoriteFrameworks” type = “checkbox” value = “Struts 1″/> <label for = “favoriteFrameworks2”>Struts 1</label> </span> <span> <input id = “favoriteFrameworks3” name = “favoriteFrameworks” type = “checkbox” value = “Struts 2” checked = “checked”/> <label for = “favoriteFrameworks3”>Struts 2</label> </span> <span> <input id = “favoriteFrameworks4” name = “favoriteFrameworks” type = “checkbox” value = “Apache Wicket”/> <label for = “favoriteFrameworks4”>Apache Wicket</label> </span> <input type = “hidden” name = “_favoriteFrameworks” 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> <tr> <td>Favorite Web Frameworks</td> <td> <% String[] favoriteFrameworks = (String[])request.getAttribute(“favoriteFrameworks”); for(String framework: favoriteFrameworks) { out.println(framework); } %></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 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. We will see the following screen, if everything is fine with your Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Textarea
Spring MVC – TextArea Example ”; Previous Next The following example explains how to use TextArea 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 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; 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; } } 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()); 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 colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:textarea /> tag to render a HTML textarea box. For example − <form:textarea path = “address” rows = “5” cols = “30” /> It will render the following HTML content. <textarea id = “address” name = “address” rows = “5” cols = “30”></textarea> 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> </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 MVC – Hidden
Spring MVC – Hidden Field Example ”; Previous Next The following example describes how to use a Hidden Field 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 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, for the first service method student(), we have passed a blank Studentobject in the ModelAndView object with the name “command”, because the spring framework expects an object with the name “command”, if you are using <form:form> tags in your JSP file. So, when the student() method is called, it returns the 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>< </td> <td><form:hidden path = “id” value = “1” /></td> </tr> <tr> <td colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using the <form:hidden /> tag to render a HTML hidden field. For example − <form:hidden path = “id” value = “1”/> It will render following HTML content. <input id = “id” name = “id” type = “hidden” value = “1”/> 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 and 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/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 will see the following screen, if everything is fine with your Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Generate Excel
Spring MVC – Generate Excel Example ”; Previous Next The following example shows how to generate Excel 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 UserExcelView and ExcelController under the com.tutorialspoint package. 3 Download the Apache POI library Apache POI 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. ExcelController.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 ExcelController 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.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.web.servlet.view.document.AbstractExcelView; public class UserExcelView extends AbstractExcelView { @Override protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String,String> userData = (Map<String,String>) model.get(“userData”); //create a wordsheet HSSFSheet sheet = workbook.createSheet(“User Report”); HSSFRow header = sheet.createRow(0); header.createCell(0).setCellValue(“Roll No”); header.createCell(1).setCellValue(“Name”); int rowNum = 1; for (Map.Entry<String, String> entry : userData.entrySet()) { //create the row data HSSFRow row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(entry.getKey()); row.createCell(1).setCellValue(entry.getValue()); } } } 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.ExcelController” /> <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.UserExcelView”></bean> </beans> Here, we have created an ExcelController and an ExcelView. Apache POI library deals with Microsoft Office file formats and will convert the data to an excel 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. Try a URL − http://localhost:8080/TestWeb/excel and we will see the following screen. Print Page Previous Next Advertisements ”;
Spring MVC – Generate RSS Feed Example ”; Previous Next The following example shows how to generate RSS Feed using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and then consider 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 Java classes RSSMessage, RSSFeedViewer and RSSController under the com.tutorialspoint package. 3 Download the Rome library Rome and its dependencies rome-utils, jdom and slf4j from the same maven repository page. Put them in your CLASSPATH. 4 Create a properties file messages.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. RSSMessage.java package com.tutorialspoint; import java.util.Date; public class RSSMessage { String title; String url; String summary; Date createdDate; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } } RSSFeedViewer.java package com.tutorialspoint; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.feed.AbstractRssFeedView; import com.rometools.rome.feed.rss.Channel; import com.rometools.rome.feed.rss.Content; import com.rometools.rome.feed.rss.Item; public class RSSFeedViewer extends AbstractRssFeedView { @Override protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) { feed.setTitle(“TutorialsPoint Dot Com”); feed.setDescription(“Java Tutorials and Examples”); feed.setLink(“http://www.tutorialspoint.com”); super.buildFeedMetadata(model, feed, request); } @Override protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { List<RSSMessage> listContent = (List<RSSMessage>) model.get(“feedContent”); List<Item> items = new ArrayList<Item>(listContent.size()); for(RSSMessage tempContent : listContent ){ Item item = new Item(); Content content = new Content(); content.setValue(tempContent.getSummary()); item.setContent(content); item.setTitle(tempContent.getTitle()); item.setLink(tempContent.getUrl()); item.setPubDate(tempContent.getCreatedDate()); items.add(item); } return items; } } RSSController.java package com.tutorialspoint; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class RSSController { @RequestMapping(value=”/rssfeed”, method = RequestMethod.GET) public ModelAndView getFeedInRss() { List<RSSMessage> items = new ArrayList<RSSMessage>(); RSSMessage content = new RSSMessage(); content.setTitle(“Spring Tutorial”); content.setUrl(“http://www.tutorialspoint/spring”); content.setSummary(“Spring tutorial summary…”); content.setCreatedDate(new Date()); items.add(content); RSSMessage content2 = new RSSMessage(); content2.setTitle(“Spring MVC”); content2.setUrl(“http://www.tutorialspoint/springmvc”); content2.setSummary(“Spring MVC tutorial summary…”); content2.setCreatedDate(new Date()); items.add(content2); ModelAndView mav = new ModelAndView(); mav.setViewName(“rssViewer”); mav.addObject(“feedContent”, items); return mav; } } 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.BeanNameViewResolver” /> <bean id = “rssViewer” class = “com.tutorialspoint.RSSFeedViewer” /> </beans> Here, we have created a RSS feed POJO RSSMessage and a RSS Message Viewer, which extends the AbstractRssFeedView and overrides its method. In RSSController, we have generated a sample RSS Feed. 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. Try a URL − http://localhost:8080/TestWeb/rssfeed and we will see the following screen. Print Page Previous Next Advertisements ”;
Spring MVC – Parameterizable View Controller Example ”; Previous Next The following example shows how to use the Parameterizable View Controller method of a Multi Action Controller using the Spring Web MVC framework. The Parameterizable View allows mapping a webpage with a request. 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; } } <bean class=”org.springframework.web.servlet.handler.SimpleUrlHandlerMapping”> <property name=”mappings”> <value> index.htm=userController </value> </property> </bean> <bean id=”userController” class=”org.springframework.web.servlet.mvc.ParameterizableViewController”> <property name=”viewName” value=”user”/> </bean> For example, using the above configuration, if URI. /index.htm is requested, DispatcherServlet will forward the request to the UserController controller with viewName set as user.jsp. 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 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; } } 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.SimpleUrlHandlerMapping”> <property name = “mappings”> <value> index.htm = userController </value> </property> </bean> <bean id = “userController” class = “org.springframework.web.servlet.mvc.ParameterizableViewController”> <property name = “viewName” value=”user”/> </bean> </beans> user.jsp <%@ page contentType=”text/html; charset=UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>Hello World</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 webapps folder using a standard browser. Now, try a URL – http://localhost:8080/TestWeb/index.htm and you will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Internal Resource View Resolver Example ”; Previous Next The InternalResourceViewResolver is used to resolve the provided URI to actual URI. The following example shows how to use the InternalResourceViewResolver using the Spring Web MVC Framework. The InternalResourceViewResolver allows mapping webpages with requests. 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”; } } <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> For example, using the above configuration, if URI /hello is requested, DispatcherServlet will forward the request to the prefix + viewname + suffix = /WEB-INF/jsp/hello.jsp. To start with, let us have a working Eclipse IDE in place and then 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.tutorialspointas explained in the Spring MVC – Hello World Example chapter. 2 Create a Java classes HelloController under the com.tutorialspointpackage. 3 Create a view file hello.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. 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.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> 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. Try to access the URL – http://localhost:8080/TestWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;
Simple Url Handler Mapping
Spring MVC – Simple Url Handler Mapping Example ”; Previous Next The following example shows how to use Simple URL Handler Mapping using the Spring Web MVC framework. The SimpleUrlHandlerMapping class helps to explicitly-map URLs with their controllers respectively. <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.SimpleUrlHandlerMapping”> <property name = “mappings”> <props> <prop key = “/welcome.htm”>welcomeController</prop> <prop key = “/helloWorld.htm”>helloController</prop> </props> </property> </bean> <bean id = “helloController” class = “com.tutorialspoint.HelloController” /> <bean id = “welcomeController” class = “com.tutorialspoint.WelcomeController”/> </beans> For example, using above configuration, if URI /helloWorld.htm is requested, DispatcherServlet will forward the request to the HelloController. /welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController. 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 and WelcomeController under the com.tutorialspoint package. 3 Create view files hello.jsp and 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.handler.SimpleUrlHandlerMapping”> <property name = “mappings”> <props> <prop key = “/welcome.htm”>welcomeController</prop> <prop key = “/helloWorld.htm”>helloController</prop> </props> </property> </bean> <bean id = “helloController” class = “com.tutorialspoint.HelloController” /> <bean id = “welcomeController” 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 the Export → WAR File option and save your 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 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/welcome.htm and you should see the following result if everything is fine with your Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Hibernate Validator Example ”; Previous Next The following example shows how to use Error Handling and Validators in forms using the Spring Web MVC framework. 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 the name TestWeb 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 and result.jsp under the jsp sub-folder. 4 Download Hibernate Validator library Hibernate Validator. Extract hibernate-validator-5.3.4.Final.jar and required dependencies present under the required folder of the downloaded zip file. Put them in your CLASSPATH. 5 Create a properties file messages.properties under the SRC folder. 6 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; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; public class Student { @Range(min = 1, max = 150) private Integer age; @NotEmpty 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.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; 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 { @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”; } } messages.properties NotEmpty.student.name = Name is required! Range.student.age = Age value must be between 1 and 150! Here, the key is <Annotation>.<object-name>.<attribute>. Value is the message to be displayed. TestWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:mvc = “http://www.springframework.org/schema/mvc” 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 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 /> <bean class = “org.springframework.context.support.ResourceBundleMessageSource” id = “messageSource”> <property name = “basename” value = “messages” /> </bean> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </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 the 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 = “/TestWeb/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> <td><form:errors path = “age” cssClass = “error” /></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 the <form:errors /> tag with path=”*” to render error messages. For example − <form:errors path = “*” cssClass = “errorblock” element = “div” /> It will render error messages for all input validations. We are using <form:errors /> tag with path = “name” to render error message for the name field. For example − <form:errors path = “name” cssClass = “error” /> <form:errors path = “age” cssClass = “error” /> It will render error messages for name and age 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 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/addStudent and we will see the following screen, if you have entered invalid values. Print Page Previous Next Advertisements ”;