티스토리 뷰
수정할 점!!!!
lesson.jsp에서 보는 별점에 대한 고민...
따로 작성해서 보기 같은 페이지에 표기하기 힘듬...알아보자!
Domain
LessonReview.java
package com.springmvc.domain;
import java.io.Serializable;
import org.springframework.web.multipart.MultipartFile;
public class LessonReview implements Serializable{
/**
*
*/
private static final long serialVersionUID = 546339524298037657L;
private String reviewId;
private String lessonId;
private String userId; //사용자아이디
private String date;
private String content;
private int score;
private String fileName;
private MultipartFile reviewImage;
public LessonReview() {
super();
// TODO Auto-generated constructor stub
}
public String getReviewId() {
return reviewId;
}
public void setReviewId(String reviewId) {
this.reviewId = reviewId;
}
public String getLessonId() {
return lessonId;
}
public void setLessonId(String lessonId) {
this.lessonId = lessonId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public MultipartFile getReviewImage() {
return reviewImage;
}
public void setReviewImage(MultipartFile reviewImage) {
this.reviewImage = reviewImage;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
Controller
LessonReviewController.java
package com.springmvc.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.springmvc.domain.LessonReview;
import com.springmvc.service.LessonReviewService;
@Controller
@RequestMapping("/lesson/review")
public class LessonReviewController {
@Autowired
private LessonReviewService lessonReviewService;
@GetMapping()
public String requestReviewList(@RequestParam("id")String lessonId, Model model) {
List<LessonReview> list = lessonReviewService.readAllReviewList(lessonId);
double avgScore = lessonReviewService.calculateAvgScore(lessonId);
model.addAttribute("reviewList",list);
model.addAttribute("avgScore",avgScore);
return "/Lesson/reviews";
}
@GetMapping("/all")
public String requestAllReview(@RequestParam("id")String reviewId, @RequestParam("lessonId")String lessonId, Model model) {
List<LessonReview> list = lessonReviewService.readAllReviewList(lessonId);
model.addAttribute("reviewList",list);
return "/Lesson/reviews";
}
@GetMapping("/detaile")
public String requestReviewById(@RequestParam("id")String reviewId,Model model) {
LessonReview reviewById = lessonReviewService.readReviewById(reviewId);
model.addAttribute("review",reviewById);
return "/Lesson/review";
}
//create
@GetMapping("/add")
public String requestAddReviewForm(@ModelAttribute("addReview")LessonReview lessonreview) {
return "/Lesson/radd";
}
@PostMapping("/add")
public String submitAddNewReview(@ModelAttribute("addReview")LessonReview lessonReview, HttpServletRequest request) {
MultipartFile img = lessonReview.getReviewImage();
String saveName = img.getOriginalFilename();
String save = request.getSession().getServletContext().getRealPath("/response/images");
File saveFile = new File(save,saveName);
if(img!=null&&!img.isEmpty())
{
try
{
img.transferTo(saveFile);
lessonReview.setFileName(saveName);
}
catch (Exception e)
{
throw new RuntimeException("리뷰 사진 업로드가 실패했습니다.");
}
}
lessonReviewService.setNewReview(lessonReview);
return "redirect:/lesson/review";
}
//update
@GetMapping("/update")
public String getUpdateReviewForm(@ModelAttribute("updateReview")LessonReview lessonReview, @RequestParam("id")String reviewId, Model model) {
LessonReview reviewById = lessonReviewService.readReviewById(reviewId);
model.addAttribute("review",reviewById);
return "/Lesson/rupdateForm";
}
@PostMapping("/update")
public String submitUpdateReviewForm(@ModelAttribute("updateReview")LessonReview lessonReview, HttpServletRequest request) {
MultipartFile img = lessonReview.getReviewImage();
String saveName = img.getOriginalFilename();
String save = request.getSession().getServletContext().getRealPath("/response/images");
File saveFile = new File(save,saveName);
if(img!=null&&!img.isEmpty())
{
try
{
img.transferTo(saveFile);
lessonReview.setFileName(saveName);
}
catch (Exception e)
{
throw new RuntimeException("리뷰 사진 업로드가 실패했습니다.");
}
}
lessonReviewService.setUpdateReview(lessonReview);
return "redirect:/lesson/review";
}
@GetMapping(value="/delete")
public String getDeleteForm(Model model, @RequestParam("id")String reviewId) {
lessonReviewService.setDeleteReview(reviewId);
return "redirect:/lesson/review";
}
// @GetMapping("/avg")
// public String getAvgScore(Model model){
// double avgScore = lessonReviewService.calculateAvgScore();
// model.addAttribute("avgScore",avgScore);
// return "/Lesson/reviews";
// }
}
Repository
LessonReviewRepository.java (interface)
package com.springmvc.repository;
import java.util.List;
import com.springmvc.domain.LessonReview;
public interface LessonReviewRepository {
List<LessonReview> readAllReviewList(String lessonId);
LessonReview readReviewById(String reviewId);
double calculateAvgScore(String lessonId);
void setNewReview(LessonReview lessonReview);
void setUpdateReview(LessonReview lessonReview);
void setDeleteReview(String reviewId);
}
LessonReviewRepositoryImpl.java
package com.springmvc.repository;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.springmvc.domain.LessonReview;
@Repository
public class LessonReviewRepositoryImpl implements LessonReviewRepository{
private JdbcTemplate template;
@Autowired
public void setJdbcTemplate(DataSource dataSource) {
this.template = new JdbcTemplate(dataSource);
}
@Override
public List<LessonReview> readAllReviewList(String lessonId) {
String SQL = "SELECT * FROM l_review WHERE lessonid=?";
List<LessonReview> listOfReviews = template.query(SQL, new Object[] {lessonId}, new LessonReviewRowMapper());
return listOfReviews;
}
@Override
public LessonReview readReviewById(String reviewId) {
LessonReview reviewInfo = null;
String SQL = "SELECT COUNT(*) FROM l_review WHERE lr_id=?";
int rowCount = template.queryForObject(SQL,Integer.class, reviewId);
if(rowCount!=0) {
SQL="SELECT * FROM l_review WHERE lr_id=?";
reviewInfo = template.queryForObject(SQL,new Object[] {reviewId}, new LessonReviewRowMapper());
}
if(reviewInfo==null) {
throw new IllegalArgumentException("일치하는 리뷰를 찾을 수 없습니다.");
}
return reviewInfo;
}
@Override
public void setNewReview(LessonReview lessonReview) {
String SQL = "INSERT INTO l_review (lr_id, lessonid, lr_userId, lr_date, lr_content, lr_score, lr_filename)"+"VALUES(?, ?, ?, ?, ?, ?, ?)";
template.update(SQL,lessonReview.getReviewId(), lessonReview.getLessonId(), lessonReview.getUserId(), lessonReview.getDate(), lessonReview.getContent(), lessonReview.getScore(), lessonReview.getFileName());
}
@Override
public void setUpdateReview(LessonReview lessonReview) {
if(lessonReview.getFileName()!=null) {
String SQL = "UPDATE l_review SET lessonid=?, lr_userId=?, lr_date=?, lr_content=?, lr_score=?, lr_filename=? WHERE lr_id=?";
template.update(SQL, lessonReview.getLessonId(), lessonReview.getUserId(), lessonReview.getDate(), lessonReview.getContent(), lessonReview.getScore(), lessonReview.getFileName(), lessonReview.getReviewId());
}
else if(lessonReview.getFileName()==null) {
String SQL = "UPDATE l_review SET lessonid=?, lr_userId=?, lr_date=?, lr_content=?, lr_score=? WHERE lr_id=?";
template.update(SQL,lessonReview.getLessonId(), lessonReview.getUserId(), lessonReview.getDate(), lessonReview.getContent(), lessonReview.getScore(), lessonReview.getReviewId());
}
}
@Override
public void setDeleteReview(String reviewId) {
String SQL = "DELETE FROM l_review WHERE lr_id=?";
template.update(SQL,reviewId);
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
@Override
public double calculateAvgScore(String lessonId) {
String SQL = "SELECT ROUND(AVG(lr_score),1) FROM l_review WHERE lessonId=?";
Double avgScore = template.queryForObject(SQL, new Object[] { lessonId }, Double.class);
return avgScore != null ? avgScore : 0.0;
}
}
LessonReviewRowMapper.java
package com.springmvc.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.springmvc.domain.LessonReview;
public class LessonReviewRowMapper implements RowMapper<LessonReview>{
@Override
public LessonReview mapRow(ResultSet rs, int rowNum) throws SQLException {
LessonReview lessonReview = new LessonReview();
lessonReview.setReviewId(rs.getString(1));
lessonReview.setLessonId(rs.getString(2));
lessonReview.setUserId(rs.getString(3));
lessonReview.setDate(rs.getString(4));
lessonReview.setContent(rs.getString(5));
lessonReview.setScore(rs.getInt(6));
lessonReview.setFileName(rs.getString(7));
return lessonReview;
}
}
SQL
drop table l_review;
create table if not exists l_review(
lr_id char(30) NOT NULL primary key,
lessonid char(30) NOT NULL, -- 강의아이디
lr_userId varchar(20) NOT NULL, -- 사용자아이디
lr_date date NOT NULL, -- 작성날짜
lr_content varchar(100) NOT NULL, -- 내용
lr_score tinyint, -- 점수
lr_filename varchar(30) -- 이미지파일이름
)default charset=utf8;
Service
LessonReviewService.java
package com.springmvc.service;
import java.util.List;
import com.springmvc.domain.LessonReview;
public interface LessonReviewService {
List<LessonReview> readAllReviewList();
LessonReview readReviewById(String reviewId);
double calculateAvgScore();
void setNewReview(LessonReview lessonReview);
void setUpdateReview(LessonReview lessonReview);
void setDeleteReview(String reviewId);
}
LessonReviewServiceImpl.java
package com.springmvc.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springmvc.domain.LessonReview;
import com.springmvc.repository.LessonReviewRepository;
@Service
public class LessonReviewServiceImpl implements LessonReviewService{
@Autowired
private LessonReviewRepository lessonReviewRepository;
@Override
public List<LessonReview> readAllReviewList() {
// TODO Auto-generated method stub
return lessonReviewRepository.readAllReviewList();
}
@Override
public LessonReview readReviewById(String reviewId) {
LessonReview reviewById = lessonReviewRepository.readReviewById(reviewId);
return reviewById;
}
@Override
public void setNewReview(LessonReview lessonReview) {
lessonReviewRepository.setNewReview(lessonReview);
}
@Override
public void setUpdateReview(LessonReview lessonReview) {
lessonReviewRepository.setUpdateReview(lessonReview);
}
@Override
public void setDeleteReview(String reviewId) {
lessonReviewRepository.setDeleteReview(reviewId);
}
@Override
public double calculateAvgScore() {
// TODO Auto-generated method stub
return lessonReviewRepository.calculateAvgScore();
}
}
뷰페이지
강의 리뷰 등록
radd.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="<c:url value="/resources/css/bootstrap.min.css"/>"rel="stylesheet" />
<title>리뷰 등록</title>
</head>
<body>
<nav class="navbar navbar-expand navbar-dark bg-dark">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="./home">Home</a>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">리뷰 등록</h1>
</div>
</div>
<div class="container">
<form:form modelAttribute="addReview" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group row">
<label class="col-sm-2 control-label">리뷰ID</label>
<div class="col-sm-3">
<form:input path="reviewId" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">강의아이디</label>
<div class="col-sm-3">
<form:input path="lessonId" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">사용자아이디</label>
<div class="col-sm-3">
<form:input path="userId" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">리뷰작성날짜</label>
<div class="col-sm-3">
<form:input type="date" path="date" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">리뷰점수</label>
<div class="col-sm-3">
<form:input path="score" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">리뷰내용</label>
<div class="col-sm-5">
<form:textarea path="content" cols="50" rows="2" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">리뷰사진</label>
<div class="col-sm-7">
<form:input path="reviewImage" type="file" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="등록하기" />
<input type="reset" class="btn btn-primary" value="다시쓰기" />
</div>
</div>
</fieldset>
</form:form>
<hr>
<footer>
<p>© review</p>
</footer>
</div>
</body>
</html>
해당 강의 리뷰 목록 보기
reviews.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!-- form 사용을 위한 선언 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="<c:url value="/resources/css/bootstrap.min.css"/>"rel="stylesheet" />
<script src="${pageContext.request.contextPath }/resources/js/controllers.js"></script>
<!-- 스크립트 사용을 위해 선언 -->
<title>리뷰 목록</title>
</head>
<body>
<h2>리뷰 목록</h2>
<div>
<p> 평균점수 : ${avgScore}</p>
</div>
<c:forEach var="review" items="${reviewList}">
<div>
<c:choose>
<c:when test="${review.getReviewImage() == null}">
<img src="<c:url value='/resources/images/${review.fileName}'/>" style="width: 20%"/>
</c:when>
<c:otherwise>
<img src="<c:url value='/resources/images/${review.fileName}'/>" style="width: 20%"/>
</c:otherwise>
</c:choose>
</div>
<div>
<p>리뷰 ID: ${review.reviewId}</p>
<p>강의 ID: ${review.lessonId}</p>
<p>사용자 ID : ${review.userId}</p>
<p>작성날짜 : ${review.date}</p>
<p>리뷰점수 : ${review.score}</p>
<p><a href="<c:url value="/lesson/review/detaile?id=${review.reviewId}"/>"class="btn btn-secondary" role="button">상세정보 »</a>
</div>
<hr>
</c:forEach>
</body>
</html>
이전 코드에서는 전체 리뷰를 보도록 작성되었지만 변경 후에는 위와 같이 해당 강의의 리뷰만 조회하도록 했다.
리뷰 상세보기
review.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!-- form 사용을 위한 선언 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="<c:url value="/resources/css/bootstrap.min.css"/>"rel="stylesheet" />
<script src="${pageContext.request.contextPath }/resources/js/controllers.js"></script>
<!-- 스크립트 사용을 위해 선언 -->
<title>리뷰</title>
</head>
<body>
<h2>리뷰</h2>
<div class="col-md-4">
<c:choose>
<c:when test="${review.getReviewImage() == null}">
<img src="<c:url value='/resources/images/${review.fileName}'/>" style="width: 20%"/>
</c:when>
<c:otherwise>
<img src="<c:url value='/resources/images/${review.fileName}'/>" style="width: 20%"/>
</c:otherwise>
</c:choose>
</div>
<div>
<p>리뷰 ID: ${review.reviewId}</p>
<p>병원 ID: ${review.lessonId}</p>
<p>사용자 ID : ${review.userId}</p>
<p>작성날짜 : ${review.date}</p>
<p>리뷰점수 : ${review.score}</p>
<p>리뷰내용 : ${review.content}</p>
<form:form name="addForm" method="put">
<a href='<c:url value="/lesson/review/update?id=${review.reviewId}"/>' class="btn btn-success">수정»</a>
<a href="<c:url value='/lesson/review/delete?id=${review.reviewId}'/>" class="btn btn-danger" onclick="return deleteConfirm('${review.lessonId}')">삭제 »</a>
<a href="<c:url value='/lesson/review/review?id=${review.reviewId}'/>" class="btn btn-success">리뷰»</a>
</form:form>
</div>
<hr>
</body>
</html>
리뷰 수정
rupdateForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div class="container">
<h3>리뷰 수정 페이지</h3>
<div class="col-md-4">
<img src="<c:url value='/resources/images/${review.fileName}'/>" alt="image" style="width: 50%"/>
</div>
<form:form modelAttribute="updateReview" action="./update?id=${review.reviewId}" class="form-horizontal" enctype="multipart/form-data">
<p> 리뷰 아이디 : <form:input path="reviewId" value="${review.reviewId}"/> <!-- path 는 DTO 객체의 변수 -->
<p> 강의 아이디 : <form:input path="lessonId" value="${review.lessonId}"/>
<p> 사용자 아이디 : <form:input path="userId" value="${review.userId}"/>
<p> 리뷰작성날짜 : <form:input type="date" path="date" value="${review.date}"/>
<p> 리뷰내용 : <form:input path="content" value="${review.content}"/>
<p> 리뷰점수 : <form:input path="score" value="${review.score}"/>
<div class="col-sm-10">
이미지<form:input path="reviewImage" type="file" class="form-control"/>
</div>
<div class="form-group row">
<input type="submit" class="btn btn-primary" value="수정"/>
<a href="<c:url value="/Lesson/reviews"/>" class="btn btn-primary">취소</a>
</div>
</form:form>
</div>
</body>
</html>
리뷰 삭제
삭제 클릭하면 delete 실행 후 redirect 되어 리뷰 목록을 보는 reviews로 이동한다.
'코딩 > spring' 카테고리의 다른 글
[20주 3일차] 하나의 컨트롤러에서 여러 Service 클래스 참조하기 (0) | 2024.02.21 |
---|---|
queryForObject() 메서드와 query() 메서드 (RowMapper) (0) | 2024.02.20 |
[20주 1일차] 프로젝트 - 경기관리 (1) | 2024.02.19 |
[19주 5일차] 프로젝트 - 병원관리(CRUD) (0) | 2024.02.16 |
[19주 3일차] 메서드의 파라미터를 바인딩하기 위한 주요 애노테이션 (0) | 2024.02.14 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday