Spring MVC的控制器的開發流程
技術標籤:Servlet、JSP、框架
控制器的開發過程
一般分為3步
獲取request請求引數
不建議在註解@RequestMapping的方法的引數中,使用Servlet容器給與的API,比如不建議下面的寫法:
這樣寫,使用了原生API中的 HttpSession和HttpServletRequest,也就和Tomcat這種特定容器關聯了。不利於擴充套件和測試。
Spring MVC可以通過更多的註解來獲取請求引數,比如引數註解@RequestParam(“ ”)
以獲取請求引數id為例:Spring MVC可以這麼寫控制器
@RequestMapping(value=”/index2”, method=RequestMethod.GET)
public ModelAndView index2(@RequestParam(“id”) Long id ){
System.out.println(“param[id]=”+id);
ModelAndView mv = new ModelAndView();
mv.setViewName(“index”);
return mv;
}
注意,這裡引數是Long型的,是在進入index2方法之前,先有如下轉換:
String str = request.getParameter(“id”);
Long id = Long.parseLong(str);
獲取session中的引數
假如登入系統已經在Session中設定了userName這個域物件,如何在控制器中進行獲取?
使用註解@SessionAtrribute去從Session中獲取對應的資料,例如:某個控制器類中的方法的寫法
@RequestMapping(value=”/index3”, method=RequestMethod.GET)
public ModelAndView index3(@SessionAttribute(“userName”) String userName ){
System.out.println(“session[userName]=”+ userName);
ModelAndView mv = new ModelAndView();
mv.setViewName(“index”);
return mv;
}
處理業務邏輯(資料模型元件) 【控制器的寫法】
以上的業務邏輯,是簡單的打印出 request請求、session域物件中的引數
但其實更多的Servlet的業務是進行Service層中的方法的呼叫。
比如,有一個Spring MVC的控制器 RoleController,在其中去注入Spring IoC容器中已經存在的業務層類RoleService,並RoleService類中有一個查詢的業務方法getRole(long id ) ;
Spring MVC中我們要做的是把這個RoleService類中的業務方法getRole(long id ) 在控制器中進行@RequestMapping(value= ”/getRole”的注入。
下面是控制器的寫法
@Controller
@RequestMapping(“/role”) //把RoleController控制器 與 瀏覽器請求的URI “/role/*****”對映在一起
public class RoleController{
@Autowired //把Service層的一個類作為屬性注入Spring IoC
Private RoleServiceroleService = null ;
@RequestMapping(value= ”/getRole”, method=”RequestMethod.GET”)
//把該方法 與 瀏覽器請求的/role/getRole.do”對映在一起,但要注意,字尾的匹配是在web.xml中配置的Spring MVC的排程器DispatcherServlet的攔截中配置的
public ModelAndView getRole(@RequestParam(“id”) Long id)
Role role = roleService.getRole(id);
ModelAndView mv = new ModelAndView();
mv.setViewName(“roleDetails”);
mv.addObject(“role”, role ); //給資料模型新增一個角色物件
return mv;
}
}
繫結模型和檢視
待續