'전체 글'에 해당되는 글 190건

  1. 2019.10.29 ORACLE LIMIT 기능 구현
  2. 2019.10.17 8일차
  3. 2019.10.15 7일차
  4. 2019.10.14 Maven 설치, Jenkins 설치
  5. 2019.10.14 Maven Project War파일 만들기 ~ 개발서버 배포
  6. 2019.10.11 프로젝트에서 꼭 활용할 내용들
  7. 2019.10.11 6일차
  8. 2019.10.10 5일차
  9. 2019.10.08 4일차
  10. 2019.10.07 3일차

ORACLE LIMIT 기능 구현

|

'SQL' 카테고리의 다른 글

ORACLE LIMIT 기능 구현  (0) 2019.10.29
DB 개발환경 구축  (0) 2019.08.31
INNER JOIN  (0) 2019.08.01
OUTER JOIN  (0) 2019.08.01
Trackback 0 And Comment 0

8일차

|
// RestController 사용하기

1. TestController

package com.myspring.pro29.ex01;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController 
@RequestMapping("/test/*")
public class TestController {
  static Logger logger = LoggerFactory.getLogger(TestController.class);
	
  @RequestMapping("/hello")
  public String hello() {
	return "Hello REST!!";
  } 
  
  @RequestMapping("/member")
  public MemberVO member() {
    MemberVO vo = new MemberVO();
    vo.setId("hong");
    vo.setPwd("1234");
    vo.setName("홍길동");
    vo.setEmail("hong@test.com");
    return vo;
  } 	
  
  @RequestMapping("/membersList")
  public List<MemberVO> listMembers () {
    List<MemberVO> list = new ArrayList<MemberVO>();
	for (int i = 0; i < 10; i++) {
	  MemberVO vo = new MemberVO();
	  vo.setId("hong"+i);
	  vo.setPwd("123"+i);
	  vo.setName("홍길동"+i);
	  vo.setEmail("hong"+i+"@test.com");
	  list.add(vo);
	}
    return list; 
  }	
  
  @RequestMapping("/membersMap")
  public Map<Integer, MemberVO> membersMap() {
    Map<Integer, MemberVO> map = new HashMap<Integer, MemberVO>();
    for (int i = 0; i < 10; i++) {
      MemberVO vo = new MemberVO();
      vo.setId("hong" + i);
      vo.setPwd("123"+i);
      vo.setName("홍길동" + i);
      vo.setEmail("hong"+i+"@test.com");
      map.put(i, vo); 
    }
    return map; 
  } 	
  
  @RequestMapping(value= "/notice/{num}" , method = RequestMethod.GET)
  public int notice(@PathVariable("num") int num ) throws Exception {
	  return num;
  }	

  @RequestMapping(value= "/info", method = RequestMethod.POST)
  public void modify(@RequestBody MemberVO vo ){
    logger.info(vo.toString());
  }
  
  // ResponseEntity 사용하기
  @RequestMapping("/membersList2")
  public  ResponseEntity<List<MemberVO>> listMembers2() {
	List<MemberVO> list = new ArrayList<MemberVO>();
	for (int i = 0; i < 10; i++) {
	  MemberVO vo = new MemberVO();
	  vo.setId("lee" + i);
	  vo.setPwd("123"+i);
	  vo.setName("이순신" + i);
      vo.setEmail("lee"+i+"@test.com");
	  list.add(vo);
	}
    return new ResponseEntity(list,HttpStatus.INTERNAL_SERVER_ERROR);
  }	
  
  // ResponseEntity 사용하기
	@RequestMapping(value = "/res3")
	public ResponseEntity res3() {
		HttpHeaders responseHeaders = new HttpHeaders();
	    responseHeaders.add("Content-Type", "text/html; charset=utf-8");
	    String message = "<script>";
		message += " alert('새 회원을 등록합니다.');";
		message += " location.href='/pro29/test/membersList2'; ";
		message += " </script>";
		return  new ResponseEntity(message, responseHeaders, HttpStatus.CREATED);
	}
	
}

2. MemberVO

package com.myspring.pro29.ex01;


public class MemberVO {
	private String id;
	private String pwd;
	private String name;
	private String email;
	
	public MemberVO() {
		
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	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;
	}
	
	@Override
	public String toString() {
		String info = id+", "+ pwd+", "+ name+", "+ email;
		return info;
	}

}

결과가 viewResolver로 안감

VO객체전달하기 : test/member

컬렉션객체전달하기 : test/membersList

Map 객체전달하기 : test/membersMap

PathVariable 사용하기 : test/notice/* : *에 들어간 값이 view로 리턴

--------------------------

// ResponseBody 사용하기

1. HomeController

package com.myspring.pro29;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	/*
	*//**
	 * Simply selects the home view to render by returning its name.
	 *//*
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}*/
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
	  return "JSONTest2";
	}
}

2. JSONTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"  isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>

<c:set var="contextPath" value="${pageContext.request.contextPath}"  />
<!DOCTYPE html>
<html>
<head>
<title>JSONTest</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>  
<script>
  $(function() {
      $("#checkJson").click(function() {
      	var member = { id:"park", 
  			    name:"박지성",
  			    pwd:"1234", 
  			    email:"park@test.com" };
  	$.ajax({
        type:"post",
        url:"${contextPath}/test/info",
        contentType: "application/json",
        data :JSON.stringify(member),
     success:function (data,textStatus){
     },
     error:function(data,textStatus){
        alert("에러가 발생했습니다.");
     },
     complete:function(data,textStatus){
     }
  });  //end ajax	
   });
});
</script>
</head>
<body>
  <input type="button" id="checkJson" value="회원 정보 보내기"/><br><br>
  <div id="output"></div>
</body>
</html>

------------------------------------

// ResponseBody 사용하기

1. ResController 

package com.myspring.pro29.ex02;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ResController {
	@RequestMapping(value = "/res1")
	@ResponseBody
	public Map<String, Object> res1() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", "hong");
		map.put("name", "È«±æµ¿");
		return map;
	}
	
	
	@RequestMapping(value = "/res2")
	public ModelAndView res2() {
		return new ModelAndView("home");
	}
	
}

 

--------------------------------

// 스프링 REST 방식으로 URI표현하기

1. BoardController

package com.myspring.pro29.ex03;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/boards")
public class BoardController {
	static Logger logger = LoggerFactory.getLogger(BoardController.class);
	
	@RequestMapping(value = "/all", method = RequestMethod.GET)
	public ResponseEntity<List<ArticleVO>> listArticles() {
		logger.info("listArticles 메서드 호출");
		List<ArticleVO> list = new ArrayList<ArticleVO>();
		for (int i = 0; i < 10; i++) {
			ArticleVO vo = new ArticleVO();
			vo.setArticleNO(i);
			vo.setWriter("이순신"+i);
			vo.setTitle("안녕하세요"+i);
			vo.setContent("새 상품을 소개합니다."+i);
			list.add(vo);
		}
		
		return new ResponseEntity(list,HttpStatus.OK);
	}
	
	@RequestMapping(value = "/{articleNO}", method = RequestMethod.GET)
	public ResponseEntity<ArticleVO> findArticle (@PathVariable("articleNO") Integer articleNO) {
		logger.info("findArticle 메서드 호출");
		ArticleVO vo = new ArticleVO();
		vo.setArticleNO(articleNO);
		vo.setWriter("홍길동");
		vo.setTitle("안녕하세요");
		vo.setContent("홍길동 글입니다");
		return new ResponseEntity(vo,HttpStatus.OK);
	}	
	
	
	@RequestMapping(value = "", method = RequestMethod.POST)
	public ResponseEntity<String> addArticle (@RequestBody ArticleVO articleVO) {
		ResponseEntity<String>  resEntity = null;
		try {
			logger.info("addArticle 메서드 호출");
			logger.info(articleVO.toString());
			resEntity =new ResponseEntity("ADD_SUCCEEDED",HttpStatus.OK);
		}catch(Exception e) {
			resEntity = new ResponseEntity(e.getMessage(),HttpStatus.BAD_REQUEST);
		}
		
		return resEntity;
	}	
	
	//수정하기
	@RequestMapping(value = "/{articleNO}", method = RequestMethod.PUT)
	public ResponseEntity<String> modArticle (@PathVariable("articleNO") Integer articleNO, @RequestBody ArticleVO articleVO) {
		ResponseEntity<String>  resEntity = null;
		try {
			logger.info("modArticle 메서드 호출");
			logger.info(articleVO.toString());
			resEntity =new ResponseEntity("MOD_SUCCEEDED",HttpStatus.OK);
		}catch(Exception e) {
			resEntity = new ResponseEntity(e.getMessage(),HttpStatus.BAD_REQUEST);
		}
		
		return resEntity;
	}
	
	//삭제하기
	@RequestMapping(value = "/{articleNO}", method = RequestMethod.DELETE)
	public ResponseEntity<String> removeArticle (@PathVariable("articleNO") Integer articleNO) {
		ResponseEntity<String>  resEntity = null;
		try {
			logger.info("removeArticle 메서드 호출");
			logger.info(articleNO.toString());
			resEntity =new ResponseEntity("REMOVE_SUCCEEDED",HttpStatus.OK);
		}catch(Exception e) {
			resEntity = new ResponseEntity(e.getMessage(),HttpStatus.BAD_REQUEST);
		}
		
		return resEntity;
	}	

}

2. JSONTest2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"  isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>

<c:set var="contextPath" value="${pageContext.request.contextPath}"  />
<!DOCTYPE html>
<html>
<head>
<title>JSONTest2</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>  
<script>
  $(function() {
      $("#checkJson").click(function() {
      	var article = {articleNO:"114", 
	               writer:"박지성",
	               title:"안녕하세요", 
	               content:"상품 소개 글입니다."
	              };
  
  	$.ajax({
  	    //type:"POST",
        //url:"${contextPath}/boards", // 새 글을 등록하는 메소드를 호출.
        type:"PUT",
        url:"${contextPath}/boards/114", // 글번호 114번에 대해 수정을 요청.
        contentType: "application/json",
        data :JSON.stringify(article), // 글 정보를 JSON 형식으로 전송.
      success:function (data,textStatus){
          alert(data);
      },
      error:function(data,textStatus){
        alert("에러가 발생했습니다.");ㅣ
      },
      complete:function(data,textStatus){
      }
   });  //end ajax	
   });
});
</script>
</head>
<body>
  <input type="button" id="checkJson" value="새글 쓰기"/><br><br>
  <div id="output"></div>
</body>
</html>

3. AricleVO

package com.myspring.pro29.ex03;

public class ArticleVO {
	private int articleNO;
	private String writer;
	private String title;
	private String content;
	
	
	public int getArticleNO() {
		return articleNO;
	}
	public void setArticleNO(int articleNO) {
		this.articleNO = articleNO;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
	
	
	@Override
	public String toString() {
		String info = "";
		info += "\n"+articleNO+"\n "
			        +writer+"\n"
			        +title+"\n"
			        +content;
			   
		return info;
	}
}

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

8일차  (0) 2019.10.17
7일차  (0) 2019.10.15
Maven 설치, Jenkins 설치  (0) 2019.10.14
Maven Project War파일 만들기 ~ 개발서버 배포  (0) 2019.10.14
프로젝트에서 꼭 활용할 내용들  (0) 2019.10.11
6일차  (0) 2019.10.11
Trackback 0 And Comment 0

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 - Spring FW' 카테고리의 다른 글

8일차  (0) 2019.10.17
7일차  (0) 2019.10.15
Maven 설치, Jenkins 설치  (0) 2019.10.14
Maven Project War파일 만들기 ~ 개발서버 배포  (0) 2019.10.14
프로젝트에서 꼭 활용할 내용들  (0) 2019.10.11
6일차  (0) 2019.10.11
Trackback 0 And Comment 0

Maven 설치, Jenkins 설치

|

1. Maven 설치

1. 파일다운

2. zip 파일 을 c:/spring 폴더에 붙여넣음

3. 환경변수 설정

4. 설치확인

cmd 들어가서 mvn 입력 후 다음과 같이 뜨면 정상설치된 것임.

 

 

2. Jenkins 설치

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

8일차  (0) 2019.10.17
7일차  (0) 2019.10.15
Maven 설치, Jenkins 설치  (0) 2019.10.14
Maven Project War파일 만들기 ~ 개발서버 배포  (0) 2019.10.14
프로젝트에서 꼭 활용할 내용들  (0) 2019.10.11
6일차  (0) 2019.10.11
Trackback 0 And Comment 0

Maven Project War파일 만들기 ~ 개발서버 배포

|

1. Goals 부분에 clean package 입력

2. apply 누르고 run 누르면 해당 프로젝트 target 폴더에 .war 파일 생성됨

3. .war 파일 C:\tomcat9\webapps 에 넣은후, tomcat 실행(이클립스 서버 끈 상태에서)

4. http://localhost:8090/mavenTest/index.jsp 접속

 

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

7일차  (0) 2019.10.15
Maven 설치, Jenkins 설치  (0) 2019.10.14
Maven Project War파일 만들기 ~ 개발서버 배포  (0) 2019.10.14
프로젝트에서 꼭 활용할 내용들  (0) 2019.10.11
6일차  (0) 2019.10.11
5일차  (0) 2019.10.10
Trackback 0 And Comment 0

프로젝트에서 꼭 활용할 내용들

|
1. AOP(Aspect Oriented Programming)
- 주기능과 보조기능을 분리한 후 선택적으로 메소드에 적용
- XML(aound advice) 스키마 기반
- aspect(클래스) 애노테이션 기반

// XML 설정파일
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
       
       
<!-- 공통 기능을 제공할 클래스를 빈으로 등록 -->
 <bean id="profiler" class="spring.apo.ex01.advice.ProfilerAdvice" />

 <!-- Aspect 설정: Advice를 어떤 Pointcut에 적용할 지 설정 -->
 <aop:config>
  <aop:aspect id="traceAspect" ref="profiler">
   // Aspect J의 표현식
   <aop:pointcut id="publicMethod" expression="execution(public * spring.apo.ex01..*(..))" />
   // pointcut 이라는 호출할 메소드의 범위를 결정하고 / * - 모든 파라미터를 가진 / (..) - 하위 패키지까지 포함.
   <aop:around pointcut-ref="publicMethod" method="trace" />
   // around - 호출시점 / trace - 공통기능
  </aop:aspect>
 </aop:config>

 <bean id="readArticleService" class="spring.apo.ex01.component.ReadArticleServiceImpl">
  <property name="articleDao" ref="articleDao" />
 </bean>

 <bean id="articleDao" class="spring.apo.ex01.component.ArticleDaoImpl" />       
       
</beans>

// Advice 클래스
// Aound Advice
// 다른 advice는 대상객체 호출을 spring FW이 실행
public class ProfilerAdvice {
// ProceedingJoinPoint joinPoint 파라미터이면 -> Around Advice이고,
 public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {
  String signatureString = joinPoint.getSignature().toShortString();
  System.out.println(signatureString + " 시작");
  long start = System.currentTimeMillis();
  try {
  // Around Advice이면, proceed() 메소드 제공한다.
   Object result = joinPoint.proceed(); // aspect가 적용될 대상 객체 호출
   return result;
  } finally {
   long finish = System.currentTimeMillis();
   System.out.println(signatureString + " 종료");
   System.out.println(signatureString + " 실행 시간 : " + (finish - start) + "ms");
  }
 }
}

2. AspectJ의 Pointcut 표현식

execution(public void set*(..)) : 리턴타입이 void이고 메소드이름이 set으로 시작하고 파라미터가 0개이상인 매소드 호출. 파라미터 부분에 ..을 사용하여 0개 이상인 것을 표현
execution(*.net.spring.*.*()) : spring 패키지의 파라미터가 없는 모든 메소드, 모든 리턴타입
execution(*.net.spring..*.*(..)) : spring 패키지의 파라미터가 0개 이상이고 패키지 부분에 ..을 표현하여 하위패키지를 표현
execution(Integer net.spring.boid.WriteArticleService.write(..)) : 리턴타입이 Integer인 WriteArticleService IF의 write() 메소드 호출
execution(* get*(*)) : 이름이 get으로 시작하고 1개의 파라미터를 갖는 메소드 호출
execution(* get*(*,*)) : 이름이 get으로 시작하고 2개의 파라미터를 갖는 메소드 호출
execution(* read*(Integer, ..)) : 이름이 read로 시작하고, 첫번째 파라미터 타입이 Integer이며, 1개의 파라미터를 갖는 메소드 호출

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

Maven 설치, Jenkins 설치  (0) 2019.10.14
Maven Project War파일 만들기 ~ 개발서버 배포  (0) 2019.10.14
프로젝트에서 꼭 활용할 내용들  (0) 2019.10.11
6일차  (0) 2019.10.11
5일차  (0) 2019.10.10
4일차  (0) 2019.10.08
Trackback 0 And Comment 0

6일차

|
// MVC 실습2




1. RegistrationController.java

package com.spring.mvc.ex02;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spring.mvc.ex02.component.MemberRegistRequest;
import com.spring.mvc.ex02.component.MemberRegistValidator;

@Controller("registrationController2")
@RequestMapping("/member/regist2")
public class RegistrationController {
 private static final String MEMBER_REGISTRATION_FORM = "member/registrationForm2";
 @Autowired
 private MemberService memberService2;

 @RequestMapping(method = RequestMethod.GET)
 public String form(@ModelAttribute("memberInfo") MemberRegistRequest memRegReq) {
  return MEMBER_REGISTRATION_FORM;
 }

 @RequestMapping(method = RequestMethod.POST)
 public String regist(
   @ModelAttribute("memberInfo") MemberRegistRequest memRegReq,
   BindingResult bindingResult) {
  new MemberRegistValidator().validate(memRegReq, bindingResult);
  if (bindingResult.hasErrors()) {
   return MEMBER_REGISTRATION_FORM;
  }
  memberService2.registNewMember(memRegReq);
  return "member/registered";
 }

 public void setMemberService(MemberService memberService) {
  this.memberService2 = memberService;
 }
}

2. MemberRegistValidator.java

package com.spring.mvc.ex02.component;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class MemberRegistValidator implements Validator {
	
	@Override
	public boolean supports(Class<?> clazz) {
		return MemberRegistRequest.class.isAssignableFrom(clazz); //검증할 수 있는 객체인지 리턴
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		MemberRegistRequest regReq = (MemberRegistRequest) target;
		if(regReq.getEmail() == null || regReq.getEmail().trim().isEmpty())
			errors.rejectValue("email", "required");
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "required");
		if(regReq.hasPassword()) {
			if(regReq.getPassword().length() < 5 )
				errors.rejectValue("password", "shortPassword");
			else if(!regReq.isSamePasswordConfirmPassword())
				errors.rejectValue("confirmPassword", "notSame");
		}
		Address address = regReq.getAddress();
		if(address == null) {
			errors.rejectValue("address", "required");
		} else {
			errors.pushNestedPath("address");
			try {
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address1", "required");
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address2", "required");
			} finally {
				errors.popNestedPath();
			}
		}
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthday", "required");
	}

}

3. registrationForm2.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>회원 가입</title>
</head>
<body>

<spring:hasBindErrors name="memberInfo" />
<form method="post">
<label for="email">이메일</label>: 
<input type="text" name="email" id="email" value="${memberInfo.email}"/>
<form:errors path="memberInfo.email"/> <br/>

<label for="name">이름</label>: 
<input type="text" name="name" id="name" value="${memberInfo.name}" />
<form:errors path="memberInfo.name"/> <br/>

<label for="password">암호</label>: 
<input type="password" name="password" id="password" value="${memberInfo.password}"/>
<form:errors path="memberInfo.password"/> <br/>

<label for="password">확인</label>: 
<input type="password" name="confirmPassword" id="confirmPassword" value="${memberInfo.confirmPassword}"/>
<form:errors path="memberInfo.confirmPassword"/> <br/>

<label>주소</label>:
주소1 
<input type="text" name="address.address1" value="${memberInfo.address.address1}" />
<form:errors path="memberInfo.address.address1"/> <br/>
주소2
<input type="text" name="address.address2" value="${memberInfo.address.address2}" />
<form:errors path="memberInfo.address.address2"/> <br/>
우편번호
<input type="text" name="address.zipcode" value="${memberInfo.address.zipcode}" />
<form:errors path="memberInfo.address.zipcode"/> <br/>

<label>
 <input type="checkbox" name="allowNoti" value="true" ${memberInfo.allowNoti ? 'checked' : '' }/>
 이메일을 수신합니다.
</label>
<br/>
<label for="birthday">생일</label>: 형식: YYYYMMDD, 예: 20140101
<input type="text" name="birthday" id="birthday" value='<fmt:formatDate value="${memberInfo.birthday}" pattern="yyyyMMdd" />'/>
<form:errors path="memberInfo.birthday"/> <br/>

<input type="submit" value="가입" />

</form>
</body>
</html>

4. error.properties

required = 필수 항목입니다.
required.email = 이메일을 입력하세요.
minlength = 최소{1} 글자 이상 입력해야 합니다.
maxlength = 최대 {1} 글자 까지만 입력해야 합니다.
invalidIdOrPassword.loginCommand=아이디와 암호가 일치하지 않습니다.
invalidPassword=암호가 일치하지 않습니다.
shortPassword=암호 길이가 짧습니다.
notSame.confirmPassword=입력한 값이 암호와 같지 않습니다.
typeMismatch.birthday=날짜 형식이 올바르지 않습니다.

NotEmpty=필수 항목입니다.
NotEmpty.currentPassword=현재 암호를 입력하세요.
Email=올바른 이메일 주소를 입력해야 합니다.

badBeginDate=이벤트 시작일이 잘못되었습니다.
badEndDate=이벤트 종료일이 잘못되었습니다.
typeMismatch.beginDate=시작 날짜 형식이 올바르지 않습니다.
typeMismatch.endDate=종료 날짜 형식이 올바르지 않습니다.

5. dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
	xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />
	<context:component-scan base-package="com" />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<beans:bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<beans:property name="basenames">
			<beans:list>
				<beans:value>message.error</beans:value>
			</beans:list>
		</beans:property>
		<beans:property name="defaultEncoding" value="UTF-8" />
	</beans:bean>

</beans:beans>

// MVC실습 3

1. LoginController.java

package com.spring.mvc.ex03;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spring.mvc.ex03.component.Auth;
import com.spring.mvc.ex03.component.AuthenticationException;
import com.spring.mvc.ex03.component.Authenticator;
import com.spring.mvc.ex03.component.LoginCommand;
import com.spring.mvc.ex03.component.LoginCommandValidator;

@Controller
@RequestMapping("/auth/login")
public class LoginController {

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

 @RequestMapping(method = RequestMethod.GET)
 public String loginForm(LoginCommand loginCommand) {
  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());
 }

 public void setAuthenticator(Authenticator authenticator) {
  this.authenticator = authenticator;
 }
}

2. LoginCommandValidator.java

package com.spring.mvc.ex03.component;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class LoginCommandValidator implements Validator {
	
	@Override
	 public boolean supports(Class<?> clazz) {
	  return LoginCommand.class.isAssignableFrom(clazz);
	 }

	 @Override
	 public void validate(Object target, Errors errors) {
	  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "required");
	  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required");
	 }
	}

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

Maven Project War파일 만들기 ~ 개발서버 배포  (0) 2019.10.14
프로젝트에서 꼭 활용할 내용들  (0) 2019.10.11
6일차  (0) 2019.10.11
5일차  (0) 2019.10.10
4일차  (0) 2019.10.08
3일차  (0) 2019.10.07
Trackback 0 And Comment 0

5일차

|
// SimpleUrlController 이용해 스프링 MVC 실습하기

1. action-servlet.xml : 빈 설정

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

// id가 simpleUrlController 인 빈을 생성
<bean id="simpleUrlController" class="com.spring.ex01.SimpleUrlController"/>
// SimpleUrlHandlerMapping클래스를 이용해 /test/index.do로 요청시 simpleUrlcontroller 호출하도록 매핑
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	  <property  name="mappings">
	    <props>
	      <prop key="/test/index.do">simpleUrlController</prop>
	    </props>
	  </property>  
	</bean>
</beans>

2. web.xml : *.do로 요청시 스프링의 DispatcherServlet 클래스가 요청을 받을수 있게 서블릿 매핑을 함.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
   <servlet>
      <servlet-name>action</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>// 값이 1이상 : 톰캣 실행시 DispatcherServlet을 미리 메모리에 로드함.(미설정이거나 음수 : 브라우저에서 요청시 메모리에 로드)
   </servlet>

   <servlet-mapping>
      <servlet-name>action</servlet-name>
      <url-pattern>*.do</url-pattern>
   </servlet-mapping>
</web-app>

3. SimpleUrlController.java : 컨트롤러

package com.spring.ex01;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class SimpleUrlController implements Controller{ // 스프링에서 제공하는 Controller 인터페이스 반드시 구현

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{
		return new ModelAndView("index.jsp");
	}

}

4. index.jsp : 브라우저로 전송

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>spring test</title>
</head>
<body>
	<h1>index.jsp파일이다</h1>
	<p>hi spring!</p>
</body>
</html>
// MultiActionController이용해 스프링 MVC 실습하기

1. action-servlet.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="simpleUrlController" class="com.spring.ex01.SimpleUrlController"/>
	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	  <property  name="mappings">
	    <props>
	      <prop key="/test/index.do">simpleUrlController</prop>
	    </props>
	  </property>  
	</bean>
	
    // 컨트롤러에서 ModelAndView 인자로 뷰이름이 반환되면 InternalResourceViewResolver의 프로퍼티
    // prefix 속성에 지정된 폴더에서 뷰이름에 해당하는 jsp를 선택해 DispatcherServlet으로 보냄.
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/test/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="userUrlMapping"
		class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/test/*.do">userController</prop>
			</props>
		</property>
	</bean>

	// methodNameResolver 프로퍼티에 userMethodNameResolver를 주입해서 지정한 요청명에 대해
    // 직접 메소드를 호출하게 됨.
	<bean id="userController" class="com.spring.ex02.UserController">
		<property name="methodNameResolver">
			<ref local="userMethodNameResolver" />
		</property>
	</bean>

	// PropertiesMethodNameResolver를 이용해 /test/login.do 로 요청하면 userController의 login 메소드를 호출.
	<bean id="userMethodNameResolver"
		  class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
		<property name="mappings">
			<props>
				<prop key="/test/login.do">login</prop>
				<prop key="/test/memberInfo.do">memberInfo</prop> 
			</props>
		</property>
	</bean>
	
</beans>

2. UserController.java

package com.spring.ex02;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class UserController extends MultiActionController{ // userMethodNameResolver 프로퍼티 사용하려면 반드시 MultiActionController를 상속받아야함.
	
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String userID;
		String passwd;
		ModelAndView mav = new ModelAndView();
		request.setCharacterEncoding("utf-8");
		userID = request.getParameter("userID");
		passwd = request.getParameter("passwd");
        // ModelAndView에 로그인 정보 바인딩
		mav.addObject("userID", userID);
		mav.addObject("passwd", passwd);
		mav.setViewName("result"); // ModelAndView객체에 포워딩할 jsp이름 설정
		return mav;
	}

}

3. loginForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath"  value="${pageContext.request.contextPath}"  />
<%
   request.setCharacterEncoding("UTF-8");
%>     
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
<title>로그인창</title>
</head>

<body>
<form name="frmLogin" method="post"  action="${contextPath}/test/login.do">
   <table border="1"  width="80%" align="center" >
      <tr align="center">
         <td>아이디</td>
         <td>비밀번호</td>
      </tr>
      <tr align="center">
         <td>
	    <input type="text" name="userID" value="" size="20">
	 </td>
         <td>
	    <input type="password" name="passwd" value="" size="20">
	 </td>
      </tr>
      <tr align="center">
         <td colspan="2">
            <input type="submit" value="로그인" > 
            <input type="reset"  value="다시입력" > 
         </td>
      </tr>
   </table>
</form>
</body>
</html>

4. result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
isELIgnored="false" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
   request.setCharacterEncoding("UTF-8");
%> 
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>결과창</title>
</head>
<body>
<table border="1" width="50%" align="center" >

   <tr align="center">
      <td>아이디</td>
      <td>비밀번호</td>
   </tr>
   <tr align="center">
      <td>${userID}</td>
      <td>${passwd}</td>
   </tr>
</table>
</body>
</html>

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

프로젝트에서 꼭 활용할 내용들  (0) 2019.10.11
6일차  (0) 2019.10.11
5일차  (0) 2019.10.10
4일차  (0) 2019.10.08
3일차  (0) 2019.10.07
개발표준  (0) 2019.09.30
Trackback 0 And Comment 0

4일차

|
// 1. 스프링 API를 이용한 AOP 기능 실습.

1. AOPTest.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
	<bean id="calcTarget" class="com.spring.ex01.Calculator"/> // 주기능 - 타깃 클래스를 빈으로 지정
	<bean id="logAdivce" class="com.spring.ex01.LoggingAdvice"/> // 공통기능 - 로그기능을 하는 어드바이스를 지정
    //스프링 프레임워크에서 제공하는 ProxyFactoryBean을 이용해 타깃과 어드바이스를 엮어줌.
	<bean id="proxyCal" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="target" ref="calcTarget"/> // 타깃 빈을 calcTest 빈으로 지정
        // 스프링의 ProxyFactoryBean의 interceptorNames 속성에 logAdvice를 어드바이스 빈으로 설정하여
        // 타깃 클래스의 메소드 호출시 logAdvice를 실행.
		<property name="interceptorNames">
			<list>
				<value>logAdivce</value>
			</list>
		</property>
	</bean>
</beans>

2. Calculator.java

package com.spring.ex01;

public class Calculator {
	public void add(int x, int y) {
		int result= x + y;
		System.out.println("결과: " + result);
	}
	public void subtract(int x, int y) {
		int result= x - y;
		System.out.println("결과: " + result);
	}
	public void multiply(int x, int y) {
		int result= x * y;
		System.out.println("결과: " + result);
	}
	public void divide(int x, int y) {
		int result= x / y;
		System.out.println("결과: " + result);
	}

}


3. LoggingAdvice.java

package com.spring.ex01;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

// 인터페이스 MethodInterceptor를 구현해 어드바이스 클래스를 만듬.
public class LoggingAdvice implements MethodInterceptor{
	
	public Object invoke(MethodInvocation invocation) throws Throwable{
		System.out.println("[메소드 호출 전 : LogginAdivce");
		System.out.println(invocation.getMethod() + "메소드 호출 전");
		
		Object object = invocation.proceed(); // invocation을 이용해 메소드를 호출.
		
		System.out.println("[메소드 호출 후 : LogginAdivce");
		System.out.println(invocation.getMethod() + "메소드 호출 후");
		return object;
	}

}

4. CalcTest.java

package com.spring.ex01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CalcTest {

	public static void main(String[] args) {
    	// AOPTest.xml을 읽어들여 빈을 생성.
		ApplicationContext context = new ClassPathXmlApplicationContext("AOPTest.xml");
		Calculator cal = (Calculator) context.getBean("proxyCal"); // id가 proxyCal인 빈에 접근.
        // proxyFactoryBean은 AOP설정이 반영된 Target객체를 리턴한다.
        // 메소드 호출 전후에 어드바이스 빈이 적용됨.
		cal.add(100, 20);
		System.out.println();
		cal.subtract(100, 20);
		System.out.println();
		cal.multiply(100, 20);
		System.out.println();
		cal.divide(100, 20);

	}

}

// XML 스키마 기반 AOP 퀵 스타트 실습

1. MainQuickStart.java

package spring.apo.ex01;

import org.springframework.context.support.GenericXmlApplicationContext;

import spring.apo.ex01.component.ReadArticleService;

public class MainQuickStart {

 public static void main(String[] args) {
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:acQuickStart.xml");

  ReadArticleService readArticleService = ctx.getBean(ReadArticleService.class);
  readArticleService.read(1); 
  
  ctx.close();
 }
}

2. ProfilerAdvice.java

package spring.apo.ex01.advice;

import org.aspectj.lang.ProceedingJoinPoint;

// Aound Advice
// 다른 advice는 대상객체 호출을 spring FW이 실행
public class ProfilerAdvice {
// ProceedingJoinPoint joinPoint 파라미터이면 -> Around Advice이고,
 public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {
  String signatureString = joinPoint.getSignature().toShortString();
  System.out.println(signatureString + " 시작");
  long start = System.currentTimeMillis();
  try {
  // Around Advice이면, proceed() 메소드 제공한다.
   Object result = joinPoint.proceed(); // aspect가 적용될 대상 객체 호출
   return result;
  } finally {
   long finish = System.currentTimeMillis();
   System.out.println(signatureString + " 종료");
   System.out.println(signatureString + " 실행 시간 : " + (finish - start) + "ms");
  }
 }
}

3. asQuickStart.xml

<?xml version="1.0" encoding="UTF-8"?>



<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
       
       
<!-- 공통 기능을 제공할 클래스를 빈으로 등록 -->
 <bean id="profiler" class="spring.apo.ex01.advice.ProfilerAdvice" />

 <!-- Aspect 설정: Advice를 어떤 Pointcut에 적용할 지 설정 -->
 <aop:config>
  <aop:aspect id="traceAspect" ref="profiler">
   // Aspect J의 표현식
   <aop:pointcut id="publicMethod" expression="execution(public * spring.apo.ex01..*(..))" />
   // pointcut 이라는 호출할 메소드의 범위를 결정하고 / * - 모든 파라미터를 가진 / (..) - 하위 패키지까지 포함.
   <aop:around pointcut-ref="publicMethod" method="trace" />
   // around - 호출시점 / trace - 공통기능
  </aop:aspect>
 </aop:config>

 <bean id="readArticleService" class="spring.apo.ex01.component.ReadArticleServiceImpl">
  <property name="articleDao" ref="articleDao" />
 </bean>

 <bean id="articleDao" class="spring.apo.ex01.component.ArticleDaoImpl" />       
       
</beans>

// @Aspect 애노테이션 기반 AOP 퀵 스타트

1. MainQuickStart2.java

package spring.apo.ex02;

import spring.apo.ex02.component.ReadArticleService;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainQuickStart2 {

	public static void main(String[] args) {
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:acQuickStart2.xml");

		  ReadArticleService readArticleService = ctx.getBean(ReadArticleService.class);
		  readArticleService.read(1);

		  ctx.close();
	}
}


2. ProfilingAspect.java

package spring.apo.ex02.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class ProfilingAspect {
	
	@Pointcut("execution(public * spring.apo.ex02..*(..))")
	private void profileTarget() {
		
	}
	
	@Around("profileTarget()") // profileTarget()의 pointcut 정보를 쓰겠다.
	public Object trace(ProceedingJoinPoint joinPoint) throws Throwable{
		 String signatureString = joinPoint.getSignature().toShortString();
		  System.out.println(signatureString + " 시작");
		  long start = System.currentTimeMillis();
		  try {
		   Object result = joinPoint.proceed(); // 타겟의 메소드 호출.
		   return result;
		  } finally {
		   long finish = System.currentTimeMillis();
		   System.out.println(signatureString + " 종료");
		   System.out.println(signatureString + " 실행 시간 : " + 
		     (finish - start) + "ms");
		  }	
	}
}

3. asQuickStart2.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
       
       <aop:aspectj-autoproxy /> // proxy를 자동으로 호출.

		    <!-- Aspect 클래스를 빈으로 등록 -->
		    <bean id="performanceTraceAspect" class="spring.apo.ex02.aspect.ProfilingAspect" />
		
		 <bean id="readArticleService" class="spring.apo.ex02.component.ReadArticleServiceImpl">
		  <property name="articleDao" ref="articleDao" />
		 </bean>
		
		 <bean id="articleDao" class="spring.apo.ex02.component.ArticleDaoImpl" />

</beans>

@Pointcut 메소드 사용시 입력방법

- 같은 클래스 : 메소드 이름

- 같은 패키지 : 클래스명.메소드이름

- 다른 패키지 : 패지키명.클래스명.메소드이름

// 스프링 애너테이션 이용해 URL 요청 실습

1.action-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <!--<property name="prefix" value="/WEB-INF/views/test/" /> -->
  <property name="prefix" value="/WEB-INF/views/test/" />
  <property name="suffix" value=".jsp" />
 </bean>
// 클래스 레벨에 @RequestMapping 처리
 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
 // 메소드 레벨에 @RequestMapping 처리
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
 <context:component-scan base-package="com.spring" /> // com.spring 패키지에 존재하는 클래스에 애너테이션 적용되도록 설정.
</beans>

2. main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" 
    isELIgnored="false"  %>
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
<%
  request.setCharacterEncoding("UTF-8");
%>    


<html>
<head>
<meta charset=UTF-8">
<title>결과창</title>
</head>
<body>
<h1>안녕하세요!!</h1>
<h1>${msg} 페이지입니다!!</h1>
</body>
</html>

3. MainController.java

package com.spring.ex01; // 애너테이션이 적용되도록 하려면 해당 클래스가 반드시 Component-scan에서 설정한 패키지나 하위패키지에 존재해야함,

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; 

@Controller("maincontroller")
@RequestMapping("/test1")
public class MainController {
	@RequestMapping(value="/main1.do", method=RequestMethod.GET)
	public ModelAndView main1(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mav = new ModelAndView(); 
		mav.addObject("msg", "main1");
		mav.setViewName("main");
		return mav;
	}
	@RequestMapping(value="/main2.do", method=RequestMethod.GET)
	public ModelAndView main2(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mav = new ModelAndView();
		mav.addObject("msg", "main2");
		mav.setViewName("main");
		return mav;
	}
	
}

4. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
     </listener-class>
   </listener>

   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
      </param-value>
   </context-param>  

 <servlet>
  <servlet-name>action</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>

</web-app>

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

6일차  (0) 2019.10.11
5일차  (0) 2019.10.10
4일차  (0) 2019.10.08
3일차  (0) 2019.10.07
개발표준  (0) 2019.09.30
1일차  (0) 2019.09.30
Trackback 0 And Comment 0

3일차

|

<class 값을 통해 유추해라 ★★>

linked : 중간 삽입/삭제가 수월

Hash : 빠름

Map : key, value

set : 유일

 

// 의존성 주입 실습

-- person.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
	<bean id="personService" class="com.spring.ex01.PersonServiceImpl">
    // bean 태그를 이용해 PersonServiceImpl 객체를 생성한 후 빈id를 personService로 지정.
		<property name="name">
			<value>홍길동</value>
		</property>
        // PersonServiceImpl 객체의 속성 name값을 value태그를 이용해 홍길동으로  초기화.
	</bean>
</beans>

-- PersonService.java

package com.spring.ex01;

public interface PersonService {
	public void sayHello();
}

-- PersonServiceImpl.java

package com.spring.ex01;

public class PersonServiceImpl implements PersonService{
	private String name;
	private int age;
	
    // value 태그의 값을 setter를 이용해 설정.
	public void setName(String name) {
		this.name = name;
	}
	
	public void sayHello() {
		System.out.println("이름 : " + name);
		System.out.println("나이 : " + age);
	}

}

-- PersonTest.java

package com.spring.ex01;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class PersonTest {

	public static void main(String[] args) {
    	// 실행시 person.xml 을 읽어 들여 빈을 생성.
		BeanFactory factory = new XmlBeanFactory(new FileSystemResource("person.xml"));
        // id가 personService인 빈을 가져옴.
		PersonService person = (PersonService)factory.getBean("personService");
        // PersonService person = new PersonServiceImpl();
        // 더이상 자바코드에서 객체를 직접 생성하지 않아도 되므로 주석처리함.
		person.sayHello(); // 생성된 빈을 이용해 name값을 출력.
	
	}

}

------------------------------------------------------------------------
// 회원 기능 이용해 DI 실습하기
-- member.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
	// 주입되는 데이터가 기본형이 아닌 참조형인 경우 ref속성으로 설정.
    // 빈을 만들면서 setter 주입방식으로 id가 memberDAO인 빈을 자신의 속성에 주입.
	<bean id="memberService" class="com.spring.ex03.MemberServiceImpl">
		<property name="memberDAO" ref="memberDAO"/>
	</bean>
	<bean id="memberDAO" class="com.spring.ex03.MemberDAOImpl"/>
</beans>

-- MemberServiceImpl.java

package com.spring.ex03;

public class MemberServiceImpl implements MemberService {
	private MemberDAO memberDAO; // 주입되는 빈을 저장할 MemberDAO 타입의 속성을 선언.

	// 설정 파일에서 memberDAO 빈을 생성 후 setter로 속성 memberDAO에 주입.
	public void setMemberDAO(MemberDAO memberDAO) {
		this.memberDAO = memberDAO;
	}

	@Override
	public void listMembers() {
		memberDAO.listMembers();
	}
}

-- MemberDAOImpl.java

package com.spring.ex03;

public class MemberDAOImpl implements MemberDAO {
	@Override
	public void listMembers() {
		System.out.println("listMembers  메서드 호출");
		System.out.println("회원정보를 조회합니다.");
	}
}

-- MemberTest1.java

package com.spring.ex03;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class MemberTest1 {
	public static void main(String[] args) {
    	// 실행시 member.xml에 설정한 대로 빈을 생성한 후 주입.
		BeanFactory factory = new XmlBeanFactory(new FileSystemResource("member.xml"));
        // id가 memberService인 빈을 가져옴.
		MemberService service = (MemberService) factory.getBean("memberService");
		service.listMembers();
	}
}

------------------------------------------------------------------------
//

------------------------------------------------------------------------
//

------------------------------------------------------------------------
//

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

6일차  (0) 2019.10.11
5일차  (0) 2019.10.10
4일차  (0) 2019.10.08
3일차  (0) 2019.10.07
개발표준  (0) 2019.09.30
1일차  (0) 2019.09.30
Trackback 0 And Comment 0
prev | 1 | 2 | 3 | 4 | ··· | 19 | next