2016년 10월 6일 목요일

06day Spring

1.스프링 템플릿에서 데이터 보내고 처리된 데이터 뷰페이지로 보내기

폴더구조

web.xml ----매핑을 기본 탬플릿에서 *.do로 바꿈, 한글필터 적용함
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!-- 한글 인코딩 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
        </init-param>
        <init-param>
          <param-name>forceEncoding</param-name>
          <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
      <filter-name>encodingFilter</filter-name>
      <url-pattern>*.do</url-pattern>
    </filter-mapping>
  
    <!-- 모든 서블릿에서 활용가능한 공유자원 정의  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- 공유자원 컨테이너 생성 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 서블릿 -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>*.do</url-pattern><!-- 매핑패턴 -->
    </servlet-mapping>

</web-app>

servlet-context.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: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 />

    <!-- 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>
    
    <context:component-scan base-package="com.exam.web01" />
    
    
    
</beans:beans>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

index.jsp
<!-- index(data) ▶ list.do ▶ConfigController(데이터 처리) ▶ view(데이터 받음) -->
<form action="./list3.do" method="post">
    데이터1 :<input type="text" name="data1">
    데이터2 :<input type="text" name="data2">
    <input type="submit" value="전송">
</form>
</body>
</html>

ConfigController.java
package com.exam.web01;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ConfigController {
 //첫번째 방법
 @RequestMapping("/list1.do")
 public String handleRequest1(
   @RequestParam("data1") String data1,
   @RequestParam("data2") String data2, Model model){
   
   System.out.println("data1 : "+data1);
   System.out.println("data2 : "+data2);
   
   model.addAttribute("data1",data1);
   model.addAttribute("data2",data2);
   
   return "listview";
 }
 
 //두번쨰 방법
 @RequestMapping("list2.do")
 public ModelAndView handleRequest2(
   @RequestParam("data1") String data1,
   @RequestParam("data2") String data2){
   
   ModelAndView modelAndView = new ModelAndView();
   modelAndView.setViewName("listview");
   modelAndView.addObject("data1", data1);
   modelAndView.addObject("data2", data2);
   
   return modelAndView;
 }
 
 //세번째 방법
 @RequestMapping("list3.do")
 public String handleRequest3(
   HttpServletResponse response,
   HttpServletRequest request,
   Model model){
  
  model.addAttribute("data1", request.getParameter("data1"));
  model.addAttribute("data2", request.getParameter("data2"));
  
  return "listview";
 }
   
}

listview.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    listview.jsp<br />
    
    data1 : <%= request.getAttribute("data1") %> <br />
    data2 : <%= request.getAttribute("data2") %> <br />
</body>
</html>


2.파일전송

먼저 파일전송을 위한 cos라이브러리를 다운받아야함.http://mvnrepository.com/artifact/com.servlets/cos/09May2002
maven사이트에서 라이브러리 검색을 하고, pom.xml에 붙어넣을 dependency 가져옴


라이브러리 가져오는 2번째 방법은 이클립스pom.xml dependencies탭에서 cos라이브러리 검색


폴더구조

web.xml --- 기본탬플릿에서 *.do로 매핑함
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

</web-app>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
index.jsp
<form action="./upload.do" method="post" enctype="multipart/form-data">
    파일 : <input type="file" name="upload" />
    <input type="submit" value="전송"/>
</form>
</body>
</html>

UploadController.java
package com.exam.web02;

import java.io.IOException;

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 com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

@Controller
public class UploadController {
 @RequestMapping(value="/upload.do", method=RequestMethod.POST)
 public String handleRequest(
   HttpServletResponse response,
   HttpServletRequest request){
  
  //업로드 조건 지정
  String uploadPath ="C:/spring/workspace/WEBEx02/src/main/webapp/upload";
  int maxFileSize = 1024*1024*2;
  String encoding = "utf-8";
  
  try {
   //파일이 업로드 됨
   MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encoding, new DefaultFileRenamePolicy());
   
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  return "upload";
 }
}

upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    파일업로드 됨
</body>
</html>


2016년 10월 5일 수요일

05day Spring

1. 액션으로 get, post방식으로 데이터 보내기

폴더구성


web.xml
<?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">
  <display-name>MVCEx02</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 서블릿 설정 -->
  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/webContext.xml</param-value><!-- 사용할 webContext 파일 설정 -->
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

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

    <bean name="/list1.do" class="spring.listController" /> <!-- list1.do를 호출했을때 listController로 보냄 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="list1.do" method="get">
    데이터 <input type="text" name="data" />
    <input type="submit" value="get전송" />
</form>

<form action="list1.do" method="post">
    데이터 <input type="text" name="data" />
    <input type="submit" value="post전송" />
</form>

</body>
</html>

listController.java 만들때 controller상속 받음

package spring;

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 listController implements Controller {

 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
  // HttpServletRequest가 넘어옴
  
  System.out.println("listController 호출");
  System.out.println(arg0.getParameter("data"));
  
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("listview"); //데이터를 보낼 파일명을 적음
  
  return modelAndView;
 }

}

listview.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/views/listview.jsp -->
/WEB-INF/views/listview.jsp

</body>
</html>


2. 한글깨짐 인코딩 처리

listController.java 에서 처리
package spring;

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 listController implements Controller {

 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
  // HttpServletRequest가 넘어옴
  
  //post방식일때 한글 깨지는 것 막음// controller에서 일일이 처리하는 방식은 잘 사용하지 않음 web.xml에서 필터사용
  arg0.setCharacterEncoding("utf-8");
  
  System.out.println("listController 호출");
  System.out.println(arg0.getParameter("data"));
  
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("listview"); //데이터를 보낼 파일명을 적음
  
  return modelAndView;
 }

}

web.xml 에서 모든페이지 필터링 처리
<?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">
  <display-name>MVCEx02</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 한글 인코딩 필터 설정 -->
  <filter>
      <filter-name>encodingFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
      </init-param>
      <init-param>
          <param-name>forceEncoding</param-name>
          <param-value>true</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>encodingFilter</filter-name>
      <url-pattern>*.do</url-pattern>
  </filter-mapping>
  <!-- 서블릿 설정 -->
  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/webContext.xml</param-value><!-- 사용할 webContext 파일 설정 -->
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>


3. webContext 여러개일경우
web.xml
<?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">
  <display-name>MVCEx02</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 한글 인코딩 필터 설정 -->
  <filter>
      <filter-name>encodingFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
      </init-param>
      <init-param>
          <param-name>forceEncoding</param-name>
          <param-value>true</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>encodingFilter</filter-name>
      <url-pattern>*.do</url-pattern>
  </filter-mapping>
  <!-- 서블릿 설정 -->
  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value><!-- 사용할 webContext 파일 2개를 병렬적으로 가져와도 상관 없음 ex)게시판용, 로그인용-->
              /WEB-INF/webContext.xml
              /WEB-INF/webContext2.xml
          </param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>


4. controller에서 받은 데이터 view.jsp로 넘김

listController.java
package spring;

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 listController implements Controller {

 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
  // HttpServletRequest가 넘어옴
  
  //post방식일때 한글 깨지는 것 막음// controller에서 일일이 처리하는 방식은 잘 사용하지 않음 web.xml에서 필터사용
  //arg0.setCharacterEncoding("utf-8");
  
  System.out.println("listController 호출");
  System.out.println(arg0.getParameter("data"));
  
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("listview"); //데이터를 보낼 파일명을 적음
  
  //방법 1 - 받은 데이터 넘김
  //arg0.setAttribute("data", arg0.getParameter("data")); 
  
  //방법 2
  modelAndView.addObject("data", arg0.getParameter("data"));
  
  return modelAndView;
 }

}

listview.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/views/listview.jsp -->
/WEB-INF/views/listview.jsp <br />
받은 테이터 : <%= request.getAttribute("data") %>

</body>
</html>


5. 공유데이터

폴더구성 ---스프링프로젝트 구조와 비슷하게 만듦


web.xml
<?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">
  <display-name>MVCEx04</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 필터 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>
  
  <!-- 공유자료 환경설정 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 서블릿 -->
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

servlet-context.xml bean 만들때 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
    xmlns="http://www.springframework.org/schema/mvc" 
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <!-- list.do를 호출했을때 listController로 보냄 -->
    <beans:bean name="/list1.do" class="spring.ListController1" >
        <beans:property name="shareClass" ref="shareData" />
    </beans:bean>
    <beans:bean name="/list2.do" class="spring.ListController2">
        <beans:property name="shareClass" ref="shareData" />
    </beans:bean>
    
    <!-- 컨트롤러에서 보내는 파일명을 적으면 앞뒤로 경로를 붙여줌 -->
    <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
</beans:beans>

ListController1.java
package spring;

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

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

import share.shareData;

public class ListController1 implements Controller {

 private shareData shareClass;
 
 public void setShareClass(shareData shareClass){
  this.shareClass = shareClass;
 }
 
 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("ListController1 호출");
  System.out.println("공유자료 : "+shareClass.getShareData());
  
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("listview1");
  
  return modelAndView;
 }

}

ListController2.java
package spring;

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

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

import share.shareData;

public class ListController2 implements Controller {
 private shareData shareClass;
 
 public void setShareClass(shareData shareClass){
  this.shareClass = shareClass;
 }
 
 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("ListController2 호출");
  System.out.println("공유자료 : "+shareClass.getShareData());
  
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("listview2");
  
  return modelAndView;
 }

}

listview1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/views/listview.jsp -->
/WEB-INF/views/listview1.jsp <br />

</body>
</html>

listview2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/views/listview.jsp -->
/WEB-INF/views/listview2.jsp <br />

</body>
</html>

root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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-4.3.xsd">
    
    <!-- 공유자료 빈 -->
    <bean id="shareData" class="share.shareData">
        <property name="shareData" value="난 공유자료" />
    </bean>

</beans>

shareData.java
package share;

public class shareData {
    private String shareData;

    public String getShareData() {
        return shareData;
    }

    public void setShareData(String shareData) {
        this.shareData = shareData;
    }
    
}


6. 어노테이션 방법

폴더구조

web.xml
<?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">
  <display-name>MVCEx05</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>
  
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
    xmlns="http://www.springframework.org/schema/mvc"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <!-- 어노테이션 컨트롤러 지정함 -->
    <beans:bean class="spring.ConfigController" />
    
    <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

</beans:beans>

ConfigController.java
package spring;

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

@Controller
public class ConfigController {
 @RequestMapping("/list1.do") //list1.do를 요청하면 작동됨
 public ModelAndView handleRequest1(){
  System.out.println("handleRequest1() 호출");
  
  return new ModelAndView("listview1"); //listview1을 보여줌
 }
 
 @RequestMapping("/list2.do") //list2.do를 요청하면 작동됨
 public ModelAndView handleRequest2(){
  System.out.println("handleRequest2() 호출");
  
  return new ModelAndView("listview2"); //listview2을 보여줌
 }
}

listview1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/views/listview.jsp -->
/WEB-INF/views/listview1.jsp <br />

</body>
</html>

listview2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/views/listview.jsp -->
/WEB-INF/views/listview2.jsp <br />

</body>
</html>


7. 컨트롤러 두개를 분리

servlet-context2.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
    xmlns="http://www.springframework.org/schema/mvc"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <!-- 어노테이션 컨트롤러를 여러개 지정할 수 있음 -->
    <beans:bean class="spring.ConfigController1" />
    <beans:bean class="spring.ConfigController2" />
    
    <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

</beans:beans>

ConfigController1.java
package spring;

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

@Controller
public class ConfigController1 {
 @RequestMapping("/list1.do") //list1.do를 요청하면 작동됨
 public ModelAndView handleRequest1(){
  System.out.println("handleRequest1() 호출");
  
  return new ModelAndView("listview1"); //listview1을 보여줌
 }
}

ConfigController2.java
package spring;

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

@Controller
public class ConfigController2 {
 
 @RequestMapping("/list2.do") //list2.do를 요청하면 작동됨
 public ModelAndView handleRequest2(){
  System.out.println("handleRequest2() 호출");
  
  return new ModelAndView("listview2"); //listview2을 보여줌
 }
}


8. 컨트롤러에서 데이터 받음

폴더구조


web.xml
<?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">
  <display-name>MVCEx05</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>
  
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context3.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

servlet-context3.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
    xmlns="http://www.springframework.org/schema/mvc"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <!-- 자동으로 컨트롤러 찾아줌 -->
    <context:component-scan base-package="spring" />
    
    <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

</beans:beans>

ConfigController3.java
package spring;

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

@Controller
public class ConfigController3 {
 @RequestMapping(value="/list1.do", method=RequestMethod.GET) //list1.do요청시 get방식일 떄 작동
 public ModelAndView handleRequest11(@RequestParam("data") String data){ //데이터 받을 때
  System.out.println("handleRequest11() 호출 :"+data);
  
  return new ModelAndView("listview1"); //listview1을 보여줌
 }
 @RequestMapping(value="/list1.do", method=RequestMethod.POST) //list1.do요청시 post방식일 떄
 public ModelAndView handleRequest12(@RequestParam("data") String data){
  System.out.println("handleRequest12() 호출 :"+data);
  
  return new ModelAndView("listview1");
 }

}

listview1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/views/listview.jsp -->
/WEB-INF/views/listview1.jsp <br />

</body>
</html>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="list1.do" method="get">
    데이터 <input type="text" name="data">
    <input type="submit" value="get 전송">
</form>
<form action="list1.do" method="post">
    데이터 <input type="text" name="data">
    <input type="submit" value="post 전송">
</form>

</body>
</html>


9. 스프링 탬플릿 사용 프로젝트 만들기
Spring Legacy Project생성


pom.xml 버전업


폴더구조

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- 공유자원 스프링 컨테이너 정의 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- 공유자원 스프링 컨테이너 생성 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 서블릿 -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

</web-app>

root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
        
</beans>

servlet-context.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: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 />

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

    <!-- 컨트롤러에서 보내는 페이지 명에 앞,뒤로 경로 달아줌 -->
    <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>
    
    <!-- 어노테이션 컨트롤러 자동으로 찾음 -->
    <context:component-scan base-package="com.exam.spring" />
    
    
    
</beans:beans>

HomeController.java
package com.exam.spring;

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 = "home.do", 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";
 }
 
}

home.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  
</h1>

<P>  The time on the server is ${serverTime}. </P>
</body>
</html>

주소값 앞에 spring붙여줘야함 (프로젝트 생성시 패키지명끝에 spring적은것)

2016년 9월 30일 금요일

04day Spring

1.어노테이션으로 aspectj라이브러리를 이용해서 aop를 만들기
폴더구성

pom.xml 에서 라이브러리 추가
<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>

Action.java
package spring;

public interface Action {
 public abstract void sayHello1();
 public abstract void sayHello2();
}

WriteAction.java
package spring;

public class WriteAction implements Action {
 private String name;
 
 public void setName(String name){
  this.name = name;
 }
 
 @Override
 public void sayHello1() {
  // TODO Auto-generated method stub
  System.out.println("sayHello1 시작");
  System.out.println("Hello1 " + name);
  System.out.println("sayHello1 끝");
 }
 
 @Override
 public void sayHello2() {
  // TODO Auto-generated method stub
  System.out.println("sayHello2 시작");
  System.out.println("Hello2 " + name);
  System.out.println("sayHello2 끝");
 }

}

LoginAdvice.java
package spring;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.util.StopWatch;

//xml에서 기술 했던부분을 java클래스에서 기술함
@Aspect
public class LoginAdvice {
 @Pointcut("execution(* sayHello1())")
 private void myTarget(){};
 
 @Around("myTarget()")
 public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
  //전처리
  String methodName = joinPoint.getKind();
  StopWatch stopWatch = new StopWatch();
  stopWatch.start(methodName);
  System.out.println("[LOG] Method : "+methodName);
  
  Object rtnObj =joinPoint.proceed();
  
  //후처리
  stopWatch.stop();
  System.out.println("[LOG] Method : "+ methodName);
  System.out.println("[LOG] 시간 : "+ stopWatch.getTotalTimeSeconds());
  
  return rtnObj;
 }
}

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

    <bean id="action" class="spring.WriteAction">
        <property name="name">
            <value>홍길동</value>
        </property>
    </bean>
    <bean id="loginAdvice" class="spring.LoginAdvice" />
    <aop:aspectj-autoproxy />
    
</beans>

ApplicationMain.java
package spring;

import org.springframework.context.support.GenericXmlApplicationContext;

import spring.Action;

public class ApplicationMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:spring/context.xml");
  
  Action action = (Action)ctx.getBean("action"); //proxy 방식이 아니라서 여기서 코드 수정 안함
  action.sayHello1();
  action.sayHello2();
  
  ctx.close();
 }

}




LoginAdvice.java 사전처리만 추가
package spring;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.util.StopWatch;

//xml에서 기술 했던부분을 java클래스에서 기술함
@Aspect
public class LoginAdvice {
 @Pointcut("execution(* sayHello1())")
 private void myTarget(){};
 
 @Around("myTarget()")  //around 전후 처리
 public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
  //전처리
  String methodName = joinPoint.getKind();
  StopWatch stopWatch = new StopWatch();
  stopWatch.start(methodName);
  System.out.println("[LOG] Method : "+methodName);
  
  Object rtnObj =joinPoint.proceed();
  
  //후처리
  stopWatch.stop();
  System.out.println("[LOG] Method : "+ methodName);
  System.out.println("[LOG] 시간 : "+ stopWatch.getTotalTimeSeconds());
  
  return rtnObj;
 }
 
 @Before("execution(* sayHello2())")  //before  사전처리만
 public void before(){
  System.out.println("[LOG] 전처리만 메서드 호출");
 }
}

ApplicationMain.java
package spring;

import org.springframework.context.support.GenericXmlApplicationContext;

import spring.Action;

public class ApplicationMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:spring/context.xml");
  
  Action action = (Action)ctx.getBean("action"); //proxy 방식이 아니라서 여기서 코드 수정 안함
  action.sayHello1();
  System.out.println("---------------------");
  action.sayHello2();
  
  ctx.close();
 }

}


2. MVC spring 서블릿프로젝트에 스프링 라이브러리를 복사하는 방법

폴더구성

web.xml
<?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">
  <display-name>MVCEx01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 서블릿 설정 -->
  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/webContext.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

webContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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-4.3.xsd">

    <bean name="/list1.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="listView1.jsp"></property>
    </bean>
</beans>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- index.jsp -->

index.jsp<br />
<a href="list1.do">list1.do</a>

</body>
</html>

listView1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- listView1.jsp -->

listView1.jsp<br />
<a href="javascript:history.back()">뒤로가기</a>

</body>
</html>


3. webContext에 폴더 경로 설정

폴더구성



web.xml
<?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">
  <display-name>MVCEx01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 서블릿 설정 -->
  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/webContext.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

webContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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-4.3.xsd">
    <!-- 가상 주소에 실제 주소를 연결함 -->
    <bean name="/list1.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="listView1.jsp"></property>
    </bean>
    <bean name="/list2.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="listView2.jsp"></property>
    </bean>
    <bean name="/list3.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="./views/listView1.jsp"></property>
    </bean>
    <bean name="/list4.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="/WEB-INF/listView1.jsp"></property>
    </bean>
    <!-- "/board1/list1.do" 가상경로를 만듦 -->
    <bean name="/board1/list1.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="/WEB-INF/listView1.jsp"></property>
    </bean>
</beans>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- index.jsp -->

index.jsp<br />
<a href="list1.do">list1.do</a>
<a href="list2.do">list2.do</a>
<a href="list3.do">list3.do</a>
<a href="list4.do">list4.do</a>

<a href="./board1/list1.do">list1.do</a>

</body>
</html>

listView1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- listView1.jsp -->

listView1.jsp<br />
<a href="javascript:history.back()">뒤로가기</a>

</body>
</html>

listView2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- listView1.jsp -->

listView2.jsp<br />
<a href="javascript:history.back()">뒤로가기</a>

</body>
</html>

views.listView1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- listView1.jsp -->

views.listView1.jsp<br />
<a href="javascript:history.back()">뒤로가기</a>

</body>
</html>

WEB-INF/listView1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- listView1.jsp -->

/WEB-INF/listView1.jsp<br />
<a href="javascript:history.back()">뒤로가기</a>

</body>
</html>


4. 실제주소 입력 단축

폴더구조

webContext2.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <!-- 실제주소 입력 단축 -->
    <bean name="/list1.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="listView1"></property>
    </bean>
    <bean name="/list2.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="listView2"></property>
    </bean>
    <!-- 실제주소 앞뒤 문자열 연결 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/" />
    <property name="suffix" value=".jsp" />
    </bean>
</beans>

web.xml
<?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">
  <display-name>MVCEx01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 서블릿 설정 -->
  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/webContext2.xml</param-value><!-- 사용할 webContext 파일 설정 -->
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- index.jsp -->

index.jsp<br />
<a href="list1.do">list1.do</a>
<a href="list2.do">list2.do</a>


</body>
</html>


5. 모델만들기

폴더구성


listAction1.java 만들때 Controller 상속받아야 함
package spring;

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

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

import com.sun.swing.internal.plaf.metal.resources.metal;

public class listAction1 implements Controller {

 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
  // TODO Auto-generated method stub
  
  System.out.println("ListAction1 : handleRequest() 호출");
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("listView1");
  
  //return new ModelAndView("listView1");
  return modelAndView;
 }

}

listAction2.java
package spring;

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 listAction2 implements Controller {

 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
  // TODO Auto-generated method stub
  
  System.out.println("ListAction2 : handleRequest() 호출");
  return new ModelAndView("redirect:/index.jsp"); //바로 보냄
 }

}

webContext3.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <bean name="/list1.do" class="spring.listAction1" />
    <bean name="/list2.do" class="spring.listAction2" />
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

web.xml 에서 사용할 webContext파일 명 바꿔줌
<?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">
  <display-name>MVCEx01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 서블릿 설정 -->
  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/webContext3.xml</param-value><!-- 사용할 webContext 파일 설정 -->
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- index.jsp -->

index.jsp<br />
<a href="list1.do">list1.do</a>
<a href="list2.do">list2.do</a>


</body>
</html>

/WEB-INF/listView1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/listView1.jsp -->

/WEB-INF/listView1.jsp<br />
<a href="javascript:history.back()">뒤로가기</a>

</body>
</html>

/WEB-INF/listView2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- /WEB-INF/listView2.jsp -->

/WEB-INF/listView2.jsp<br />
<a href="javascript:history.back()">뒤로가기</a>

</body>
</html>


2016년 9월 29일 목요일

03day Spring

1. 어노테이션기법으로 context.xml 빈파일을 대체하는 방법

폴더구조


WriteAction.java
package spring6;

public class WriteAction {
 
 public WriteAction() {
  // 겟빈이 디폴트로 부르는 기본 생성자
  System.out.println("디폴트 생성자 호출");
 }

 public void sayHello(String name){
  System.out.println(name + "님 안녕하세요");
 }

}

Config.java 어노테이션 설정 파일
package spring6;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
 @Bean
 public WriteAction action1(){
  return new WriteAction();
 }
}

ApplicationMain.java
package spring6;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // 어노테이션 기법으로 스프링 빈객체를 만듦
  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
  
  WriteAction action1 =(WriteAction)ctx.getBean("action1");
  action1.sayHello("홍길동");
 }

}


2. 어노테이션 옵션추가


Config.java
package spring6;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
 @Bean
 public WriteAction action1(){
  return new WriteAction();
 }
 
 @Bean(name="action3") //메서드의 이름을 바꿈
 public WriteAction action2(){
  return new WriteAction();
 }
}

ApplicationMain.java
package spring6;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // 어노테이션 기법으로 스프링 빈객체를 만듦
  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
  
  WriteAction action1 =(WriteAction)ctx.getBean("action1");
  action1.sayHello("홍길동");
  
  WriteAction action3 =(WriteAction)ctx.getBean("action3"); //바뀐 메서드이름을 써야함 action2 쓰면 에러남
  action3.sayHello("박문수");
 }

}


3. 오버로딩 생성자 사용


WriteAction.java
package spring6;

public class WriteAction {
 
 public WriteAction() {
  // 겟빈이 디폴트로 부르는 기본 생성자
  System.out.println("디폴트 생성자 호출");
 }
 
 public WriteAction(String name){
  System.out.println("오버로딩 생성자 호출");
 }
 
 public void sayHello(String name){
  System.out.println(name + "님 안녕하세요");
 }

}

Config.java
package spring6;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
 @Bean
 public WriteAction action1(){
  return new WriteAction();
 }
 
 @Bean(name="action3") //메서드의 이름을 바꿈
 public WriteAction action2(){
  return new WriteAction();
 }
 
 @Bean
 public WriteAction action4(){
  return new WriteAction("성춘향"); //오버로딩 생성자 호출
 }
}

ApplicationMain.java
package spring6;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // 어노테이션 기법으로 스프링 빈객체를 만듦
  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);

 }

}


4. AOP 관점 지향 프로그래밍 ---di(의존성 주입)를 이용해서 aop를 만듦

폴더구성


Action.java
package spring1;

public interface Action {
 public abstract void sayHello();
}

WriteAction.java
package spring1;

public class WriteAction implements Action {
 private String name;
 
 public void setName(String name){
  this.name = name;
 }
 
 @Override
 public void sayHello() {
  // TODO Auto-generated method stub
  System.out.println("sayHello 시작");
  System.out.println("Hello " + name);
  System.out.println("sayHello 끝");
 }

}

LoginAdvice.java 인터페이스 MethodInterceptor 상속받음

package spring1;

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

//서블릿의 필터와 같은 역할을 함 ( 전처리와 후처리 담당 )
public class LoginAdvice implements MethodInterceptor {

 @Override
 public Object invoke(MethodInvocation arg0) throws Throwable {
  //전처리 구간
  System.out.println("전처리 구간");
  Object rtnObj = arg0.proceed();
  
  //후처리 구간
  
  System.out.println("후처리 구간");
  return rtnObj;
 }

}

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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-4.1.xsd">
    
    <!-- 전후처리 함수가있는 클래스 -->
    <bean id="loginAdvice" class="spring1.LoginAdvice" />
    <!-- 전후처리 빈 -->
    <bean id="advice" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <!-- 공통 관심사를 구현하는 관점의 메서드를 advice라고 하며 각 어드바이스는 해당 어드바이스가 적용될 메서드를 지정한 pointcut과 연결됨 -->
        <property name="advice" ref="loginAdvice" /><!-- 전후처리 클래스를 받음 -->
        <property name="pointcut"><!-- 전후처리를 어느 메서드에 적용할 것인지 찾음 -->
            <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
                <property name="pattern" value=".*sayHello.*" /><!-- 정규표현식 sayHello 메서드를 찾음 -->
            </bean>
        </property>
    </bean>
    
    <!-- 그냥 빈 -->
    <bean id="action" class="spring1.WriteAction">
        <property name="name">
            <value>홍길동</value>
        </property>
    </bean>
    
    <!-- 전처리 후처리 빈 + 그냥 빈 -->
    <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="action" /><!-- 그냥 빈을 받음 -->
        <property name="interceptorNames">
            <list>
                <value>advice</value><!-- 전처리 후처리 빈을 받음 -->
            </list>
        </property>
    </bean>
    
</beans>

ApplicationMain.java
package spring1;

import org.springframework.context.support.GenericXmlApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:spring1/context.xml");
  
  //Action action = (Action)ctx.getBean("action"); //그냥 호출
  Action action = (Action)ctx.getBean("proxy"); //전처리 후처리 있는 빈 호출
  action.sayHello();
  
  ctx.close();
 }

}


5. 전후처리를 메소드 명에따라서 선별적으로 적용함


Action.java
package spring1;

public interface Action {
 public abstract void sayHello1();
 public abstract void sayHello2();
}

WriteAction.java
package spring1;

public class WriteAction implements Action {
 private String name;
 
 public void setName(String name){
  this.name = name;
 }
 
 @Override
 public void sayHello1() {
  // TODO Auto-generated method stub
  System.out.println("sayHello1 시작");
  System.out.println("Hello1 " + name);
  System.out.println("sayHello1 끝");
 }
 
 @Override
 public void sayHello2() {
  // TODO Auto-generated method stub
  System.out.println("sayHello2 시작");
  System.out.println("Hello2 " + name);
  System.out.println("sayHello2 끝");
 }

}

LoginAdvice.java
package spring1;

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

//서블릿의 필터와 같은 역할을 함 ( 전처리와 후처리 담당 )
public class LoginAdvice implements MethodInterceptor {

 @Override
 public Object invoke(MethodInvocation arg0) throws Throwable {
  //전처리 구간
  System.out.println("전처리 구간");
  Object rtnObj = arg0.proceed();
  
  //후처리 구간
  
  System.out.println("후처리 구간");
  return rtnObj;
 }

}

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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-4.1.xsd">
    
    <!-- 전후처리 함수가있는 클래스 -->
    <bean id="loginAdvice" class="spring1.LoginAdvice" />
    <!-- 전후처리 빈 -->
    <bean id="advice" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="advice" ref="loginAdvice" />
        <property name="pointcut">
            <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
                <property name="pattern" value=".*sayHello1.*" /><!-- 정규표현식 sayHello1 메서드를 찾음 -->
            </bean>
        </property>
    </bean>
    
    <!-- 그냥 빈 -->
    <bean id="action" class="spring1.WriteAction">
        <property name="name">
            <value>홍길동</value>
        </property>
    </bean>
    
    <!-- 전처리 후처리 빈 + 그냥 빈 -->
    <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="action" />
        <property name="interceptorNames">
            <list>
                <value>advice</value>
            </list>
        </property>
    </bean>
    
</beans>

ApplicationMain.java
package spring1;

import org.springframework.context.support.GenericXmlApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:spring1/context.xml");
  
  //Action action = (Action)ctx.getBean("action"); //그냥 호출
  Action action = (Action)ctx.getBean("proxy"); //전처리 후처리 있는 빈 호출
  action.sayHello1();
  System.out.println();
  
  action.sayHello2();
  
  ctx.close();
 }

}


6.전후처리에 메소드가동 시간을 측정하는 처리

폴더구성


Action.java
package spring1;

public interface Action {
 public abstract void sayHello1();
 public abstract void sayHello2();
}

WriteAction.java
package spring1;

public class WriteAction implements Action {
 private String name;
 
 public void setName(String name){
  this.name = name;
 }
 
 @Override
 public void sayHello1() {
  // TODO Auto-generated method stub
  System.out.println("sayHello1 시작");
  System.out.println("Hello1 " + name);
  System.out.println("sayHello1 끝");
 }
 
 @Override
 public void sayHello2() {
  // TODO Auto-generated method stub
  System.out.println("sayHello2 시작");
  System.out.println("Hello2 " + name);
  System.out.println("sayHello2 끝");
 }

}

LoginAdvice.java
package spring1;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StopWatch;

//서블릿의 필터와 같은 역할을 함 ( 전처리와 후처리 담당 )
public class LoginAdvice implements MethodInterceptor {

 @Override
 public Object invoke(MethodInvocation arg0) throws Throwable {
  //전처리 구간에서 함수적으로 처리할 수있음
  System.out.println("-----------------전처리 구간");
  
  String methodeName = arg0.getMethod().getName();
  StopWatch stopWatch = new StopWatch();
  stopWatch.start(methodeName);
  
  System.out.println("[LOG] 1차 advice 호출 시작");
  System.out.println("[LOG] 호출 Method명  : " + methodeName);
  System.out.println("-------------------------");
  Object rtnObj = arg0.proceed(); //null로 바꾸면 전후처리 안에 아무것도 안 넣음
  
  //후처리 구간
  
  System.out.println("-----------------후처리 구간");
  stopWatch.stop();
  
  System.out.println("[LOG] 처리시간 : " + stopWatch.getTotalTimeSeconds());
  System.out.println("[LOG] 호출 Method명 : " + methodeName+" 종료");
  System.out.println("-------------------------");
  return rtnObj;
 }

}

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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-4.1.xsd">
    
    <!-- 전후처리 함수가있는 클래스 -->
    <bean id="loginAdvice" class="spring1.LoginAdvice" />
    <!-- 전후처리 빈 -->
    <bean id="advice" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <!-- 공통 관심사를 구현하는 관점의 메서드를 advice라고 하며 각 어드바이스는 해당 어드바이스가 적용될 메서드를 지정한 pointcut과 연결됨 -->
        <property name="advice" ref="loginAdvice" /><!-- 전후처리 클래스를 받음 -->
        <property name="pointcut"><!-- 전후처리를 어느 메서드에 적용할 것인지 찾음 -->
            <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
                <property name="pattern" value=".*sayHello1.*" /><!-- 정규표현식 sayHello1 메서드를 찾음 -->
            </bean>
        </property>
    </bean>
    
    <!-- 그냥 빈 -->
    <bean id="action" class="spring1.WriteAction">
        <property name="name">
            <value>홍길동</value>
        </property>
    </bean>
    
    <!-- 전처리 후처리 빈 + 그냥 빈 -->
    <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="action" /><!-- 전후처리할 타겟에 그냥 빈을 받음 -->
        <property name="interceptorNames">
            <list>
                <value>advice</value><!-- 전처리 후처리 빈을 받음 -->
            </list>
        </property>
    </bean>
    
</beans>

ApplicationMain.java
package spring1;

import org.springframework.context.support.GenericXmlApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:spring1/context.xml");
  
  //Action action = (Action)ctx.getBean("action"); //그냥 호출
  Action action = (Action)ctx.getBean("proxy"); //전처리 후처리 있는 빈 호출
  action.sayHello1();
  System.out.println();
  
  action.sayHello2();
  
  ctx.close();
 }

}


7. 여러가지 전후처리 클래스 적용하기

폴더구성


Action.java
package spring1;

public interface Action {
 public abstract void sayHello1();
 public abstract void sayHello2();
}

WriteAction.java
package spring1;

public class WriteAction implements Action {
 private String name;
 
 public void setName(String name){
  this.name = name;
 }
 
 @Override
 public void sayHello1() {
  // TODO Auto-generated method stub
  System.out.println("sayHello1 시작");
  System.out.println("Hello1 " + name);
  System.out.println("sayHello1 끝");
 }
 
 @Override
 public void sayHello2() {
  // TODO Auto-generated method stub
  System.out.println("sayHello2 시작");
  System.out.println("Hello2 " + name);
  System.out.println("sayHello2 끝");
 }

}

LoginAdvice.java
package spring1;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StopWatch;

//서블릿의 필터와 같은 역할을 함 ( 전처리와 후처리 담당 )
public class LoginAdvice implements MethodInterceptor {

 @Override
 public Object invoke(MethodInvocation arg0) throws Throwable {
  //전처리 구간에서 함수적으로 처리할 수있음
  System.out.println("전처리 구간1");

  Object rtnObj = arg0.proceed(); //null로 바꾸면 전후처리 안에 아무것도 안 넣음
  
  //후처리 구간
  
  System.out.println("후처리 구간1");

  return rtnObj;
 }

}

LoginAdvice2.java
package spring1;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StopWatch;

//서블릿의 필터와 같은 역할을 함 ( 전처리와 후처리 담당 )
public class LoginAdvice2 implements MethodInterceptor {

 @Override
 public Object invoke(MethodInvocation arg0) throws Throwable {
  System.out.println("전처리 구간2");

  Object rtnObj = arg0.proceed();
  
  //후처리 구간
  
  System.out.println("후처리 구간2");

  return rtnObj;
 }

}

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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-4.1.xsd">
    
    <!-- 전후처리 함수가있는 클래스 -->
    <bean id="loginAdvice" class="spring1.LoginAdvice" />
    <!-- 전후처리2 함수가있는 클래스 -->
    <bean id="loginAdvice2" class="spring1.LoginAdvice2" />
    <!-- 전후처리 빈 -->
    <bean id="advice" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <!-- 공통 관심사를 구현하는 관점의 메서드를 advice라고 하며 각 어드바이스는 해당 어드바이스가 적용될 메서드를 지정한 pointcut과 연결됨 -->
        <property name="advice" ref="loginAdvice" /><!-- 전후처리 클래스를 받음 -->
        <property name="pointcut"><!-- 전후처리를 어느 메서드에 적용할 것인지 찾음 -->
            <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
                <property name="pattern" value=".*sayHello1.*" /><!-- 정규표현식 sayHello1 메서드를 찾음 -->
            </bean>
        </property>
    </bean>
    <!-- 전후처리2 빈 -->
    <bean id="advice2" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <!-- 공통 관심사를 구현하는 관점의 메서드를 advice라고 하며 각 어드바이스는 해당 어드바이스가 적용될 메서드를 지정한 pointcut과 연결됨 -->
        <property name="advice" ref="loginAdvice2" /><!-- 전후처리 클래스를 받음 -->
        <property name="pointcut"><!-- 전후처리를 어느 메서드에 적용할 것인지 찾음 -->
            <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
                <property name="pattern" value=".*sayHello1.*" /><!-- 정규표현식 sayHello1 메서드를 찾음 -->
            </bean>
        </property>
    </bean>
    
    <!-- 그냥 빈 -->
    <bean id="action" class="spring1.WriteAction">
        <property name="name">
            <value>홍길동</value>
        </property>
    </bean>
    
    <!-- 전처리 후처리 빈 + 그냥 빈 -->
    <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="action" /><!-- 전후처리할 타겟에 그냥 빈을 받음 -->
        <property name="interceptorNames">
            <list> <!--처리 순서가 앞에것 먼저됨 -->
                <value>advice</value><!-- 전처리 후처리 빈을 받음 -->
                <value>advice2</value><!-- 전처리 후처리 빈을 받음 -->
            </list>
        </property>
    </bean>
    
</beans>

ApplicationMain.java
package spring1;

import org.springframework.context.support.GenericXmlApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:spring1/context.xml");
  
  //Action action = (Action)ctx.getBean("action"); //그냥 호출
  Action action = (Action)ctx.getBean("proxy"); //전처리 후처리 있는 빈 호출
  action.sayHello1();
  System.out.println();
  
  action.sayHello2();
  
  ctx.close();
 }

}


8. aspectj라이브러리를 이용해서 aop를 만듦

폴더구성


pom.xml에 라이브러리 추가
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.samples</groupId>
  <artifactId>AOPEx02</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>

        <!-- Generic properties -->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- Spring -->
        <spring-framework.version>4.2.3.RELEASE</spring-framework.version>

        <!-- Hibernate / JPA -->
        <hibernate.version>4.2.1.Final</hibernate.version>

        <!-- Logging -->
        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>

        <!-- Test -->
        <junit.version>4.11</junit.version>

    </properties>
    
    <dependencies>
        <!-- Spring and Transactions -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        
        <!-- Test Artifacts -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-framework.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- 라이브러리 추가 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.11</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
    </dependencies>    
</project>


Action.java
package spring1;

public interface Action {
 public abstract void sayHello1();
 public abstract void sayHello2();
}

WriteAction.java
package spring1;

public class WriteAction implements Action {
 private String name;
 
 public void setName(String name){
  this.name = name;
 }
 
 @Override
 public void sayHello1() {
  // TODO Auto-generated method stub
  System.out.println("sayHello1 시작");
  System.out.println("Hello1 " + name);
  System.out.println("sayHello1 끝");
 }
 
 @Override
 public void sayHello2() {
  // TODO Auto-generated method stub
  System.out.println("sayHello2 시작");
  System.out.println("Hello2 " + name);
  System.out.println("sayHello2 끝");
 }

}

LoginAdvice.java
package spring1;

import org.aspectj.lang.ProceedingJoinPoint;

public class LoginAdvice {
 public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
  System.out.println("전처리 구간");
  Object rtnObj = joinPoint.proceed();
  
  System.out.println("후처리 구간");
  return rtnObj;
 }
}

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

    <bean id="action1" class="spring1.WriteAction">
        <property name="name">
            <value>홍길동</value>
        </property>
    </bean>
    
    <bean id="loginAdvice" class="spring1.LoginAdvice"></bean>
    
    <!-- 전처리 하고 싶으면 적고, 안하고 싶으면 삭제하면 됨 -->
    <aop:config>
        <aop:aspect id="logAspect" ref="loginAdvice">
            <aop:around method="logAround" pointcut="execution(* sayHello1())"/>
        </aop:aspect>
    </aop:config>
</beans>

ApplicationMain.java
package spring1;

import org.springframework.context.support.GenericXmlApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:spring1/context.xml");
  
  Action action = (Action)ctx.getBean("action1"); //proxy 방식이 아니라서 여기서 코드 수정 안함
  action.sayHello1();
  
  ctx.close();
 }

}




전처리만 실행하고 싶을 때
LoginAdvice.java
package spring1;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class LoginAdvice {
 public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
  System.out.println("전처리 구간");
  Object rtnObj = joinPoint.proceed();
  
  System.out.println("후처리 구간");
  return rtnObj;
 }
 public void before(JoinPoint joinpoint) throws Throwable {
  String data = joinpoint.getSignature().getName(); //joinpoint로 실행메서드 파악가능
  System.out.println("전처리만 실행 : "+data);
 }
}

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

    <bean id="action1" class="spring1.WriteAction">
        <property name="name">
            <value>홍길동</value>
        </property>
    </bean>
    
    <bean id="loginAdvice" class="spring1.LoginAdvice"></bean>
    
    <!-- 전처리 하고 싶으면 적고, 안하고 싶으면 삭제하면 됨 -->
    <aop:config>
        <aop:aspect id="logAspect" ref="loginAdvice">
            <!-- <aop:around method="logAround" pointcut="execution(* sayHello1())"/> --><!-- 전후처리 모두 -->
            <aop:before method="before" pointcut="execution(* sayHello1())"/><!-- 전처리만 -->
        </aop:aspect>
    </aop:config>
</beans>

ApplicationMain.java
package spring1;

import org.springframework.context.support.GenericXmlApplicationContext;

public class ApplicationMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:spring1/context.xml");
  
  Action action = (Action)ctx.getBean("action1"); //proxy 방식이 아니라서 여기서 코드 수정 안함
  action.sayHello1();
  
  ctx.close();
 }

}