7일차

|
// 스프링 MVC - HTTP 세션 사용하기 - 플젝활용할것 ★★★
(jsp에서 hidden 쓸 필요 없음)

--------------------------------------------------------------------------
TEST URL: newevent/step1.do

1. com.spring.mvc.ex04.EventCreationController.java

@Controller
@SessionAttributes("eventForm") // 클래스에 SessionAttributes를 적용하고 세션으로 공유할 객체의 모델이름을 지정한다.
public class EventCreationController {

 private static final String EVENT_CREATION_STEP1 = "event/creationStep1";
 private static final String EVENT_CREATION_STEP2 = "event/creationStep2";
 private static final String EVENT_CREATION_STEP3 = "event/creationStep3";
 private static final String EVENT_CREATION_DONE = "event/creationDone";

 @RequestMapping("/newevent/step1") // 메소드 호출 될때
 public String step1(Model model) {
  model.addAttribute("eventForm", new EventForm()); //eventForm이 model에 추가됨.
  return EVENT_CREATION_STEP1; // 세션에 담는다.
 }
  
 @RequestMapping(value = "/newevent/step2", method = RequestMethod.POST)
 public String step2(@ModelAttribute("eventForm") EventForm formData, BindingResult result) { // step1의 eventForm을 담는다.
  new EventFormStep1Validator().validate(formData, result);
  if (result.hasErrors())
   return EVENT_CREATION_STEP1;
  return EVENT_CREATION_STEP2;
 }

 @RequestMapping(value = "/newevent/step2", method = RequestMethod.GET)
 public String step2FromStep3(@ModelAttribute("eventForm") EventForm formData) {
  return EVENT_CREATION_STEP2;
 }

 @RequestMapping(value = "/newevent/step3", method = RequestMethod.POST)
 public String step3(@ModelAttribute("eventForm") EventForm formData, BindingResult result) {
  ValidationUtils.rejectIfEmpty(result, "target", "required");
  if (result.hasErrors())
   return EVENT_CREATION_STEP2;
  return EVENT_CREATION_STEP3;
 }

 @RequestMapping(value = "/newevent/done", method = RequestMethod.POST)
 public String done(@ModelAttribute("eventForm") EventForm formData, SessionStatus sessionStatus) {
  sessionStatus.setComplete();
  return EVENT_CREATION_DONE; // 최종 데이터가 담김.
 }
}

---------------------------------------------------------------------
2. views/event/creationStep1.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="com.spring.mvc.ex04.component.EventType" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>이벤트 생성: ${project}</title>
</head>
<body>

<form:form commandName="eventForm" action="/springMvcSample/newevent/step2.do">

<label for="name">이벤트 명</label>: 
<input type="text" name="name" id="name" value="${eventForm.name}"/> 
<form:errors path="name"/><br/>

<label for="type">타입</label>:
<select name="type" id="type">
 <option value="">선택하세요</option>
 <c:forEach var="type" items="<%= EventType.values() %>">
 <option value="${type}" ${eventForm.type == type ? 'selected' : ''}>${type}</option>
 </c:forEach>
</select> 
<form:errors path="type"/><br/>

<label>이벤트 기간</label>: 
<input type="text" name="beginDate" value='<fmt:formatDate value="${eventForm.beginDate}" pattern="yyyyMMdd"/>'/>부터 
<input type="text" name="endDate" value='<fmt:formatDate value="${eventForm.endDate}" pattern="yyyyMMdd"/>'/>까지
<form:errors path="beginDate"/><br/>
<form:errors path="endDate"/><br/>

<input type="submit" value="다음 단계로" />
</form:form>

세션 존재 여부: <%= session.getAttribute("eventForm") != null ? "존재" : "없음" %>
</body>
</html>

---------------------------------------------------------------------
3. views/event/creationStep2.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="com.spring.mvc.ex04.component.EventType" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>이벤트 생성</title>
</head>
<body>

<form:form commandName="eventForm" action="/springMvcSample/newevent/step3.do">

<label>적용 회원 등급</label>: 
<label><input type="radio" name="target" value="all" ${eventForm.target == 'all' ? 'checked' : '' }/>모든 회원</label>
<label><input type="radio" name="target" value="premium" ${eventForm.target == 'premium' ? 'checked' : '' } />프리미엄 회원</label>
<form:errors path="target"/><br/>
<br/>
<a href="/springMvcSample/newevent/step1.do">[이전 단계로]</a>
<input type="submit" value="다음 단계로" />
</form:form>

세션 존재 여부: <%= session.getAttribute("eventForm") != null ? "존재" : "없음" %>

</body>
</html>

step1

step2

step3

done

// 스프링 MVC - Exception 처리

---------------------------------------------------------------------
TEST URL: /cal/divide.do?op1=10&op2=0

* com.spring.mvc.ex05.CalculationController.java

@Controller
public class CalculationController {

 @RequestMapping("/cal/add")
 public String add(
   @RequestParam("op1") int op1,
   @RequestParam("op2") int op2,
   Model model) {
  model.addAttribute("result", op1 + op2);
  return "cal/result";
 }

 @RequestMapping("/cal/divide")
 public String divide(Model model,
   @RequestParam("op1") int op1, @RequestParam("op2") int op2) {
  model.addAttribute("result", op1 / op2);
  return "cal/result";
 }

 @ExceptionHandler(RuntimeException.class) // error유형을 catch해서 처리.
 public String handleException(HttpServletResponse response) {
  response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  return "error/exception";
 }
}

--------------------------------------------------------------------------
* com.spring.mvc.ex05.CommonExceptionHandler ( 공통 exception 처리 handler )

@Controller
@ControllerAdvice("com.spring.mvc.ex05") // error처리 범위 설정.
public class CommonExceptionHandler {

 @ExceptionHandler(RuntimeException.class)
 public String handleException() {
  return "error/commonException";
 }
}

---------------------------------------------------------------------
* views/error/commonException.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page isErrorPage="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>에러!!</title>
</head>
<body>

[공통 에러 화면] 작업 처리 도중 문제가 발생했습니다.
<%= exception %>

</body>
</html>

---------------------------------------------------------------------
* views/error/exception.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page isErrorPage="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>에러 발생</title>
</head>
<body>

작업 처리 도중 문제가 발생했습니다.
<%= exception %>

</body>
</html>

// View 구현 - JSP를 이용한 View 구현
// select 태그를 위한 커스텀 태그


---------------------------------------------------------------------
* TEST URL: auth/login2.do

* com.spring.mvc.ex06.LoginController.java
@Controller("LoginController2")
@RequestMapping("/auth/login2")
public class LoginController {

 private static final String LOGIN_FORM = "auth/loginForm2";
 @Autowired
 private Authenticator authenticator;

 @ModelAttribute("jobCodes")
 public List<Code> jobCodes() {
  return Arrays.asList(
    new Code("1", "운동선수"),
    new Code("2", "프로그래머"),
    new Code("3", "예술가"),
    new Code("4", "작가")
    );
 } 
 
 @ModelAttribute("loginTypes")
 protected List<String> referenceData() {
  List<String> loginTypes = new ArrayList<String>();
  loginTypes.add("일반회원");
  loginTypes.add("기업회원");
  loginTypes.add("헤드헌터회원");
  return loginTypes;
 }

 @RequestMapping(method = RequestMethod.GET)
 public String loginForm(LoginCommand loginCommand) {
  loginCommand.setSecurityLevel(SecurityLevel.HIGH);
  return LOGIN_FORM;
 }

 @RequestMapping(method = RequestMethod.POST)
 public String login(@Valid LoginCommand loginCommand, Errors errors,
   HttpServletRequest request) {
  if (errors.hasErrors()) {
   return LOGIN_FORM;
  }
  try {
   Auth auth = authenticator.authenticate(loginCommand.getEmail(), loginCommand.getPassword());
   HttpSession session = request.getSession();
   session.setAttribute("auth", auth);
   return "redirect:/index.jsp";
  } catch (AuthenticationException ex) {
   errors.reject("invalidIdOrPassword");
   return LOGIN_FORM;
  }
 }

 @InitBinder
 protected void initBinder(WebDataBinder binder) {
  binder.setValidator(new LoginCommandValidator());
 }
}

---------------------------------------------------------------------
* views/auth/loginForm2.jsp
<!DOCTYPE html>
<html>
<head><title><spring:message code="login.form.title"/></title></head>
<body>

<form:form commandName="loginCommand">
<form:hidden path="securityLevel"/>
<form:errors element="div" />
<p>
 <label for="email"><spring:message code="email" /></label>: 
 <input type="text" name="email" id="email" value="${loginCommand.email}">
 <form:errors path="email"/>
</p>
<p>
 <label for="password"><spring:message code="password" /></label>: 
 <input type="password" name="password" id="password">
 <form:errors path="password"/>
</p>
<p>
    <label for="loginType"><spring:message code="login.form.type" /></label>
    <form:select path="loginType" items="${loginTypes}" />
    <form:select path="jobCode" items="${jobCodes}" itemLabel="label" itemValue="code" />
</p>

<input type="submit" value="<spring:message code="login.form.login" />">
</form:form>

<ul>
 <li><spring:message code="login.form.help" /></li>
</ul>
</body>
</html>

// View 구현 - Locale 처리

* TEST URL
changeLanguage.do?lang=en

changeLanguage2.do?lang=en

changeLanguage3.do?lang=en



-----------------------------------------------------------------------------------
* com.spring.mvc.ex07.LocaleChangeController.java
@Controller
public class LocaleChangeController {
 @Autowired(required=false)
 private LocaleResolver localeResolver;

 @RequestMapping("/changeLanguage")
 public String change(@RequestParam("lang") String language,
   HttpServletRequest request, HttpServletResponse response, HttpSession session) {
  Locale locale = new Locale(language);
  localeResolver.setLocale(request, response, locale);
  return "locale/locale";
 }

 public void setLocaleResolver(LocaleResolver localeResolver) {
  this.localeResolver = localeResolver;
 }
}

-----------------------------------------------------------------------------------
* com.spring.mvc.ex07.LocaleChangeController2.java
@Controller
public class LocaleChangeController2 {

 @RequestMapping("/changeLanguage2")
 public String change(@RequestParam("lang") String language,
   HttpServletRequest request, HttpServletResponse response) {
  Locale locale = new Locale(language);
  LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);

  localeResolver.setLocale(request, response, locale);
  return "locale/locale";
 }
}

-----------------------------------------------------------------------------------
* com.spring.mvc.ex07.LocaleChangeController3.java
@Controller
public class LocaleChangeController3 {

 @RequestMapping("/changeLanguage3")
 public String change(HttpServletRequest request, HttpServletResponse response) {
  return "locale/locale2";
 }
}

-----------------------------------------------------------------------------------
* views/locale/locale.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Local Test: <spring:message code="email" />
</body>
</html>

-----------------------------------------------------------------------------------
* views/locale/locale2.jsp
<!DOCTYPE html >
<html>
<head>
<meta charset="UTF-8">
<title><spring:message code="site.title" text="Member Info" /></title>
</head>
<body>
<a href="${pageContext.request.contextPath }/changeLanguage3.do?lang=ko">한국어</a>
<a href="${pageContext.request.contextPath }/changeLanguage3.do?lang=en">ENGLISH</a> 
 <h1><spring:message code="site.title" text="Member Info" /></h1>
 <p><spring:message code="site.name" text="no name" /> : <spring:message code="name" text="no name" /></p>
 <p><spring:message code="site.job" text="no job" />   : <spring:message code="job" text="no job" /></p>


<input type=button value="<spring:message code='btn.send' />" />
<input type=button value="<spring:message code='btn.cancel' />" />
<input type=button value="<spring:message code='btn.finish' />" />

</body>
</html>

 

'Bitcamp > BITCAMP - Spring FW' 카테고리의 다른 글

Maven Project War파일 만들기 ~ 개발서버 배포  (0) 2020.06.29
8일차  (0) 2019.10.17
6일차  (0) 2019.10.11
5일차  (0) 2019.10.10
4일차  (0) 2019.10.08
And