Spring Boot – Servlet Filter ”; Previous Next A filter is an object used to intercept the HTTP requests and responses of your application. By using filter, we can perform two operations at two instances − Before sending the request to the controller Before sending a response to the client. The following code shows the sample code for a Servlet Filter implementation class with @Component annotation. @Component public class SimpleFilter implements Filter { @Override public void destroy() {} @Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException {} @Override public void init(FilterConfig filterconfig) throws ServletException {} } The following example shows the code for reading the remote host and remote address from the ServletRequest object before sending the request to the controller. In doFilter() method, we have added the System.out.println statements to print the remote host and remote address. package com.tutorialspoint.demo; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.stereotype.Component; @Component public class SimpleFilter implements Filter { @Override public void destroy() {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException { System.out.println(“Remote Host:”+request.getRemoteHost()); System.out.println(“Remote Address:”+request.getRemoteAddr()); filterchain.doFilter(request, response); } @Override public void init(FilterConfig filterconfig) throws ServletException {} } In the Spring Boot main application class file, we have added the simple REST endpoint that returns the “Hello World” string. package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @RequestMapping(value = “/”) public String hello() { return “Hello World”; } } The code for Maven build – pom.xml is given below − <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0″ xmlns:xsi = ” http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below − For Maven, use the command as shown below − mvn clean install After BUILD SUCCESS, you can find the JAR file under the target directory. For Gradle, use the command as shown below − gradle clean build After BUILD SUCCESSFUL, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the following command java –jar <JARFILE> You can see the application has started on the Tomcat port 8080. Now hit the URL http://localhost:8080/ and see the output Hello World. It should look as shown below − Then, you can see the Remote host and Remote address on the console log as shown below − Print Page Previous Next Advertisements ”;
Category: Java
Spring Boot – Rest Template
Spring Boot – Rest Template ”; Previous Next Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object. package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } } GET Consuming the GET API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products returns the following JSON and we are going to consume this API response by using Rest Template using the following code − [ { “id”: “1”, “name”: “Honey” }, { “id”: “2”, “name”: “Almond” } ] You will have to follow the given points to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Provide the URL, HttpMethod, and Return type for Exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”) public String getProductList() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity <String> entity = new HttpEntity<String>(headers); return restTemplate.exchange(” http://localhost:8080/products”, HttpMethod.GET, entity, String.class).getBody(); } } POST Consuming POST API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products returns the response shown below, we are going to consume this API response by using the Rest Template. The code given below is the Request body − { “id”:”3″, “name”:”Ginger” } The code given below is the Response body − Product is created successfully You will have to follow the points given below to consume the API − Autowired the Rest Template Object. Use the HttpHeaders to set the Request Headers. Use the HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”, method = RequestMethod.POST) public String createProducts(@RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.POST, entity, String.class).getBody(); } } PUT Consuming PUT API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products/3 returns the below response and we are going to consume this API response by using Rest Template. The code given below is Request body − { “name”:”Indian Ginger” } The code given below is the Response body − Product is updated successfully You will have to follow the points given below to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.PUT) public String updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.PUT, entity, String.class).getBody(); } } DELETE Consuming DELETE API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products/3 returns the response given below and we are going to consume this API response by using Rest Template. This line of code shown below is the Response body − Product is deleted successfully You will have to follow the points shown below to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.DELETE) public String deleteProduct(@PathVariable(“id”) String id) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.DELETE, entity, String.class).getBody(); } } The complete Rest Template Controller class file is given below − package com.tutorialspoint.demo.controller; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.tutorialspoint.demo.model.Product; @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”) public String getProductList() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<String>(headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.GET, entity, String.class).getBody(); } @RequestMapping(value = “/template/products”, method = RequestMethod.POST) public String createProducts(@RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.POST, entity, String.class).getBody(); } @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.PUT) public String updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.PUT, entity, String.class).getBody(); } @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.DELETE) public String deleteProduct(@PathVariable(“id”) String id) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.DELETE, entity, String.class).getBody(); } } The code for Spring Boot Application Class – DemoApplication.java is given below − package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The code for Maven build – pom.xml is given below − <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the
Struts2 Questions and Answers ”; Previous Next Struts2 Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Struts2 Interview Questions This section provides a huge collection of Struts2 Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Struts2 Online Quiz This section provides a great collection of Struts2 Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Struts2 Online Test If you are preparing to appear for a Java and Struts2 Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Struts2 Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;
Spring Boot – Building RESTful Web Services ”; Previous Next Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot. Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the build configuration file. If you are a Maven user, use the following code to add the below dependency in your pom.xml file − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> If you are a Gradle user, use the following code to add the below dependency in your build.gradle file. compile(”org.springframework.boot:spring-boot-starter-web”) The code for complete build configuration file Maven build – pom.xml is given below − <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for complete build configuration file Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Before you proceed to build a RESTful web service, it is suggested that you have knowledge of the following annotations − Rest Controller The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below − @RestController public class ProductServiceController { } Request Mapping The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET. @RequestMapping(value = “/products”) public ResponseEntity<Object> getProducts() { } Request Body The @RequestBody annotation is used to define the request body content type. public ResponseEntity<Object> createProduct(@RequestBody Product product) { } Path Variable The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below − public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id) { } Request Parameter The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here − public ResponseEntity<Object> getProduct( @RequestParam(value = “name”, required = false, defaultValue = “honey”) String name) { } GET API The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL. The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that we used a POJO class as the product to be stored. Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that contains GET method REST Endpoint. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId(“1”); honey.setName(“Honey”); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId(“2”); almond.setName(“Almond”); productRepo.put(almond.getId(), almond); } @RequestMapping(value = “/products”) public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } } POST API The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the Product, where the product is a POJO class. Here, the request URI is /products, and it will return the String after storing the product into HashMap repository. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = “/products”, method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>(“Product is created successfully”, HttpStatus.CREATED); } } PUT API The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing Product, where the product is a POJO class. Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path variable {id} which defines the products ID that needs to be updated. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>(“Product is updated successsfully”, HttpStatus.OK); } } DELETE API The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing product, which is a POJO class. The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the
Struts2 – Validations
Struts 2 – Validations Framework ”; Previous Next In this chapter, we shall look deeper into Struts validation framework. At the Struts core, we have the validation framework that assists the application to run the rules to perform validation before the action method is executed. Client side validation is usually achieved using Javascript. However, one should not rely upon client side validation alone. The best practices suggest that the validation should be introduced at all levels of your application framework. Now let us look at two ways of adding validation to our Struts project. Here, we will take an example of an Employee whose name and age should be captured using a simple page, and we will put these two validations to make sure that the user always enters a name and age which should be in a range between 28 and 65. Let us start with the main JSP page of the example. Create Main Page Let us write main page JSP file index.jsp, which will be used to collect Employee related information mentioned above. <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Employee Form</title> </head> <body> <s:form action = “empinfo” method = “post”> <s:textfield name = “name” label = “Name” size = “20” /> <s:textfield name = “age” label = “Age” size = “20” /> <s:submit name = “submit” label = “Submit” align=”center” /> </s:form> </body> </html> The index.jsp makes use of Struts tag, which we have not covered yet, but we will study them in tags related chapters. But for now, just assume that the s:textfield tag prints a input field, and the s:submit prints a submit button. We have used label property for each tag which creates label for each tag. Create Views We will use JSP file success.jsp which will be invoked in case defined action returns SUCCESS. <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Success</title> </head> <body> Employee Information is captured successfully. </body> </html> Create Action So let us define a small action class Employee, and then add a method called validate() as shown below in Employee.java file. Make sure that your action class extends the ActionSupport class, otherwise your validate method will not be executed. package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class Employee extends ActionSupport { private String name; private int age; public String execute() { return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void validate() { if (name == null || name.trim().equals(“”)) { addFieldError(“name”,”The name is required”); } if (age < 28 || age > 65) { addFieldError(“age”,”Age must be in between 28 and 65″); } } } As shown in the above example, the validation method checks whether the ”Name” field has a value or not. If no value has been supplied, we add a field error for the ”Name” field with a custom error message. Secondly, we check if entered value for ”Age” field is in between 28 and 65 or not, if this condition does not meet we add an error above the validated field. Configuration Files Finally, let us put everything together using the struts.xml configuration file as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “empinfo” class = “com.tutorialspoint.struts2.Employee” method = “execute”> <result name = “input”>/index.jsp</result> <result name = “success”>/success.jsp</result> </action> </package> </struts> Following is the content of web.xml file − <?xml version = “1.0” Encoding = “UTF-8”?> <web-app xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns = “http://java.sun.com/xml/ns/javaee” xmlns:web = “http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” xsi:schemaLocation = “http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd” id = “WebApp_ID” version = “3.0”> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen − Now do not enter any required information, just click on Submit button. You will see the following result − Enter the required information but enter a wrong From field, let us say name as “test” and age as 30, and finally click on Submit button. You will see the following result − How this Validation Works? When the user presses the submit button, Struts 2 will automatically execute the validate method and if any of the “if” statements listed inside the method are true, Struts 2 will call its addFieldError method. If any errors have been added, then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return input as the result of calling the action. Hence, when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the index.jsp file. Since, we used Struts 2 form tags, Struts 2 will automatically add the error messages just above the form filed. These error messages are the ones we specified in the addFieldError method call. The addFieldError method takes two arguments. The first, is the form field name to which the error applies and the second, is the error message to display above that form field. addFieldError(“name”,”The name is required”); To handle the return value of input we need to add the following result to our action node in struts.xml. <result name = “input”>/index.jsp</result> XML Based Validation The second method of doing validation is by placing an xml file next to the action class. Struts2 XML based validation provides more
Struts2 – Spring
Struts 2 & Spring Integration ”; Previous Next Spring is a popular web framework that provides easy integration with lots of common web tasks. So the question is, why do we need Spring when we have Struts2? Well, Spring is more than a MVC framework – it offers many other goodies which are not available in Struts. For example: dependency injection that can be useful to any framework. In this chapter, we will go through a simple example to see how to integrate Spring and Struts2 together. First of all, you need to add the following files to the project”s build path from Spring installation. You can download and install latest version of Spring Framework from https://www.springsource.org/download org.springframework.asm-x.y.z.M(a).jar org.springframework.beans-x.y.z.M(a).jar org.springframework.context-x.y.z.M(a).jar org.springframework.core-x.y.z.M(a).jar org.springframework.expression-x.y.z.M(a).jar org.springframework.web-x.y.z.M(a).jar org.springframework.web.servlet-x.y.z.M(a).jar Finally add struts2-spring-plugin-x.y.z.jar in your WEB-INF/lib from your struts lib directory. If you are using Eclipse then you may face an exception java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener. To fix this problem, you should have to go in Marker tab and righ click on the class dependencies one by one and do Quick fix to publish/export all the dependences. Finally make sure there is no dependency conflict available under the marker tab. Now let us setup the web.xml for the Struts-Spring integration as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <web-app xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns = “http://java.sun.com/xml/ns/javaee” xmlns:web = “http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” xsi:schemaLocation = “http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd” id = “WebApp_ID” version = “3.0”> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> The important thing to note here is the listener that we have configured. The ContextLoaderListener is required to load the spring context file. Spring”s configuration file is called applicationContext.xml file and it must be placed at the same level as the web.xml file Let us create a simple action class called User.java with two properties – firstName and lastName. package com.tutorialspoint.struts2; public class User { private String firstName; private String lastName; public String execute() { return “success”; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } Now let us create the applicationContext.xml spring configuration file and instantiate the User.java class. As mentioned earlier, this file should be under the WEB-INF folder − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” “http://www.springframework.org/dtd/spring-beans.dtd”> <beans> <bean id = “userClass” class = “com.tutorialspoint.struts2.User”> <property name = “firstName” value = “Michael” /> <property name = “lastName” value = “Jackson” /> </bean> </beans> As seen above, we have configured the user bean and we have injected the values Michael and Jackson into the bean. We have also given this bean a name “userClass”, so that we can reuse this elsewhere. Next let us create the User.jsp in the WebContent folder − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2 – Spring integration</h1> <s:form> <s:textfield name = “firstName” label = “First Name”/><br/> <s:textfield name = “lastName” label = “Last Name”/><br/> </s:form> </body> </html> The User.jsp file is pretty straight forward. It serves only one purpose – to display the values of the firstname and lastname of the user object. Finally, let us put all entities together using the struts.xml file. <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “user” class=”userClass” method = “execute”> <result name = “success”>/User.jsp</result> </action> </package> </struts> The important thing to note is that we are using the id userClass to refer to the class. This means that we are using spring to do the dependency injection for the User class. Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/User.jsp. This will produce the following screen − We have now seen how to bring two great frameworks together. This concludes the Struts – Spring integration chapter. Print Page Previous Next Advertisements ”;
Spring MVC – Hello World Example ”; Previous Next The following example shows how to write a simple web based Hello World application using the Spring MVC Framework. To start with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Web Application using the Spring Web Framework. Step Description 1 Create a Dynamic Web Project with a name HelloWeb and create a package com.tutorialspoint under the src folder in the created project. 2 Drag and drop the following Spring and other libraries into the folder WebContent/WEB-INF/lib.. 3 Create a Java class HelloController under the com.tutorialspoint package. 4 Create Spring configuration files web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder. 5 Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view file hello.jsp under this sub-folder. 6 The final step is to create the content of the source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } web.xml <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> HelloWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> hello.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> Following is the list of Spring and other libraries to be included in the web application. We can just drag these files and drop them in – WebContent/WEB-INF/lib folder. servlet-api-x.y.z.jar commons-logging-x.y.z.jar spring-aop-x.y.z.jar spring-beans-x.y.z.jar spring-context-x.y.z.jar spring-core-x.y.z.jar spring-expression-x.y.z.jar spring-webmvc-x.y.z.jar spring-web-x.y.z.jar Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now, try to access the URL − http://localhost:8080/HelloWeb/hello. If everything is fine with the Spring Web Application, we will see the following screen. You should note that in the given URL, HelloWeb is the application name and hello is the virtual subfolder, which we have mentioned in our controller using @RequestMapping(“/hello”). You can use direct root while mapping your URL using @RequestMapping(“/”), in this case you can access the same page using short URL http://localhost:8080/HelloWeb/, but it is advised to have different functionalities under different folders. Print Page Previous Next Advertisements ”;
Spring ORM – Update Project
Spring ORM – Update Project ”; Previous Next Let”s add the following classes in the project in the relevant packages. Employee class to be persisted in database. Employee.java package com.tutorialspoint.jpa.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = “Employees”) public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = “NAME”) private String name; @Column(name = “SALARY”) private double salary; @Column(name = “DESIGNATION”) private String designation; public Employee( ) { } public Employee(String name, double salary, String designation) { this.name = name; this.salary = salary; this.designation = designation; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } } Employee DAO class to do operations on database. EmployeeDao.java package com.tutorialspoint.jpa.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import com.tutorialspoint.jpa.entity.Employee; @Repository public class EmployeeDao { @PersistenceContext private EntityManager em; public void add(Employee employee) { em.persist(employee); } public List<Employee> listEmployees() { CriteriaQuery<Employee> criteriaQuery = em.getCriteriaBuilder().createQuery(Employee.class); @SuppressWarnings(“unused”) Root<Employee> root = criteriaQuery.from(Employee.class); return em.createQuery(criteriaQuery).getResultList(); } } Employee Service class to use Employee DAO class. EmployeeService.java package com.tutorialspoint.jpa.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tutorialspoint.jpa.dao.EmployeeDao; import com.tutorialspoint.jpa.entity.Employee; @Service public class EmployeeService { @Autowired private EmployeeDao employeeDao; @Transactional public void add(Employee employee) { employeeDao.add(employee); } @Transactional() public List<Employee> listEmployees() { return employeeDao.listEmployees(); } } Application Configuration to be used by Spring framework. AppConfig.java package com.tutorialspoint.jpa; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScans; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalEntityManagerFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @ComponentScans(value = { @ComponentScan(“com.tutorialspoint.jpa.dao”), @ComponentScan(“com.tutorialspoint.jpa.service”) }) public class AppConfig { @Bean public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() { LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean(); factoryBean.setPersistenceUnitName(“Hibernate_JPA”); return factoryBean; } @Bean public JpaTransactionManager geJpaTransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject()); return transactionManager; } } Main Application to run and test the functionalities. MainApp.java package com.tutorialspoint.jpa; import java.sql.SQLException; import java.util.List; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.tutorialspoint.jpa.entity.Employee; import com.tutorialspoint.jpa.service.EmployeeService; public class MainApp { public static void main(String[] args) throws SQLException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); EmployeeService employeeService = context.getBean(EmployeeService.class); employeeService.add(new Employee(“Julie”, 10000, “Technical Manager”)); employeeService.add(new Employee(“Robert”, 20000, “Senior Manager”)); employeeService.add(new Employee(“Anil”, 5000, “Software Engineer”)); // Get Persons List<Employee> employees = employeeService.listEmployees(); for (Employee employee : employees) { System.out.println(“Id : “+employee.getId()); System.out.println(“Name : “+employee.getName()); System.out.println(“Salary = “+employee.getSalary()); System.out.println(“Designation = “+employee.getDesignation()); System.out.println(); } context.close(); } } Print Page Previous Next Advertisements ”;
Spring MVC – Static Pages
Spring MVC – Static Pages Example ”; Previous Next The following example shows how to write a simple web based application using Spring MVC Framework, which can access static pages along with dynamic pages with the help of a <mvc:resources> tag. To begin with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class WebController under the com.tutorialspoint package. 3 Create a static file final.htm under jsp sub-folder. 4 Update the Spring configuration file HelloWeb-servlet.xml under the WebContent/WEB-INF folder as shown below. 5 The final step is to create the content of the source and configuration files and export the application, which is explained below. WebController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WebController { @RequestMapping(value = “/index”, method = RequestMethod.GET) public String index() { return “index”; } @RequestMapping(value = “/staticPage”, method = RequestMethod.GET) public String redirect() { return “redirect:/pages/final.htm”; } } HelloWeb-servlet.xml <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:xsi = ” http://www.w3.org/2001/XMLSchema-instance” xmlns:context = “http://www.springframework.org/schema/context” xmlns:mvc = “http://www.springframework.org/schema/mvc” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean id = “viewResolver” class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> <mvc:resources mapping = “/pages/**” location = “/WEB-INF/pages/” /> <mvc:annotation-driven/> </beans> Here, the <mvc:resources…./> tag is being used to map static pages. The mapping attribute must be an Ant pattern that specifies the URL pattern of an http requests. The location attribute must specify one or more valid resource directory locations having static pages including images, stylesheets, JavaScript, and other static content. Multiple resource locations may be specified using a comma-separated list of values. Following is the content of Spring view file WEB-INF/jsp/index.jsp. This will be a landing page; this page will send a request to access the staticPage service method, which will redirect this request to a static page available in WEB-INF/pages folder. index.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring Landing Page</title> </head> <body> <h2>Spring Landing Pag</h2> <p>Click below button to get a simple HTML page</p> <form:form method = “GET” action = “/HelloWeb/staticPage”> <table> <tr> <td> <input type = “submit” value = “Get HTML Page”/> </td> </tr> </table> </form:form> </body> </html> final.htm <html> <head> <title>Spring Static Page</title> </head> <body> <h2>A simple HTML page</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now try to access the URL – http://localhost:8080/HelloWeb/index. If everything is fine with the Spring Web Application, we will see the following screen. Click on “Get HTML Page” button to access a static page mentioned in the staticPage service method. If everything is fine with your Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;
Spring MVC – Overview
Spring – MVC Framework Overview ”; Previous Next The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The Model encapsulates the application data and in general, they will consist of POJO. The View is responsible for rendering the model data and in general, it generates HTML output that the client”s browser can interpret. The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering. The DispatcherServlet The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration. Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet − After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers. All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications. Required Configuration We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet − <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> </web-app> The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application”s WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml. Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet. If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows − <web-app…> <!——– DispatcherServlet definition goes here—–> …. <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application”s WebContent/WEB-INF directory. <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> Following are some important points about HelloWeb-servlet.xml file − The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope. The <context:component-scan…> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc. The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp. Let us now understand how to create the actual components i.e., Controller, Model and View. Defining a Controller The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller”s default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL. We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows − @Controller public class HelloController{ @RequestMapping(value = “/hello”, method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request. Following are some important points to be noted regarding the controller defined above − You will define the required business logic inside a service method. You can call another method inside this method as per the requirement. Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute “message”. A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns “hello” as the logical view name. Creating JSP Views Spring MVC supports many types of views for different presentation technologies. These include – JSPs, HTML,