지난번 게시글 리스트 출력을 했으니 (Select)
실제로 내용이 들어갈 게시글 CRUD 를 작성해본다.
글쓰기부터
1. controller 생성
만들어둔 PostController 에 우선 Create (Write) 를 만들어본다.
@GetMapping("/Write") public ModelAndView writePost(HttpServletRequest request){ mav.setViewName("Write"); return mav; } @PostMapping("/Write") public ModelAndView writePost(@ModelAttribute Post post, HttpServletResponse response){ System.out.println("test"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); postService.inserPost(post); mav.setViewName("redirect:/"); return mav; }
글쓰기 페이지를 만들것이고 같은 url 로 get이냐 post냐에 따라 달리 작동시키기 위해 메서드를 두개만들어두었다.
Write 로 get 요청을 보내면 첫번째 메서드인 Write.jsp 로 리턴해주는것이 먼저 호출된다.
두번째 Write 메서드는 글쓰기를 위한 클래스
또한 service 를 호출하기 위한 autowired 가 선행되어야 한다.
가장 상단에 autowired 어노테이션을 통한 주입부터 해준다.
public class PostContoller { @Autowired PostService postService; @Autowired PostListService postListService; ModelAndView mav = new ModelAndView(); private static String UPLOAD_FOLDER = "D:/logs/";
2. Service 만들기
지난번 만든 Service class 에 writeService 도 하나 만들어준다.
나는 PostService.java 라는 이름으로 만들었음.
public void inserPost(Post post) { postDao.insertPost(post); }
추가로 Autowired 도 해둔다. (위 postDao 호출을 위해)
@Autowired PostDao postDao;
3. dao 만들기
서비스와 마찬가지로 dao 도만든다.
PostDao.java 로 만들어두었음.
public void insertPost(Post post) { sqlSession.insert("PostMapper.insertPost", post); }
Repository 어노테이션을 써주고
mapper-post.xml 의 namespace PostMapper 와 연동할수있게끔 써준다.
sqlSession. 까지만치고 자동완성으로 보면 select 이외에도 update, delete 등 여러 메서드들 확인할 수 있으니 참고
4. mapper-post.xml 에서 SQL Query 작성
<insert id="insertPost" parameterType="com.example.post.model.Post" useGeneratedKeys="true" keyProperty="num"> INSERT INTO TEST1 (Author, Contents, Title) VALUES (#{author}, #{contents}, #{title}) </insert>
5. write.jsp 페이지 작성
뒷단에서 할 작업을 끝냈으니 jsp 페이지를 만들어 form 형태로 데이터를 보내 글을 저장할 수 있게끔 해본다.
write.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>${post.title}</title> </head> <body> <form action="${pageContext.request.contextPath}/Write" method="POST" accept-charset="utf-8" enctype="multipart/form-data"> <label for="title">제목:</label> <input type="text" id="title" name="title" required><br><br> <label for="author">작성자:</label> <input type="text" id="author" name="author" required><br><br> <label for="contents">내용:</label><br> <textarea id="contents" name="contents" required></textarea><br><br> <input type="submit" value="글쓰기"> </body> </html>
pageContext.request.contextPath 는 내 contextPath 를 알아서 넣어준다. (나는 / 라서 따로 필요없긴함)
form 형태로 만들어 submit 을 통해 action url 으로 날리게 된다.
enctype 은 없어도되는데, 이후 file 업로드를 위해 미리 설정해두었다.