jsp에서 <a>태그에 href값을 주면 get방식으로 넘어간다. 

하지만 post로 넘기고 싶다면?

=> onClick이벤트로 자바스크립트 함수를 추가하고 그 함수안에서 post로 넘기면 된다.

 

 

1. 컨트롤러로 넘기는 값이 없을때

(1) JSP (form 태그로 안감싸도 된다.)

1
<a href="javascript:void(0)" onClick="javascript:goPost()">클릭시 POST로 페이지 </a>
cs

(2) Javascript 함수 (method는 post, 컨트롤러 주소는 goPost.do)

1
2
3
4
5
6
7
function goPost(){
    let f = document.createElement('form');
    f.setAttribute('method''post');
    f.setAttribute('action''goPost.do');
    document.body.appendChild(f);
    f.submit();
}
cs

 

(3)Controller (goPost.do로 호출되고 post.jsp라는 페이지로 이동한다)

1
2
3
4
@PostMapping("goPost.do")
public String go_post(){
    return "post";
}
cs

 

전달하는 값은 없지만 굳이 PostMapping으로 페이지 이동을 해야할때 사용 

 

 

2. 컨트롤러로 넘기는 값이 있을때

(1) JSP (jstl 태그의 값을 인수로 넘겨준다고 쳤을때)

1
<a href="javascript:listView('${list.userid}')">유저아이디</a>
cs

이전에는 보통 다음과 같이 getMapping으로 넘어가도록 했었다.

1
<a href="getView.do?userid=${list.userid}">유저아</a>
cs

 

 

(2) Javascript 함수

hidden 타입의 input태그를 만들어서 그 value값에 전달하고자 하는 인수를 집어넣고, userid란 이름으로 넘기겠다는 뜻이다.

method는 post, 컨트롤러 주소는 view.do이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function listView(userid){
    let f = document.createElement('form');
    
    let obj;
    obj = document.createElement('input');
    obj.setAttribute('type''hidden');
    obj.setAttribute('name''userid');
    obj.setAttribute('value', userid);
    
    f.appendChild(obj);
    f.setAttribute('method''post');
    f.setAttribute('action''view.do');
    document.body.appendChild(f);
    f.submit();
}
cs

 

(3)Controller

1
2
3
4
5
6
@PostMapping("view.do")
public String getView(String userid, Model model){
    User userView = userService.view(userid);
    model.addAttribute("userView", userView);
    return "view";
}
cs

 

 

'Learning > HTML&JavaScript' 카테고리의 다른 글

과제-반응형 웹 만들고 이력서와 회원가입 페이지 연결하기  (0) 2020.08.04
반응형 웹 디자인  (0) 2020.08.04
DOM, BOM  (0) 2020.08.04
자바스크립트 함수 2  (0) 2020.08.03
자바스크립트 함수 1  (0) 2020.07.31

메이븐 기반 웹프로젝트

게시판에 파일 입력하기

 

  • pom.xml

⇒ MultipartResolver를 사용하기 위해 Apache Commons FileUpload를 pom.xml 디펜던시에 추가

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
cs

 

 

  • jsp
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
        <!-- 파일업로드는 multipart/form-data -->
        <form action="" id="frm" method="post" enctype="multipart/form-data">
            <br/><br/>
            <div class="form-group">
                제목
                <input type="text" class="form-control" id="title" name="title">
                <div id="title_check"></div>
            </div>
            
            <div class="form-group">
                파일 
                <input type="file" class="form-control" id="file" name="file">
            </div>
            
            <div class="form-group">
                내용 
                <textarea class="form-control" rows="10" id="content" name="content"></textarea>
                <div id="content_check"></div>
            </div>
            
            <div class="text-center">
                <a id="sendBtn" class="btn btn-primary">작성</a>
                <a id="resetBtn" class="btn btn-danger">취소</a>
            </div>
        </form>
cs

 

 

  • javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//작성버튼을 눌렀을 경우
    $("#sendBtn").click(function(){
        var formData = new FormData($("#frm")[0]);
        
        $.ajax({
            url: "boardInsert.do",
            type: "post",
            enctype: "multipart/form-data",
            data: formData,
            processData: false,
            contentType: false,
            success: function(val){
                if(val == 1){
                    alert("글을 입력하였습니다."); location.href="/mvnschool/board.do";
                }else{
                    alert("전송 실패");
                }
            },
            error: function(e){
                alert(e);
            }
        })//ajax
    }); //sendBtn
cs

 

 

 

  • Controller

⇒ 컨트롤러에서 부를때 그냥 HttpServletRequest로 부르지말고 MultipartHttpServletRequest로 불러야함

⇒ MultipartFile 객체를 생성하여 MultipartHttpServletRequest의 getFile메소드로 불러온 파일을 저장

⇒ 저장할 경로 지정

⇒ 가져온 원본파일의 이름에 중복방지를 위해 time을 추가하고 지정한 경로에 파일 생성

⇒ db에는 그 파일의 이름이 저장됨

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
32
33
34
35
36
37
38
39
40
41
    @RequestMapping(value="/boardInsert.do", method = RequestMethod.POST)
    @ResponseBody
    public int boardInsert(HttpServletRequest request, MultipartHttpServletRequest multiRequest,
            @ModelAttribute Board board) throws IllegalStateException, IOException{
        //글쓴이 정보 생성
        HttpSession session = request.getSession();
        String userno = (String)session.getAttribute("userno");
        User user = userDAO.userView(userno);
        String name = user.getName();
 
        //board에 글쓴이 정보를 세팅
        board.setUserno(userno);
        board.setName(name);
        
        MultipartFile mf = null;
        //파일을 업로드 하지 않는다면 fileupload 컬럼에는 그냥 null이 입력됨
        if(multiRequest.getFile("file").getSize() != 0){
            mf = multiRequest.getFile("file"); //input file로 넘어온 값
            
            //경로 지정
            String path = "D:\\kj\\mvnschool\\webapp\\WEB-INF\\upload";
            File fileDir = new File(path);
            if(!fileDir.exists()){
                fileDir.mkdirs();
            }
 
            //중복방지를 위해 time 추가
            long time = System.currentTimeMillis();
            String originFileName = mf.getOriginalFilename(); //원본 파일명
            String saveFileName = String.format("%d_%s", time, originFileName); //저장 파일명
            
            //파일 생성
            mf.transferTo(new File(path, saveFileName)); 
 
            board.setFileupload(saveFileName);
        }
        
        int result = boardDAO.boardInsert(board);
        
        return result;
    }
cs

 

 

  • dao
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
//게시판 업로드
    public int boardInsert(Board board){
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;
        
        try {
            conn = getConnection();
            String sql = "insert into board "
                    + "(bnum, userno, name, title, content, hit, regdate, replycnt, fileupload) "
                    + "values('BOA' || board_seq.nextval, ?, ?, ?, ?, 0, sysdate, 0, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, board.getUserno());
            pstmt.setString(2, board.getName());
            pstmt.setString(3, board.getTitle());
            pstmt.setString(4, board.getContent());
            pstmt.setString(5, board.getFileupload());
            result = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConnection(conn, pstmt);
        }
        return result;
    }
cs
 
 
 

1. 메이븐 기반 프로젝트이므로 pom.xml에 javax.mail 디펜던시 추가

 

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>
cs

 

 

2. selectbox 선택부분

  • jsp
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
32
33
34
35
<table class="table table-hover">
            <colgroup>
            <col width="5%"/>
            <col width="5%"/>
            <col width="10%"/>
            <col width="10%"/>
            <col width="40%"/>
            <col width="10%"/>
            <col width="20%"/>
        </colgroup>
        <thead>
            <tr>
                <th scope="col"><input type="checkbox" name="select_all" id="select_all" value="select_all"></th>
                <th scope="col">No.</th>
                <th scope="col">이름</th>
                <th scope="col">아이디</th>
                <th scope="col">주소</th>
                <th scope="col">전화번호</th>
                <th scope="col">이메일</th>
            </tr>
        </thead>
        <tbody>
                <c:forEach items="${list}" var="list" varStatus="st">
                    <tr>
                        <td><input type="checkbox" name="select_tch" id="select_tch" value="${list.userno}"></td>
                        <td>${rowNo-st.index}</td>
                        <td>${list.name}</td>
                        <td>${list.userid}</td>
                        <td>${list.address}</td>
                        <td>${list.phone}</td>
                        <td>${list.email}</td>
                    </tr>
                </c:forEach>
        </tbody>
</table>
cs

 

  • javascript

맨 윗줄 checkbox를 체크하면 전체선택이 되도록, 한번더 누르면 전체선택이 해제되도록 설정

 

1
2
3
4
5
6
7
8
//전체선택 구현 (id=select_all을 누르면 모든 checkbox 타입의 input box의 checked를 true로 바꿔라)
    $("#select_all").on("click",function(){
        if($("input:checkbox[id = 'select_all']").prop("checked")){
            $("input[type=checkbox]:not(:disabled)").prop("checked"true);
        }else{
            $("input[type=checkbox]:not(:disabled)").prop("checked"false);
        }
    });
cs

 

교사 승인 버튼을 눌렀을 경우 체크박스의 value (user의 userno, email값)를 배열에 담고 json형태로 바꿔서 넘기기

 

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
32
//교사 승인 버튼을 눌렀을경우 체크박스의 value(user의 userno), email 값을 배열에 담고 json형태로 바꿔서 넘긴다.
    $("#tchProveBtn").click(function(){
        var checkbox = $("input[name='select_tch']:checked");
        var jarr = [];
        
        $(checkbox).each(function(i){
            var tr = checkbox.parent().parent().eq(i);
            var td = tr.children();
            
            var userno = $(this).val(); //체크박스의 value값
            var email = td.eq(6).text(); //0번째부터 시작이므로 마지막 줄의 td의 값
            
            jarr.push({"userno": userno, "email": email}); //배열에 userno와 email을 담는다.
        });
        var jStr = JSON.stringify(jarr); //json형태 문자열로 바꾸기
        
        if(jarr.length >= 1){
//json형태 data를 컨트롤러로 넘긴다.
            $.ajax({
                url: "tchProve.do",
                type: "post",
                data: {
                    "jStr": jStr
                },
                success: function(val){
                    if(val>=1){
                        alert("교사 승인이 완료되었습니다.");
                        location.href="/mvnschool/tchWaitList_pre.do";
                    }
                }
            })
        }
    }); //tchProveBtn
cs

userno는 dao에서 update를 하기 위해 필요한 값이고

email은 수신자 메일주소이다.

 

 

  • Controller.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//교사 승인 -> dao를 통해 role이 2로 업데이트되고, 해당회원의 이메일로 메일 발송
    @RequestMapping(value="tchProve.do", method = RequestMethod.POST)
    @ResponseBody
    public int tchProve(@RequestParam(value="jStr"String jStr) throws AddressException, MessagingException{
        int result = -1;
        JSONArray jsonArr = new JSONArray(jStr);

//이메일 주소들을 List에 담는다.
        List<String> emailList = new ArrayList<>();
        for(int i=0; i<jsonArr.length(); i++){
            JSONObject jsonObject = jsonArr.getJSONObject(i);
            String userno = (String) jsonObject.getString("userno");
            String email = (String) jsonObject.getString("email");
            emailList.add(email);
            result = userDAO.tchProve(userno);
        }
        
        //이메일로 메일 발송
        SendEmail.sendEmail(emailList);
        
        return result;
    }
cs

JSONArray를 통해 받아온 jStr을 다시 JSON 배열 형태로 풀어준다. 

그 배열의 크기만큼 반복문을 돌려서 JSONObject로 하나씩 뽑아낸다. 

 

userno는 dao와 연결시키고,

email은 List에 담은 후 자바메일 발송을 위해 만들어놓은 클래스의 함수와 연결시킨다.

 

 

  • dao
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//교사 승인
    public int tchProve(String userno){
        Connection conn = null;
        Statement st = null;
        int result = 0
        try {
            conn = getConnection();
            String sql = "update user_haksa set role =2 where userno='"+userno+"'";
            st = conn.createStatement();
            result = st.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConnection(conn, st, null);
        }
        return result; 
    }
cs

 

 

  • SendEmail.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.mvnschool.vo;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class SendEmail {
    static String host = "smtp.naver.com";
    static int port = 465;
    static String username = "네이버아이디@naver.com";
    static final String password = "네이버비밀번호";
    
    static String subject = "교사 승인";
    static String contents = "교사 승인 알람 메일";
 
    public static void sendEmail(List<String> emailList) throws AddressException, MessagingException{
        //서버정보 설정
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth""true");
        props.put("mail.smtp.ssl.enable""true");
        props.put("mail.smtp.ssl.trust", host);
        
        //세션 생성 & 발신자 smtp 서버 로그인 인증
        Session session = Session.getInstance(props, new javax.mail.Authenticator(){
            protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
                return new javax.mail.PasswordAuthentication(username, password);
            }
        });
        session.setDebug(true); //디버그 모드
        
        //MimeMessage 생성 & 메일 세팅
        Message mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(username)); //발신자
        
        System.out.println("mailSession success");
        
        //가져온 리스트의 사이즈만큼 InternetAddress 배열 크기 정하기
        InternetAddress[] addArray = new InternetAddress[emailList.size()];
        for(int i=0; i<emailList.size(); i++){ //배열에 이메일을 저장
            addArray[i] = new InternetAddress(emailList.get(i));
        }
        mimeMessage.setRecipients(Message.RecipientType.TO, addArray);
        mimeMessage.setSubject(subject); //메일 제목
        mimeMessage.setText(contents); //메일 내용
        
        //메일 보내기
        Transport.send(mimeMessage);
        System.out.println("success sending email");
        
    }
}
cs

⇒ 자바메일 설정하는 동안 만났던 오류들
1. ssl관련 에러

("mail.smtp.ssl.enable", "true" , "mail.smtp.ssl.true", "smtp.naver.com" 처럼 설정을 해주니까 해결)


2. username과 password 관련 에러

(발신자 smtp 서버 로그인 인증을 해야함. Authenticator만들기. 관련 주석의 밑에줄)

 

3. 그 외

메일을 보낼때 mimeMessage에 addRecipients말고 setRecipients(Message.RecipientType.TO, addArray)를 하니까

(List로 가져온 메일 주소 String을 배열 []로 풀어서 저장) 잘 보내짐.

 

 

+ Recent posts