Git-Hub
https://github.com/braverokmc79/spring_boot_demo2
ApiAnswerController
package net.slipp.web;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.slipp.domain.Answer;
import net.slipp.domain.AnswerRepository;
import net.slipp.domain.Question;
import net.slipp.domain.QuestionRepository;
import net.slipp.domain.Result;
import net.slipp.domain.User;
@RestController
@RequestMapping("/api/questions/{questionId}/answers")
public class ApiAnswerController {
@Autowired
private QuestionRepository questionRepository;
@Autowired
private AnswerRepository answerRepository;
@PostMapping("")
public Answer create(@PathVariable Long questionId, String contents, HttpSession session){
if(!HttpSessionUtils.isLoginUser(session)){
return null;
}
User loginUser =HttpSessionUtils.getUserFromSession(session);
Question question =questionRepository.findOne(questionId);
Answer answer =new Answer(loginUser, question, contents);
return answerRepository.save(answer);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Long questionId, @PathVariable Long id, HttpSession session){
if(!HttpSessionUtils.isLoginUser(session)){
return Result.fail("로그인해야 합니다.");
}
Answer answer =answerRepository.findOne(id);
User loginUser =HttpSessionUtils.getUserFromSession(session);
if(!answer.isSameWriter(loginUser)){
return Result.fail("자신의 글만 삭제 할 수 있습니다.");
}
answerRepository.delete(id);
return Result.ok();
}
}
show.html
<div class="qna-comment">
<div class="qna-comment-slipp">
<p class="qna-comment-count"><strong>2</strong>개의 의견</p>
<div class="qna-comment-slipp-articles">
{{#answers}}
<article class="article" id="answer-1405">
<div class="article-header">
<div class="article-header-thumb">
<img src="https://graph.facebook.com/v2.3/1324855987/picture" class="article-author-thumb" alt="">
</div>
<div class="article-header-text">
<a href="/users/1/자바지기" class="article-author-name">{{writer.userId}}</a>
<a href="#answer-1434" class="article-header-time" title="퍼머링크">
{{getFormattedCreateDate}}
</a>
</div>
</div>
<div class="article-doc comment-doc">
<p>{{contents}}</p>
</div>
<div class="article-util">
<ul class="article-util-list">
<li>
<a class="link-modify-article" href="/questions/413/answers/1405/form">수정</a>
</li>
<li>
<a class="link-delete-article" href="/api/questions/{{question.id}}/answers/{{id}}">삭제</a>
</li>
</ul>
</div>
</article>
{{/answers}}
<form class="answer-write" method="post" action="/api/questions/{{id}}/answers">
<div class="form-group" style="padding:14px;">
<textarea class="form-control" placeholder="Update your status" name="contents"></textarea>
</div>
<input type="submit" class="btn btn-success pull-right" value="답변하기" >
<div class="clearfix" ></div>
</form>
</div>
</div>
</div>
scripts.js
$(".answer-write input[type=submit]").click(addAnswer);
$(".link-delete-article").click(deleteAnswer);
function addAnswer(e){
e.preventDefault();
console.log("click!");
var queryString=$(".answer-write").serialize();
console.log("query : " +queryString);
var url =$(".answer-write").attr("action");
console.log("url : " + url);
$.ajax({
type:'post',
url :url,
data: queryString,
dataType :'json',
error :onError,
success:onSuccess
});
}
function onError(){
console.log("error");
}
function onSuccess(data, status){
console.log(data);
var answerTemplate =$("#answerTemplate").html();
var template =answerTemplate.format(data.writer.userId, data.formattedCreateDate, data.contents, data.questionId, data.id);
$(".qna-comment-slipp-articles").prepend(template);
$("textarea[name=contents]").val("");
}
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
function deleteAnswer(e){
e.preventDefault();
var url =$(this).attr("href");
console.log("답변 삭제" + url);
var thisDelete=$(this);
$.ajax({
type :'delete',
url: url,
dataType : 'json',
error :function (xhr, status){
console.log("error");
},
success:function(data, status){
console.log(data);
if(data.valid){
thisDelete.closest('article').remove();
}else{
alert(data.errorMessage);
}
}
});
}
class Answer
package net.slipp.domain;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonProperty;
@Entity
public class Answer {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(foreignKey =@ForeignKey(name ="fk_answer_writer"))
private User writer;
@ManyToOne
@JoinColumn(foreignKey=@ForeignKey(name="fk_answer_to_question"))
private Question question;
@Lob
private String contents;
private LocalDateTime createDate;
public Answer(){
}
public Answer(User writer, Question question, String contents){
this.writer=writer;
this.question=question;
this.contents=contents;
this.createDate=LocalDateTime.now();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getWriter() {
return writer;
}
public void setWriter(User writer) {
this.writer = writer;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public LocalDateTime getCreateDate() {
return createDate;
}
public void setCreateDate(LocalDateTime createDate) {
this.createDate = createDate;
}
public String getFormattedCreateDate(){
if(createDate ==null){
return "";
}
return createDate.format(DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss"));
}
@Override
public String toString() {
return "Answer [id=" + id + ", writer=" + writer + ", question=" + question + ", contents=" + contents
+ ", createDate=" + createDate + "]";
}
public Long getQuestionId() {
return question.getId();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Answer other = (Answer) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public boolean isSameWriter(User loginUser) {
return this.writer.equals(loginUser);
}
}
class Question
package net.slipp.domain;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonProperty;
@Entity
public class Question {
@Id
@GeneratedValue
@JsonProperty
private Long id;
@ManyToOne
@JoinColumn(foreignKey=@ForeignKey(name="fk_question_writer"))
@JsonProperty
private User writer;
@JsonProperty
private String title;
@Lob
@JsonProperty
private String contents;
@Temporal(TemporalType.TIMESTAMP)
private Date datetime;
@OneToMany(mappedBy="question")
@OrderBy("id DESC")
private List<Answer> answers;
public Question() {
}
public Question(User writer, String title, String contents) {
this.datetime = new Date();
this.writer = writer;
this.title = title;
this.contents = contents;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getWriter() {
return writer;
}
public void setWriter(User writer) {
this.writer = writer;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public Date getDatetime() {
return datetime;
}
public void setDatetime(Date datetime) {
this.datetime = datetime;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
public void update(String title2, String contents2) {
this.title=title2;
this.contents=contents2;
}
public boolean isSameWriter(User sessionedUser) {
return this.writer.equals(sessionedUser);
}
}
class User
package net.slipp.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import com.fasterxml.jackson.annotation.JsonProperty;
@Entity
public class User implements Serializable{
@Id
@GeneratedValue
private Long id;
//널 방지
@Column(nullable=false, length=20)
@JsonProperty
private String userId;
@JsonProperty
private String name;
@JsonProperty
private String email;
@JsonProperty
private String password;
public User() {
}
public User(String userId, String name, String email, String password) {
super();
this.userId = userId;
this.name = name;
this.email = email;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean matchPassword(String newPassword){
if(newPassword==null){
return false;
}
return this.password.equals(newPassword);
}
public boolean matchId(Long newId){
if(newId==null){
return false;
}
return this.id.equals(newId);
}
@Override
public String toString() {
return "User [id=" + id + ", userId=" + userId + ", name=" + name + ", email=" + email + ", password="
+ password + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
댓글 ( 4)
댓글 남기기