본문 바로가기
웹개발/스프링

스프링 개발전 Controller Class파일 작성하기 - part2

by 인생여희 2020. 11. 14.

1.VO 클래스 작성

package sample.customer.biz.domain;

import java.util.Date;

import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

import org.springframework.format.annotation.DateTimeFormat;

@XmlRootElement
public class Customer implements java.io.Serializable {

    private int id;

    
    //검증처리
    @NotNull
    @Size(max = 20)
    private String name;

    @NotNull
    @Pattern(regexp = ".+@.+")
    private String emailAddress;

    @NotNull
    @DateTimeFormat(pattern = "yyyy/MM/dd")
    private Date birthday;

    @Max(9)
    @Min(0)
    private Integer favoriteNumber;

    @AssertFalse(message = "{errors.emailAddress.ng}")
    public boolean isNgEmail() {
        if (emailAddress == null) {
            return false;
        }
        return emailAddress.matches(".*@ng.foo.baz$");
    }

    public Customer() {}

    public Customer(String name, String emailAddress,
                        Date birthday, Integer favoriteNumber) {
        this.name = name;
        this.emailAddress = emailAddress;
        this.birthday = birthday;
        this.favoriteNumber = favoriteNumber;
    }

   //setter getter 생략...
   
    @Override
    public String toString() {
        return String.format(
                "Customer [id=%s, name=%s, emailAddress=%s, birthday=%s, favoriteNumber=%s]",
                id, name, emailAddress, birthday, favoriteNumber);
    }

    private static final long serialVersionUID = 5498108629060769963L;
}

 

2.Service 작성

package sample.customer.biz.service;

import sample.customer.biz.domain.Customer;

import java.util.List;

public interface CustomerService {
    public List<Customer> findAll();
    
    public Customer findById(int id) throws DataNotFoundException;
    
    public Customer register(Customer customer);
    
    public void update(Customer customer) throws DataNotFoundException;
    
    public void delete(int id) throws DataNotFoundException;
}

 

3.ServiceImple 작성

package sample.customer.biz.service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import sample.customer.biz.domain.Customer;

@Service
public class MockCustomerService implements CustomerService {
    private Map<Integer, Customer> customerMap = new LinkedHashMap<Integer, Customer>();

    private int nextId = 1;

    private boolean isExists(int id) {
        return customerMap.containsKey(id);
    }

    public List<Customer> findAll() {
        List<Customer> list = new LinkedList<Customer>();
        for (Customer customer : customerMap.values()) {
            list.add(newCustomer(customer));
        }
        return list;
    }

    public Customer findById(int id) throws DataNotFoundException {
        if (!isExists(id)) {
            throw new DataNotFoundException();
        }
        return newCustomer(customerMap.get(id));
    }

    public Customer register(Customer customer) {
        customer.setId(nextId++);
        customerMap.put(customer.getId(), newCustomer(customer));

        return customer;
    }

    public void update(Customer customer) throws DataNotFoundException {
        if (!isExists(customer.getId())) {
            throw new DataNotFoundException();
        }
        customerMap.put(customer.getId(), newCustomer(customer));
    }

    public void delete(int id) throws DataNotFoundException {
        if (!isExists(id)) {
            throw new DataNotFoundException();
        }
        customerMap.remove(id);
    }

    @PostConstruct
    public void initCustomer() {
        nextId = 1;

        register(new Customer("길동", "taro@aa.bb.cc", date("19750111"), 1));
        register(new Customer("명보", "jiro@aa.bb.cc", date("19760212"), 2));
        register(new Customer("삼둥", "sabu@aa.bb.cc", date("19770313"), 3));
    }

    private static Date date(String dateString) {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
            return df.parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException("yyyyMMdd format faild", e);
        }
    }

    private Customer newCustomer(Customer orig) {
        Customer dest = new Customer();
        try {
            BeanUtils.copyProperties(dest, orig);
        } catch (Exception e) {
            throw new RuntimeException("Exception threw in Customer copy ", e);
        }
        return dest;
    }
}

 

4.CustomerListController.java

package sample.customer.web.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import sample.customer.biz.domain.Customer;
import sample.customer.biz.service.CustomerService;
import sample.customer.biz.service.DataNotFoundException;

@Controller
public class CustomerListController {

    @Autowired
    private CustomerService customerService;

    @RequestMapping(value = "/", method = GET)
    public String home() {
        return "forward:/customer";
    }

    @RequestMapping(value = "/customer", method = GET)
    public String showAllCustomers(Model model) {
        List<Customer> customers = customerService.findAll();
        model.addAttribute("customers", customers);
        return "customer/list";
    }

    @RequestMapping(value = "/customer/{customerId}", method = GET)
    public String showCustomerDetail(@PathVariable int customerId, Model model)
                                        throws DataNotFoundException{
        Customer customer = customerService.findById(customerId);
        model.addAttribute("customer", customer);
        return "customer/detail";
    }

    @ExceptionHandler(DataNotFoundException.class)
    public String handleException() {
        return "customer/notfound";
    }

//    @ExceptionHandler
//    public String handleException(Exception e) {
//        return "error/system";
//    }
}

 

5.CustomerEditController.java

package sample.customer.web.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import sample.customer.biz.domain.Customer;
import sample.customer.biz.service.CustomerService;
import sample.customer.biz.service.DataNotFoundException;

@Controller
@RequestMapping("/customer/{customerId}")
@SessionAttributes(value = "editCustomer")
public class CustomerEditController {

    @Autowired
    private CustomerService customerService;

    @RequestMapping(value = "/edit", method = GET)
    public String redirectToEntryForm(
            @PathVariable int customerId, Model model)
                                throws DataNotFoundException {
        Customer customer = customerService.findById(customerId);
        model.addAttribute("editCustomer", customer);

        return "redirect:enter";
    }

    @RequestMapping(value = "/enter", method = GET)
    public String showEntryForm() {
        return "customer/edit/enter";
    }

    @RequestMapping(
        value = "/enter", params = "_event_proceed", method = POST)
    public String verify(
            @Valid @ModelAttribute("editCustomer") Customer customer,
            Errors errors) {
        if (errors.hasErrors()) {
            return "customer/edit/enter";
        }
        return "redirect:review";
    }

    @RequestMapping(value = "/review", method = GET)
    public String showReview() {
        return "customer/edit/review";
    }

    @RequestMapping(value = "/review", params = "_event_revise", method = POST)
    public String revise() {
        return "redirect:enter";
    }

    @RequestMapping(
        value = "/review", params = "_event_confirmed", method = POST)
    public String edit(
            @ModelAttribute("editCustomer") Customer customer)
                                    throws DataNotFoundException {
        customerService.update(customer);

        return "redirect:edited";
    }

    @RequestMapping(value = "/edited", method = GET)
    public String showEdited(
            SessionStatus sessionStatus) {
        sessionStatus.setComplete();

        return "customer/edit/edited";
    }
}

 

6.CustomerRestController.java

package sample.customer.web.controller;

import static org.springframework.web.bind.annotation.RequestMethod.*;

import java.nio.charset.Charset;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import sample.customer.biz.domain.Customer;
import sample.customer.biz.service.CustomerService;
import sample.customer.biz.service.DataNotFoundException;

@RestController
@RequestMapping("/api/customer")
public class CustomerRestController {

    @Autowired
    private CustomerService customerService;

    @RequestMapping(method = POST)
    @ResponseStatus(HttpStatus.OK)
    public String register(@RequestBody Customer customer) {
        customerService.register(customer);
        return "OK";
    }

    @RequestMapping(value = "/{customerId}", method = GET)
    public ResponseEntity<Customer> findById(@PathVariable int customerId)
                                        throws DataNotFoundException {
        Customer customer = customerService.findById(customerId);

        return ResponseEntity.ok()
                .header("My-Header", "MyHeaderValue")
                .contentType(new MediaType("text", "xml", Charset.forName("UTF-8")))
                .body(customer);
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleException(DataNotFoundException e) {
        return "customer is not found";
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleException(Exception e) {
        return "server error";
    }
}

 


JSP 화면

 

1.입력화면

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>입력화면</title>
</head>
<body>
<h1>입력화면</h1>
<form:form modelAttribute="editCustomer">
<dl>
  <dt>이름</dt>
  <dd>
    <form:input path="name"/>
    <form:errors path="name"/>
  </dd>
  <dt>주소</dt>
  <dd>
    <form:input path="emailAddress"/>
    <form:errors path="emailAddress"/>
    <form:errors path="ngEmail"/>
  </dd>
  <dt>생일</dt>
  <dd>
    <form:input path="birthday"/>
    <form:errors path="birthday"/>
  </dd>
  <dt>좋아하는 숫자</dt>
  <dd>
    <form:input path="favoriteNumber"/>
    <form:errors path="favoriteNumber"/>
  </dd>
</dl>
<button type="submit" name="_event_proceed" value="proceed">
  제출
</button>
</form:form>
</body>
</html>

 

2.수정화면

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>수정</title>
</head>
<body>
<h1>수정</h1>
<dl>
  <dt>이름</dt>
  <dd><c:out value="${editCustomer.name}"/></dd>
  <dt>주소</dt>
  <dd><c:out value="${editCustomer.emailAddress}"/></dd>
  <dt>생</dt>
  <dd><fmt:formatDate pattern="yyyy/MM/dd" value="${editCustomer.birthday}"/></dd>
  <dt>좋아하는 숫자</dt>
  <dd><c:out value="${editCustomer.favoriteNumber}"/></dd>
</dl>
<c:url var="url" value="/customer"/>
<a href="${url}">완료</a>
</body>
</html>

 

3.리뷰화면

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h1></h1>
<form method="post">
<dl>
  <dt>이름</dt>
  <dd><c:out value="${editCustomer.name}"/></dd>
  <dt></dt>
  <dd><c:out value="${editCustomer.emailAddress}"/></dd>
  <dt>생일</dt>
  <dd><fmt:formatDate pattern="yyyy/MM/dd" value="${editCustomer.birthday}"/></dd>
  <dt>좋아하는 숫자</dt>
  <dd><c:out value="${editCustomer.favoriteNumber}"/></dd>
</dl>
<button type="submit" name="_event_confirmed">수정</button>
<button type="submit" name="_event_revise">재입력</button>
</form>
</body>
</html>

 

4.상세보기화면

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h1></h1>
<dl>
  <dt>이름</dt>
  <dd><c:out value="${customer.name}"/></dd>
  <dt>주소</dt>
  <dd><c:out value="${customer.emailAddress}"/></dd>
  <dt>생일</dt>
  <dd><fmt:formatDate pattern="yyyy/MM/dd" value="${customer.birthday}"/></dd>
  <dt>좋아하는 숫자</dt>
  <dd><c:out value="${customer.favoriteNumber}"/></dd>
</dl>
<c:url value="/customer" var="url"/>
<a href="${url}">입력</a>
</body>
</html>

 

5.리스트화면

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>화면</title>
</head>
<body>
<h1></h1>
<c:if test="${editedCustomer != null}">

<dl>
  <dt>이름</dt>
  <dd><c:out value="${editedCustomer.name}"/></dd>
  <dt>주소</dt>
  <dd><c:out value="${editedCustomer.emailAddress}"/></dd>
  <dt>생일</dt>
  <dd><fmt:formatDate pattern="yyyy/MM/dd" value="${editedCustomer.birthday}"/></dd>
  <dt>숫자</dt>
  <dd><c:out value="${editedCustomer.favoriteNumber}"/></dd>
</dl>
</c:if>
<table border="1">
  <tr>
    <th>ID</th>
    <th>이름</th>
    <th>주소</th>
    <th></th>
  </tr>
  <c:forEach items="${customers}" var="customer">
  <tr>
    <td><c:out value="${customer.id}"/></td>
    <td><c:out value="${customer.name}"/></td>
    <td><c:out value="${customer.emailAddress}"/></td>
    <td>
      <c:url value="/customer/${customer.id}" var="url"/>
      <a href="${url}">-</a>
      <c:url value="/customer/${customer.id}/edit" var="url"/>
      <a href="${url}">--</a>
    </td>
  </tr>
  </c:forEach>
</table>
</body>
</html>

 

6.예외화면

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ㅜ</title>
</head>
<body>
<h1>ㅜ</h1>
<c:url value="/customer" var="url"/>
<a href="${url}"></a>
</body>
</html>

 

7.오류화면

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>예외발생</title>
</head>
<body>
<dl>
  <dt>예외명</dt>
  <dd>${exception.getClass().name}</dd>
  <dt>알림</dt>
  <dd>${exception.message}</dd>
</dl>

</body>
</html>

 

 

예제파일

mvc.zip
0.08MB