25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10 ■ Showing Your <strong>Spring</strong> Application on the Web<br />

@Controller<br />

@RequestMapping("/search")<br />

public class SearchController {<br />

@Autowired<br />

DocumentDAO documentDAO;<br />

}<br />

@RequestMapping(value="/all",method=RequestMethod.GET)<br />

public String searchAll(Model model){<br />

model.addAttribute("docs", documentDAO.getAll());<br />

return "search/all";<br />

}<br />

As you can see in Listing 10-3, the controller is very simple and it uses different annotations, but let’s see each one<br />

and its meaning.<br />

• @Controller: This will mark your class as the controller so the DispatcherServlet know where<br />

to delegate the request.<br />

• @RequestMapping: This annotation tells how to access this controller, in this case through<br />

the path/search. Later on in the method you will have the same annotation that is telling you<br />

that it will only execute with the path /all and will only accept GET requests. At the end, the<br />

path will be http://///search/all.<br />

• @Autowired: This will inject the DocumentDAO implementation.<br />

Next, you need to add the web.xml that will define how the web application should start up. In any Java web<br />

application, the web.xml file is necessary for most application servers so they know what to do to start the web<br />

application; this is a standard way to deploy web apps. Nowadays this has been simplified by removing the web.xml<br />

file (like in Java 6 EE, and of course when using <strong>Spring</strong>), but in this case you are going to follow the same standard.<br />

Later (in Chapter 19) you will see that no web.xml or any other configuration file is required for web applications.<br />

Listing 10-4 shows the web.xml file; this file should be put in the src/main/webapp/WEB-INF/ folder.<br />

Listing 10-4. web.xml<br />

<br />

<br />

<br />

mydocuments<br />

org.springframework.web.servlet.DispatcherServlet<br />

1<br />

<br />

<br />

mydocuments<br />

/mydocuments/*<br />

<br />

<br />

136

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!