Controller
Spring Boot finds your controller by component-scanning the application's base package. It will autowire any dependencies, such as a DAO, provided it can find a satisfactory bean.
- Inject your DAO in your controller using an
@Autowiredannotation, so you can access it from within your@RequestMappingmethods.
@Controller
public class FilmController {
@Autowired
private FilmDAO filmDAO;
}
-
When you retrieve a JPA entity from a DAO, the returned entity is unmanaged.
-
Any changes you make to the entity will have no effect on the database, unless you merge it back into the persistence context.
@Controller
public class FilmController {
@Autowired
private FilmDAO filmDAO;
@RequestMapping(path = "getFilm.do", method = RequestMethod.GET)
public ModelAndView getFilm(@RequestParam("fid") int fid) {
ModelAndView mv = new ModelAndView();
Film film = filmDAO.findById(fid);
// film is unmanaged after it is outside of the transaction that exists in the DAO
mv.addObject("film", film);
mv.setViewName("WEB-INF/film/show.jsp");
return mv;
}
}
Drill¶
Create a JSP file called index.jsp in your
src/main/webapp/WEB-INFdirectory.Create a new directory inside of
src/main/webapp/WEB-INFnamedfilm.Create a JSP file called show.jsp in that directory.
src/main/webapp/ ├── WEB-INF ├── film │ └── show.jsp └── index.jsp
- In the com.example.bootmvc.controllers package:
- Add a class called FilmController to that package. Use the
@Autowiredannotation to inject your DAO.- In FilmController, create a request handling method that returns the name of your index.jsp.
Map this method to the request paths
/andindex.dowith the methodGET.@RequestMapping(path={"/","index.do"}) public String index() { return "WEB-INF/index.jsp"; // return "index"; // if using a ViewResolver. }Create a route (or RequestMapping) in FilmController mapped to
getFilm.do.- The method will take a single parameter
fidas a@RequestParam.- Use the DAO
findByIdmethod to find a film by the provided id and add it to the model.Return the view
WEB-INF/film/show.jsp.Modify your
index.jspfile to invoke your controller'sgetFilm.doroute<form action="getFilm.do" method="GET"> Film ID: <input type="text" name="fid" /> <input type="submit" value="Show Film" /> </form>Modify your
show.jspfile to display the film that will be attached to the model.<div> <h5>${film.title} (${film.releaseYear})</h5> <p>${film.description}</p> </div>