ank spring mvc.docx

23
Spring MVC Hello World Spring is the most popular open source java application framework as of current moment. It is one of the best job enablers too (at least in Indian software services companies). Before starting on spring framework, I recommend you to become strong in core-java first, then remember to study servlets, jsp and then start on Spring framework. Spring framework provides multiple modules wherein MVC and Inversion of Control container are popular among them. In this article I will present a spring MVC based Hello World web application. I am using Spring version 3 latest available now. SpringSource provides a tool suite (STS) IDE which is based on Eclipse to develop Spring based applications. But, my personal choice for now is to continue with Eclipse JEE IDE. Model View Controller (MVC)

Upload: swetabhsrinath92

Post on 06-Nov-2015

27 views

Category:

Documents


0 download

TRANSCRIPT

Spring MVC Hello WorldSpring is the most popular open source java application framework as of current moment. It is one of the best job enablers too (at least in Indian software services companies).Before starting on spring framework, I recommend you to become strong in core-java first, then remember to study servlets, jsp and then start on Spring framework.Spring framework provides multiple modules wherein MVC and Inversion of Control container are popular among them. In this article I will present a spring MVC based Hello World web application.

I am using Spring version 3 latest available now.SpringSourceprovides a tool suite (STS) IDE which is based onEclipseto develop Spring based applications. But, my personal choice for now is to continue with Eclipse JEE IDE.Model View Controller (MVC)Model view controller is a software architecture design pattern. It provides solution to layer an application by separating three concerns business, presentation and control flow. Model contains business logic, controller takes care of the interaction between view and model. Controller gets input from view and coverts it in preferable format for the model and passes to it. Then gets the response and forwards to view. View contains the presentation part of the application.Spring MVCSpring MVC is a module for enabling us to implement the MVC pattern. Following image shows the Springs MVC architecture

DispatcherServletThis class is a front controller that acts as central dispatcher for HTTP web requests. Based on the handler mappings we provide in spring configuration, it routes control from view to other controllers and gets processed result back and routes it back to view.

Control Flow in Spring MVC1. Based on servletmapping from web.xml request gets routed by servlet container to a front controller (DispatcherServlet).2. DispatcherServlet uses handler mapping and forwards the request to matching controller.3. Controller processes the request and returns ModeAndView back to front controller (DispatcherServlet). Generally controller uses a Service to perform the rules.4. DispatcherServlet uses the view resolver and sends the model to view.5. Response is constructed and control sent back to DispatcherServlet.6. DispatcherServlet returns the response.Spring 3 MVC SampleSoftware versions used to run the sample code: Spring 3 Java 1.6 Tomcat 7 JSTL 1.2 Eclipse Java EE IDEWeb Application StructureUse Java EE perspective and create a new dynamic web project. Let us start with web.xml

web.xmlIn web.xml primarily we are doingservlet mappingto give configuration for DispatcherServlet to load-on-startup and defining spring configuration path.

Spring Hello World /

springDispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/config/spring-context.xml 1 springDispatcher /

Spring ConfigurationThis spring configuration file provides context information to spring container. In our case,The tag mvc:annotation-driven says that we are using annotation based configurations. context:component-scan says that the annotated components like Controller, Service are to be scanned automatically by Spring container starting from the given package.

Library files needed commons-logging.jar org.springframework.asm-3.1.2.RELEASE.jar org.springframework.beans-3.1.2.RELEASE.jar org.springframework.context-3.1.2.RELEASE.jar org.springframework.core-3.1.2.RELEASE.jar org.springframework.expression-3.1.2.RELEASE.jar org.springframework.web.servlet-3.1.2.RELEASE.jar org.springframework.web-3.1.2.RELEASE.jar javax.servlet.jsp.jstl-1.2.1.jar (http://jstl.java.net/download.html -> JSTL Implementation)These jars are part of standard spring framework download except the jstl.ControllerFollowing controller class has got methods. First one hello maps to the url /. Annotation has made our job easier by just declaring the annotation we order Spring container to invoke this method whenever this url is called. return hello means this is used for selecting the view. In spring configuration we have declared InternalResourceViewResolver and have given a prefix and suffix. Based on this, the prefix and suffix is added to the returned word hello thus making it as /WEB-INF/view/hello.jsp. So on invoking of / the control gets forwarded to the hello.jsp. In hello.jsp we just print Hello World.org.springframework.web.servlet.view.InternalResourceViewResolverAdded to printing Hello World I wanted to give you a small bonus with this sample. Just get an input from user and send a response back based on it. The second method hi serves that purpose in controller. It gets the user input and concatenates Hi to it and sets the value in model object. model is a specialhashmappassed by spring container while invoking this method. When we set a key-value pair, it becomes available in the view. We can use the key to get the value and display it in the view which is our hi.jsp. As explained above InternalResourceViewResolver is used to resole the view.package com.javapapers.spring.mvc;

import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;

@Controllerpublic class HelloWorldController {

@RequestMapping("/")public String hello() {return "hello";}

@RequestMapping(value = "/hi", method = RequestMethod.GET)public String hi(@RequestParam("name") String name, Model model) {String message = "Hi " + name + "!";model.addAttribute("message", message);return "hi";}

}View Hello World

Home

Hello World!

Name:

Use key message in model to get the value and print it.

Result

Hello World Output

Spring Form Handling==================

The following example show how to write a simple web based application which makes use of HTML forms using Spring Web MVC framework. To start with it, let us have working Eclipse IDE in place and follow the following steps to develope a Dynamic Form based Web Application using Spring Web Framework:StepDescription

1Create aDynamic Web Projectwith a nameHelloWeband create a packagecom.tutorialspointunder thesrcfolder in the created project.

2Drag and drop below mentioned Spring and other libraries into the folderWebContent/WEB-INF/lib.

3Create a Java classesStudentandStudentControllerunder thecom.tutorialspointpackage.

4Create Spring configuration filesWeb.xmlandHelloWeb-servlet.xmlunder theWebContent/WEB-INFfolder.

5Create a sub-folder with a namejspunder theWebContent/WEB-INFfolder. Create a view filesstudent.jspandresult.jspunder this sub-folder.

6The final step is to create the content of all the source and configuration files and export the application as explained below.

Here is the content ofStudent.javafile: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; }}Following is the content ofStudentController.javafile: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;

@Controllerpublic 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 methodstudent(), we have passed a blankStudentobject in the ModelAndView object with name "command" because the spring framework expects an object with name "command" if you are using tags in your JSP file. So whenstudent()method is called it returnsstudent.jspview.Second service methodaddStudent()will be called against a POST method on theHelloWeb/addStudentURL. 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.jspFollowing is the content of Spring Web configuration fileweb.xml

Spring MVC Form Handling HelloWeb org.springframework.web.servlet.DispatcherServlet 1

HelloWeb /

Following is the content of another Spring Web configuration fileHelloWeb-servlet.xml

Following is the content of Spring view filestudent.jsp

Spring MVC Form Handling

Student Information

Name Age id

Following is the content of Spring view fileresult.jsp

Spring MVC Form Handling

Submitted Student Information Name ${name} Age ${age} ID ${id}

Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them inWebContent/WEB-INF/libfolder. commons-logging-x.y.z.jar org.springframework.asm-x.y.z.jar org.springframework.beans-x.y.z.jar org.springframework.context-x.y.z.jar org.springframework.core-x.y.z.jar org.springframework.expression-x.y.z.jar org.springframework.web.servlet-x.y.z.jar org.springframework.web-x.y.z.jar spring-web.jarOnce you are done with creating source and configuration files, export your application. Right click on your application and useExport > WAR Fileoption and save yourSpringWeb.warfile in Tomcat'swebappsfolder.Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Now try a URLhttp://localhost:8080/SpringWeb/studentand you should see the following result if everything is fine with your Spring Web Application:

After submitting required information click on submit button to submit the form. You should see the following result if everything is fine with your Spring Web Application: