JAVA
Spring:댓글더보기(ajax.ver)
docc
2021. 7. 26. 23:28
java 와 javascript 의 차이점 - 메서드에 매개변수의 유동성
void g(int a){}
// in java
g(); // 오류
//in javascript
g(); // 실행
g(5); // 실행
javascript 에는 undefined 형이 있기 때문에 매개변수를 넣야할 int a 부분에 아무것도 없어도 메서드가 실행된다. 그 값은 undefined 형으로 지정되어 있다. |
@ResponseBody 가 붙었을 때 반환형이 String 또는 void 형이면
/* 기존 컨트롤의 방식 */
@RequestMapping(...)
public String process(){}
// view명 반환으로 인식
/* ajax 연결 컨트롤의 방식 */
@RequestMapping(...)
@ResponseBody
public String process(){}
// Data 반환으로 인식
// view 반환이 아님
@RequestMapping(...)
@ResponseBody
public void process(HttpServletRequest request, HttpServletResponse response, ...)
// response 가 있기 때문에 혼자서 요청, 응답하여 이 컨트롤에서 작업이 끝난다고 인식
ajax 의 error
var 정상연결 = true;
var 보여줄댓글수 = 3;
function 화면갱신(){
if(정상연결){
$.ajax({
url:"/board/comments/${board.no}",
type:"POST",
success:function(result){
$("#comments").html(result);
},
error:function(){
정상연결:false;
alert("연결오류");
}
});
}
}
//비동기로 화면갱신!
setInterval(화면갱신, 3000);
error:function(){} : 연결신호가 안가고 에러 날때 error:function(){} 로 가고 if(정상연결) 이 false 가 되어 setInterval() 이 실행되도 ajax() 연결이 작동하지 않는다 |
아예 setInterval 를 멈추기
var 보여줄댓글수 = 3;
function 화면갱신(){
$.ajax({
url:"/board/comments/${board.no}",
type:"POST",
contentType:"application/json",
data:JSON.stringify({size:보여줄댓글수}),
success:function(result){
$("#comments").html(result);
},
error:function(){
clearInterval(intervalId);
alert("연결오류");
}
});
}
//비동기로 화면갱신!
var intervalId = setInterval(화면갱신, 3000);
setInterval() : 인터벌 아이디를 반환한다. clearInterval() : 인터벌 아이디를 매개값으로 넣으면 더 이상 setInterval() 이 작동 하지 않는다. |
댓글 더보기
>> 게시물상세창.jsp
<script>
var 보여줄댓글수 = 3;
function 화면갱신(){
$.ajax({
url:"/board/comments/${board.no}",
type:"POST",
contentType:"application/json",
data:JSON.stringify({size:보여줄댓글수}),
success:function(result){
$("#comments").html(result);
},
error:function(){
clearInterval(intervalId);
alert("연결오류");
}
});
}
//비동기로 화면갱신!
var intervalId = setInterval(화면갱신, 3000);
// 중략..
</script>
<body>
// 중략..
<!--댓글 쓰기 부분 -->
댓글 <textarea cols=40 rows=5 id="contents"></textarea>
<button type="button" onclick="댓글등록하다()">보내기</button><br>
<!-- 댓글들 출력 부분 -->
<div id="comments"></div>
<!-- 더보기 -->
<button type="button" onclick="더보기()">더보기</button>
</body>
>> 게시물컨트롤.java
1. JSON 을 String 으로 넘겨 객체가 된 걸 받을 클래스 생성
2. 컨트롤에 @RequestBody 로 1번의 객체를 매개변수로 넣는다
class DataSize{
int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
// 중략..
@RequestMapping(value="board/comments/{no}", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
@ResponseBody
public String 게시물댓글을출력하다(@PathVariable int no, @RequestBody DataSize dSize, HttpSession session) {
RefInteger totalSize = new RefInteger();
List<Comment> comments = commentDAO.selectByBoardNo(no, dSize.size, totalSize);
if(comments == null) {return "<p> 댓글이 없어요 </p>";}
ModelAndView mv = new ModelAndView();
String html="";
html+="<p>댓글수는 "+totalSize.value +"</p>";
html+="<ul>";
for(Comment comment : comments) {
html += "<li>";
html += String.format("<p>%s</p>", comment.getWriter().getName());
html += String.format("<p>%s</p>", comment.getWdate().toString());
html += String.format("<textarea cols=20 rows=5 readonly>%s</textarea><br>", comment.getContents());
html += "<button>좋아요</button><button>싫어요</button>";
html += "</li>";
}
html+="</ul>";
return html;
}
JSON 으로 js 에서 볼 댓글의 size 를 넘겨준다 넘길때 JSON 을 객체형태로 보내기 때문에 보내는 size 를 int형으로 멤버변수를 둔 객체를 따로 만들어야 한다. |