2017년 7월 31일 월요일

같은 페이지 내에서 데이터 주고 받기


제품 코드를 입력 하면 같은 페이지에서 해당 코드에 대한 정보 출력






같은 페이지에서 데이터를 주고 받기 위해서 그 페이지가 한번 거쳐다가 왓는지를 확인 하는 것이 필요하다. 그렇기에 2가지 방법이 있다.
1. 세션을 이용
2. 주소값으로 parameter를 넘겨서 확인하는 방법


이번에는 2번째 방법으로 구현해 보았다.


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
/// Controller
    @RequestMapping(value = "test1_search", method = RequestMethod.GET)
    public String search_(Model model, 
            @RequestParam(value="type", defaultValue="0")int type,
            @RequestParam(value="code", defaultValue="0")String code) {
        Test1 p = null;
        if(type==0){
            p = new Test1();
        }
        else if(type==2){
            try {
                p = t.getOne(code);
                if(p == null){
                    p = new Test1();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        model.addAttribute("obj", p);
        return "test1/search";
    }
    
    @RequestMapping(value = "test1_search", method = RequestMethod.POST)
    public String productSelect(@ModelAttribute("obj") Test1 p) {
        
        return "redirect:test1_search?type=2&code="+p.getCode();
    }
cs


먼저 type와 code의 기본 값을 0으로 세팅해 놓는다.

@RequestParam(value="type", defaultValue="0")int type,
            @RequestParam(value="code", defaultValue="0")String code) {

Test1 vo를 null로 초기화 시키고 만약 type 가 0이라면 초기화된 test1 vo값을 넣고
type가 2 라면 t.getOne(code)  DAO와 XML에서 얻은 값을 p에 넣어준다.
만약 p=null 사용자가 입력 한 것이 아무 것도 없으면 빈 VO를 그냥 넣어준다.(에러페이지방지)

Test1 p = null;
        if(type==0){
            p = new Test1();
        }
        else if(type==2){
            try {
                p = t.getOne(code);
                if(p == null){
                    p = new Test1();
                }

dao 와 xml

1
2
3
4
5
6
7
8
9
10
/// DAO
public Test1 getOne(String i){
        return sqlSession.selectOne("Test1.getOne", i);
    }
 
// XML
 
<select id="getOne" resultType="com.ds.vo.Test1" parameterType="String" >
        SELECT * FROM test_product WHERE code=#{code}
 </select> 
cs

POST에서 obj 로 보내온 JSP폼 모델을 받고 새 주소로 return 한다.

@ModelAttribute("obj") Test1 p

 redirect 할때 type=2로 고정해 주고 받아온 p.getCode()를 주소에 넣어 보낸다.
 return "redirect:test1_search?type=2&code="+p.getCode();

그러면 다시 GET페이지로 돌아가게 되어 if문이 시작되어 post에서 보낸
code를 이용해 데이터 베이스에서 값들을  가져와서 출력할수 있다.














댓글 없음:

댓글 쓰기