SpringMVC 의 Model 대상 용법 설명

4431 단어 SpringMVCModel대상
모델 대상 의 역할 은 주로 데 이 터 를 저장 하 는 것 으로 데 이 터 를 전단 으로 가 져 갈 수 있다.
자주 사용 하 는 모델 대상 은 다음 과 같은 몇 가지 가 있다.ModelAndView(말 그대로 모델 과 보 기 는 데이터 정 보 를 휴대 할 수도 있 고 보기 정 보 를 휴대 할 수도 있 습 니 다.일반적인 용법 은 다음 과 같 습 니 다)

    /**
     * ModelAndView         (ModelMap       View      )
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/case2")
    public ModelAndView case2() throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/demo03/model.jsp");
        mav.addObject("sex", "boy");
        return mav;
    }
Map,modelAndView원리 와 마찬가지 로 데 이 터 를 하나씩requestScope에 놓 고 전단 에서 데 이 터 를 추출 하 는 것 도${모델 데이터}입 니 다.

    /**
     *          Map   (        Model     ModelMap   )   . 
     * @param map
     * @return
     */
    @RequestMapping("/case")
    public String case1(Map map) throws Exception{
        map.put("sex", "    !!");
        return "/demo03/model.jsp";
    }
@SessionAttributes(창설session대상 에 해당 하 며session대상 에 데 이 터 를 넣 고 주석 하나 로 완벽 하 게 해결)
기본 형식 은 다음 과 같 습 니 다.

/**
 * @SessionAttributes                       (        value    ),
 *                              (        types    )
 *   :            .           map  session           ,  String     
 */
@SessionAttributes("user")
@Controller
public class SessionController { 
 @ModelAttribute("user")
 public User getUser(){
  User user = new User();
  return user;
 }
 /**
  * http://localhost:8080/s/s1?id=1
  *      forward:        
  *       redirect:   SessionAttribute                   session  【      】
  * @return
  * @throws Exception
  */
 @RequestMapping(value="/s1",method=RequestMethod.GET)
 public String case1(@ModelAttribute("user") User user) throws Exception{
  return "redirect:/s2";
 }
 
 @RequestMapping(value="/s2",method=RequestMethod.GET)
 public String case2(Map map,HttpServletResponse res,SessionStatus sessionStatus) throws Exception{
  User user=(User)map.get("user");
  res.getWriter().println(user.getId());
  sessionStatus.setComplete();
  return null;
 }
}
SpringMVC 의 Model 과 Model AndView 의 차이 점
1.주요 차이 점Model은 요청 할 때마다 존재 하 는 기본 매개 변수 로addAttribute()방법 으로 서버 의 값 을jsp페이지 에 전달 할 수 있 습 니 다.ModelAndViewmodelview두 부분 을 포함 하고 사용 시 자체 예화 가 필요 하 며ModelMap를 이용 하여 값 을 전달 할 수도 있 고view의 이름 을 설정 할 수도 있다.
2.예
1)사용Model전송 값

@RequestMapping(value="/list-books")
 private String getAllBooks(Model model){
  logger.error("/list-books");
  List<Book> books= bookService.getAllBooks();
  model.addAttribute("books", books);
  return "BookList";
 }
jsp페이지 이익${books}에서 그 중의 값 을 추출 할 수 있다.
2)사용ModelAndView전달 치 는 두 가지 방법 이 있 는데 서로 다른 방법 으로jsp페이지 의 수치 채취 방식 이 다 르 고view의 이름 을 설정 했다.

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
        LibraryException le=null;
        if(ex instanceof LibraryException){
            le=(LibraryException)ex;
        }else{
            le=new LibraryException("      !");
        }
 
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("exception",le.getMessage());
        modelAndView.getModel().put("exception",le.getMessage());
        modelAndView.setViewName("error"); 
        return modelAndView;
    }
jsp${requestScope.exception1}의 값 을 꺼 낼 수 있다.exception1jsp의 값 을 추출 할 수 있 습 니 다${exception2}이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기