티스토리 뷰

It

Spring MVC 5-5 클라이언트 요청 처리

worknettwo 2023. 1. 27. 02:03

Spring MVC 5-5 ;클라이언트 요청 처리

;

HTML <form /> ;처리

이전 방식은 ;request ;객체의 ;getParameter() ;메서드를 이용

Command ;객체를 이용해 단순화시킬 수 있음.

login.jsp
<%@page contentType="text/html; charset=EUC-KR"%>
<html><head><title>로그인</title></head>
<body>
; ;<form action="loign.do" method="post">
; ; ; ;<table border="1" cellpadding="0" cellspacing="0">
; ; ; ; ; ; ;<tr><td>아이디</td><td><input name="id" type="text" /></td></tr>
; ; ; ; ; ; ;<tr><td>비밀번호</td><td><input name="password" type="password" /></td></tr>
; ; ; ; ; ; ;<tr>
; ; ; ; ; ; ; ; ;<td colspan="2" align="center">
; ; ; ; ; ; ; ; ; ; ; ;<input type="submit" value="로그인" />
; ; ; ; ; ; ; ; ;</td>
; ; ; ; ; ; ;</tr>
; ; ; ;</table>
; ;</form>
</body>
</html>

;

command ;객체 구현

폼 필드의 ;name ;속성과 일치하도록 멤버변수명을 지정한다.

;

UserVO.java
public class UserVO {
; ; ; ; ; ; ; ; ; ; ;private String id;
; ; ; ; ; ; ; ; ; ; ;private String password;
; ; ; ; ; ; ; ;// public Getter/Setter methods
}

;

LoginController.java
@Controller
public class LoginController implements Controller {
@RequestMapping("/loign.do")
public String login(UserVO vo) throws Exception {
; ; ; ;UserVO user = userService.getUser(vo);
; ; ; ;return "loginResult";
}
}

;

JSP ;에서 ;Command ;객체 활용

Command ;객체에 저장된 정보는 ;JSP에서 ;${…} ;구문으로 이용 가능

<body>

; ; ; ;<h3>${userVO.id}님 로그인 환영합니다.</h3>

</body>

;

;

;

만일 ;Command ;클래스의 이름을 변경하고자 한다면 ;@ModelAttribute Annotation을 사용함.

@RequestMapping("/loign.do")

public String login(@ModelAttribute("user") ;UserVO vo) throws Exception {

; ; ;

}

<body>

; ; ; ;<h3>${user.id}님 로그인 환영합니다.</h3>

</body>

;

@RequestParam ;사용

request.getParameter() : ;코딩량 증가, ;불편

Command ;객체 ;: ;요청 파라미터와 동일한 이름의 속성이 ;Command ;객체에 존재해야 함.

Command ;객체에는 없는 파라미터는?

@RequestParam Annotation으로 해결

TestController.java
@RequestMapping(value="/test1.do", method=RequestMethod.GET)
public String test(
; ; ;@RequestParam("cond") String condition,
; ; ;@RequestParam("keyword") String keyword) {
; ; ;System.out.println("검색조건 ;: " + condition);
; ; ;System.out.println("검색단어 ;: " + keyword);
; ; ;return "test.jsp";
}

;

;

@RequestParam ;사용시 주의사항

모든 파라미터를 반드시 입력해야 실행됨

왜냐하면? required ;속성의 기본값이 ;true ;이기 때문에...

type ;변환이 불가능한 경우 해당 메서드를 실행하지 못함.

해결책

필수입력항목이 아닌 것들은 ;required ;속성을 ;false로 지정

잘못 입력된 값을 위해 ; ;defaultValue를 부여

type변환이 불가능한 경우를 위한 에러 처리

;

;

@RequestParam ;사용 ; ;이어서

TestController.java
@RequestMapping(value="/test1.do", method=RequestMethod.GET)
public String test(
; ;@RequestParam(value="cond", required=false, defaultValue="name") ;String condition,
; ;@RequestParam(value="keyword", required=false, defaultValue="obama") ;String keyword) {
; ;System.out.println("검색조건 ;: " + condition);
; ;System.out.println("검색단어 ;: " + keyword);
; ;return "test.jsp";
}

/test1.do

condition : name, keyword : obama

/test1.do?keyword=romney

condition : name, keyword : obama

/test1.do?cond=tel&keyword=010-222-3333

condition : tel, keyword : 010-222-3333

;

@RequestParam ;사용 ; ;이어서

TestController.java
@RequestMapping(value="/test2.do", method=RequestMethod.GET)
public String test2(
; ;@RequestParam(value="pageno", required=false, defaultValue="1") ;int pageno) {
; ;System.out.println("페이지번호 ;: " + pageno);
; ;return "test.jsp";
}

;

/test2.do

페이지 번호 ;: 1

/test2.do?pageno=2

페이지 번호 ;: 2

/test2.do?pageno=abc

Exception ;발생

;

Servlet API ;사용

Spring MVC에서는 매개변수로 다음 타입의 파라미터는 언제든 전달 가능. ;기존의 파라미터에 파라미터를 추가하면 됨.

ServletRequest / HttpServletRequest

ServletResponse / HttpServletResponse

HttpSession

;

LoginController.java
@Controller
public class LoginController {
; ; ; ; ; ;@RequestMapping("/login.do")
; ; ; ; ; ;public String login(UserVO vo, ;HttpServletRequest request) {
; ; ; ; ; ; ; ; ;UserDAO dao = new UserDAO();
; ; ; ; ; ; ; ; ;UserVO user = dao.getUser(vo);
; ; ; ; ; ; ; ; ;if(user != null){
; ; ; ; ; ; ; ; ; ; ; ;request.getSession().setAttribute("userId", user.getId());
; ; ; ; ; ; ; ; ; ; ; ;return "redirect:/getUserList.do";
; ; ; ; ; ; ; ; ;}else{
; ; ; ; ; ; ; ; ; ; ; ;return "login.jsp";
; ; ; ; ; ; ; ; ;}
; ; ; ; ; ;}
}

;

Controller의 리턴 타입

지원하는 주요 리턴 타입

타입 설명
ModelAndView Model ;View ;정보가 저장된 객체다.
String View ;정보를 정확한 이름으로 설정한다.
Model View에 전달할 객체들을 담고 있는 ;Model ;객체다.
Map View에 전달할 정보가 저장된 ;Map ;객체를 리턴한다. ;이때 ;View ;이름은 요청 ;URL을 통해서 자동으로 결정된다.

;

;

String ;을 리턴하는 경우

view ;정보만을 알려줌

ModelAndView ;객체를 리턴하는 경우

가장 범용적으로 사용됨.

model ;정보와 ;view ;정보를 ;ModelAndView ;객체에 함께 담아서 전달

redirect ;하기

view ;정보를 ;"redirect:/list.do" ;와 같은 형태로 전달하면 됨.

;

;

;

Model ;데이터 생성

Model ;객체 ;: view로 전달하고자 하는 정보를 담은 객체

ModelAndView ;객체 활용

model ;객체와 ;view ;정보를 한번에 리턴할 수 있음.

GetUserController.java
import org.springframework.ui.ModelAndView;
@Controller
public class GetUserController {
@RequestMapping("/getUser.do")
public ;ModelAndView ;getUser(UserVO vo) {
; ; ; ;ModelAndView mav = new ModelAndView();
; ; ; ;UserVO user = userDAO.getUser(vo);
; ; ; ;mav.addObject("user", user);
; ; ; ;mav.setViewName("getUser.jsp");
; ; ; ;return mav;
}
}

;

view에서는 ;${} ;구문을 이용하거나 ;request.getAttribute() ;문을 이용해 ;model ;객체의 정보에 접근할 수 있음.

;

Model ;객체를 파라미터로 전달

Model ;타입의 파라미터 사용

리턴 타입은 ;String으로

GetUserController.java
import org.springframework.ui.Model;
@Controller
public class GetUserController {
; ; ; ; ; ; ; ; ; ; ;@RequestMapping(params="method=getUser")
; ; ; ; ; ; ; ; ; ; ;public String getUser(UserVO vo, ;Model model) {
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;UserVO user = userService.getUser(vo);
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;model.addObject("user", user);
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;return "getUser.jsp";
; ; ; ; ; ; ; ; ; ; ;}
}

Map ;객체 활용

Model ;객체 활용 방법과 유사

GetUserController.java
import java.util.Map;
@Controller
public class GetUserController {
; ; ; ; ; ; ; ; ; ; ;@RequestMapping(params="method=getUser")
; ; ; ; ; ; ; ; ; ; ;public String getUser(UserVO vo, ;Map<String, UserVO> model) {
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;UserVO user = userService.getUser(vo);
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;map.put ("user", user);
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;return "getUser.jsp";
; ; ; ; ; ; ; ; ; ; ;}
}

;

;

ModelMap ;객체 활용

예제 생략

;

@ModelAttribute

기능

@RequestMapping Annotation이 적용되지 않은 별도의 메서드로 ;Model에 추가될 객체를 생성할 수 있음

@RequestMapping ;이 적용된 메서드보다 먼저 실행됨.

Command ;객체 초기화 작업 수행

;

GetBoardListController.java
@Controller
public class GetBoardListController {
@ModelAttribute("searchConditionList")
public ArrayList<CodeVO> makeSearchConditionList() {
; ; ; ; ; ; ; ; ; ; ;ArrayList<CodeVO> searchConditionList = new ArrayList<CodeVO>();
; ; ; ; ; ; ; ; ; ; ;searchConditionList.add(new CodeVO(1, "제목"));
; ; ; ; ; ; ; ; ; ; ;searchConditionList.add(new CodeVO(2, "내용"));
; ; ; ; ; ; ; ; ; ; ;searchConditionList.add(new CodeVO(3, "제목+내용"));
return searchConditionList;
}
; ; ;
@RequestMapping("/getBoardList.do")
public String getBoardList(@ModelAttribute("board") BoardVO vo, Model model) {
; ; ; ; ; ; ; ; ; ; ;ArrayList<BoardVO> boardList = boardService.getBoardList(new BoardVO());
; ; ; ; ; ; ; ; ; ; ;model.addAttribute("boardList", boardList);
; ; ; ; ; ; ; ; ; ; ;return "getBoardList.jsp";
}
}

;

;

;

;

;

;

@ModelAttribute – ;이어서

getBoardList.jsp
<form action="board.sds?method=getBoardList" method="post">
<table border="1" cellpadding="0" cellspacing="0" width="700">
<tr><td align="right">
<select name="searchCondition">
<c:forEach var="searchType" items="${searchConditionList}">
; ; ; ; ; ; ; ; ; ; ;<option value="${searchType.code}"/>${searchType.codeName}
</c:forEach> ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
</select>
<input type="text" name="searchKeyword" value="${board.searchKeyword}"/>
<input type="submit" value=" ;검색 ;"/>
</td></tr>
</table>
</form>

;

위 예제는 ;JSTL ;적용한 것임. ;다음과 같이 획득해도 됨.

ArrayList<CodeVO> list =

; ; ; ; ; ;(ArrayList<CodeVO>)request.getAttribute("searchConditionList");

;

;

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함