관점 지향 프로그래밍
(관점지향 : 어떤 로직을 기준으로, 핵심적인 관점/부가적인 관점으로 나눠보고, 그 관점을 기준으로 각각 모듈화(어떤 공통된 로직이나 기능을 하나단위로 묶는것)하겠다는 것
AOP 의존 설정
(오류발생시 pom.xml작성)
<!-- cglib -->
<dependency>
<groupId>com.kenai.nbpwr</groupId>
<artifactId>net-sf-cglib</artifactId>
<version>2.1.3-201003011305</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
주요 개념
1. Aspect
: 여러객체에 공통으로 적용되는 기능
2.Advice
: 언제 공통 관심 기능을 핵심로직에 적용할 지 정의.
3.Jointpoint
: Adivce를 적용 가능한 지점(메소드 호출, 필드값 변경 등이 해당)
스프링은 프록시를 이용하여 AOP를 구현하기 때문에 메소드 호출에 대한 JoinPoint만 지원됨.
4.Pointcut
:Join Point의 상세한 스펙을 정의한 것.
5.Weaving (핵심기능을 적용시키는 행위 자체)
:Advice를 핵심 로직 코드에 적용하는 것
공통 기능을 쓰기 위해 Bean 생성
Expression -> com.javalec.ex… -> 패키지안의 적용 범위
<aop:before> : 메소드 실행 전에 advice실행
<aop:after-returning> : 정상적으로 메소드 실행 후에 advice실행
<aop:after-throwing> : 메소드 실행중 exception 발생시 advice실행
<aop:after> : 메소드 실행중 exception 이 발생하여도 advice실행
<aop:around> : 메서드 실행 전/후 및 exception 발생시 advice실행
Student
package com.javalec.spring_9_1;
public class Student {
private String name;
private int age;
private int gradeNum;
private int classNumS;
public void getStudentInfo() {
System.out.println("이름 : "+getName());
System.out.println("나이 : "+getAge());
System.out.println("학년 : "+getGradeNum());
System.out.println("반 : "+getClassNumS());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGradeNum() {
return gradeNum;
}
public void setGradeNum(int gradeNum) {
this.gradeNum = gradeNum;
}
public int getClassNumS() {
return classNumS;
}
public void setClassNumS(int classNumS) {
this.classNumS = classNumS;
}
}
Worker
package com.javalec.spring_9_1;
public class Worker {
private String name;
private int age;
private String job;
public void getWorkerInfo() {
System.out.println("이름 : "+getName());
System.out.println("나이 : "+getAge());
System.out.println("직업 : "+getJob());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
LogAop
package com.javalec.spring_9_1;
import org.aspectj.lang.ProceedingJoinPoint;
public class LogAop {
public Object loggerAop(ProceedingJoinPoint jointPoint) {
String signatureStr = jointPoint.getSignature().toShortString();
System.out.println(signatureStr+"is start");
long st = System.currentTimeMillis();
Object obj = null;
//핵심기능..적용된 기능
try {
obj =jointPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
}finally {
long et = System.currentTimeMillis();
System.out.println(signatureStr+"is end");
System.out.println(signatureStr+"경과시간 : "+(et-st));
}
return obj;
}
}
또는
package com.javalec.spring_9_1;
import org.aspectj.lang.ProceedingJoinPoint;
public class LogAop {
public Object loggerAop(ProceedingJoinPoint jointPoint) throws Throwable {
String signatureStr = jointPoint.getSignature().toShortString();
System.out.println(signatureStr+"is start");
long st = System.currentTimeMillis();
Object obj = null;
// //핵심기능..적용된 기능
try {
obj =jointPoint.proceed();
return obj;
}finally {
long et = System.currentTimeMillis();
System.out.println(signatureStr+"is end");
System.out.println(signatureStr+"경과시간 : "+(et-st));
}
}
}
applicationCTX.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<bean id="logAop" class="com.javalec.spring_9_1.LogAop"></bean>
<aop:config>
<aop:aspect id="logger" ref="logAop">
<aop:pointcut id="publicM" expression="within(com.javalec.spring_9_1.*)"/>
<aop:around method="loggerAop" pointcut-ref="publicM"/>
</aop:aspect>
</aop:config>
<!--bean 객체 생성 -->
<bean id="student" class="com.javalec.spring_9_1.Student">
<property name="name" value="홍길동"></property>
<property name="age" value="10"></property>
<property name="gradeNum" value="3"></property>
<property name="classNumS" value="5"></property>
</bean>
<bean id="worker" class="com.javalec.spring_9_1.Worker">
<property name="name" value="홍길순"></property>
<property name="age" value="35"></property>
<property name="job" value="개발자"></property>
</bean>
</beans>
MainClass
package com.javalec.spring_9_1;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
Student student = ctx.getBean("student",Student.class);
student.getStudentInfo();
Worker worker = ctx.getBean("worker",Worker.class);
worker.getWorkerInfo();
}
}
pom.xml
<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<!-- cglib -->
<dependency>
<groupId>com.kenai.nbpwr</groupId>
<artifactId>net-sf-cglib</artifactId>
<version>2.1.3-201003011305</version>
</dependency>
Professor.java
package com.javalec.spring_ex_9_1;
public class Professor {
private String name;
private String subject;
private int age;
public void getProfessorInfo() {
System.out.println("이름 : "+getName());
System.out.println("과목 : "+getSubject());
System.out.println("나이 : "+getAge());
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
Singer.java
package com.javalec.spring_ex_9_1;
public class Singer {
private String name;
private String song;
private int member;
public void getSingerInfo() {
System.out.println("이름 : "+getName());
System.out.println("노래 : "+getSong());
System.out.println("멤버 : "+getMember());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
public int getMember() {
return member;
}
public void setMember(int member) {
this.member = member;
}
}
LogAop.java
package com.javalec.spring_ex_9_1;
import org.aspectj.lang.ProceedingJoinPoint;
public class LogAop {
public Object loggerAop(ProceedingJoinPoint jointPoint) {
String signatureStr = jointPoint.getSignature().toShortString();
System.out.println("@@@### start ====>"+signatureStr);
Object obj = null;
try {
obj =jointPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
}finally {
System.out.println("@@@### end ====>"+signatureStr);
}
return signatureStr;
}
}
applicationCTX.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<bean id="logAop" class="com.javalec.spring_ex_9_1.LogAop"> </bean>
<aop:config>
<aop:aspect id="logger" ref="logAop">
<aop:pointcut id="publicM" expression="within(com.javalec.spring_ex_9_1.*)"/>
<aop:around method="loggerAop" pointcut-ref="publicM"/>
</aop:aspect>
</aop:config>
<!--bean 객체 생성 -->
<bean id="professor" class="com.javalec.spring_ex_9_1.Professor">
<property name="name" value="김교수"></property>
<property name="age" value="33"></property>
<property name="subject" value="스프링"></property>
</bean>
<bean id="singer" class="com.javalec.spring_ex_9_1.Singer">
<property name="name" value="방탄소년단"></property>
<property name="song" value="다이너마이트"></property>
<property name="member" value="7"></property>
</bean>
</beans>
MainClass.java
package com.javalec.spring_ex_9_1;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
Professor professor = ctx.getBean("professor",Professor.class);
professor.getProfessorInfo();
Singer singer = ctx.getBean("singer",Singer.class);
singer.getSingerInfo();
}
}
*.xml
<aop:config>
<aop:aspect>
<aop:pointcut/>
<aop:around/>
</aop:aspect>
</aop:config>
@Aspect (=<aop:config>)
@Pointcut("within(com.javalec.spring_10_1.*)") (=<aop:pointcut/>)
@Around("pointcutMethod()") (=<aop:around/>)
*.xml
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
Student.java
package com.javalec.spring_10_1;
public class Student {
private String name;
private int age;
private int gradeNum;
private int classNum;
public void getStudentInfo() {
System.out.println("이름 : "+getName());
System.out.println("나이 : "+getAge());
System.out.println("학년 : "+getGradeNum());
System.out.println("반 : "+getClassNum());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGradeNum() {
return gradeNum;
}
public void setGradeNum(int gradeNum) {
this.gradeNum = gradeNum;
}
public int getClassNum() {
return classNum;
}
public void setClassNum(int classNum) {
this.classNum = classNum;
}
}
Worker.java
package com.javalec.spring_10_1;
public class Worker {
private String name;
private int age;
private String job;
public void getWorkerInfo() {
System.out.println("이름 : "+getName());
System.out.println("나이 : "+getAge());
System.out.println("직업 : "+getJob());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
applicationCTX.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="logAop" class="com.javalec.spring_10_1.LogAop"></bean>
<!-- <aop:config>
<aop:aspect id="logger" ref="logAop">
<aop:pointcut expression="within(com.javalec.spring_10_1.*)" id="publicM"/>
<aop:around method="loggerAop" pointcut-ref="publicM"/>
</aop:aspect>
</aop:config> -->
<bean id="student" class="com.javalec.spring_10_1.Student">
<property name="name" value="홍길동"></property>
<property name="age" value="10"></property>
<property name="gradeNum" value="3"></property>
<property name="classNum" value="5"></property>
</bean>
<bean id="worker" class="com.javalec.spring_10_1.Worker">
<property name="name" value="홍길순"></property>
<property name="age" value="35"></property>
<property name="job" value="개발자"></property>
</bean>
</beans>
LogAop.java
package com.javalec.spring_10_1;
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 LogAop {
@Pointcut("within(com.javalec.spring_10_1.*)")//범위 설정
private void pointCutMethod() {}
@Around("pointCutMethod()")
public Object loggerAop(ProceedingJoinPoint jointPoint) throws Throwable {
String signatureStr = jointPoint.getSignature().toShortString();
System.out.println(signatureStr+"is start");
long st = System.currentTimeMillis();
Object obj = null;
// //핵심기능 적용된 기능
// try {
// obj =jointPoint.proceed();
// } catch (Throwable e) {
// e.printStackTrace();
// }finally {
// long et = System.currentTimeMillis();
// System.out.println(signatureStr+"is end");
// System.out.println(signatureStr+"경과시간 : "+(et-st));
// }
try {
obj =jointPoint.proceed();
return obj;
}finally {
long et = System.currentTimeMillis();
System.out.println(signatureStr+"is end");
System.out.println(signatureStr+"경과시간 : "+(et-st));
}
}
}
MainClass.java
package com.javalec.spring_10_1;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
Student student = ctx.getBean("student",Student.class);
student.getStudentInfo();
Worker worker = ctx.getBean("worker",Worker.class);
worker.getWorkerInfo();
}
}
Car.java
package com.javalec.spring_ex_10_1;
public class Car {
private String company;
private String product;
private int capRank;
public void getCarInfo() {
System.out.println("회사 : "+getCompany());
System.out.println("시총 : "+getCapRank());
System.out.println("제품 : "+getProduct());
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public int getCapRank() {
return capRank;
}
public void setCapRank(int capRank) {
this.capRank = capRank;
}
}
Graphic.java
package com.javalec.spring_ex_10_1;
public class Graphic {
private String company;
private int capRank;
public void getGraphicInfo() {
System.out.println("회사 : "+getCompany());
System.out.println("시총 : "+getCapRank());
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getCapRank() {
return capRank;
}
public void setCapRank(int capRank) {
this.capRank = capRank;
}
}
LogAop.java
package com.javalec.spring_ex_10_1;
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 LogAop {
@Pointcut("within(com.javalec.spring_ex_10_1.*)")//범위 설정
private void pointCutMethod() {}
@Around("pointCutMethod()")
public Object loggerAop(ProceedingJoinPoint jointPoint) throws Throwable {
String signatureStr = jointPoint.getSignature().toShortString();
System.out.println("@@@$$$ start ===>"+signatureStr);
Object obj = null;
try {
obj =jointPoint.proceed();
return obj;
}finally {
System.out.println("@@@$$$ end ===>"+signatureStr);
}
}
}
applicationCTX.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="logAop" class="com.javalec.spring_ex_10_1.LogAop"></bean>
<bean id="car" class="com.javalec.spring_ex_10_1.Car">
<property name="company" value="테슬라"></property>
<property name="capRank" value="6"></property>
<property name="product" value="모델S"></property>
</bean>
<bean id="graphic" class="com.javalec.spring_ex_10_1.Graphic">
<property name="company" value="엔비디아"></property>
<property name="capRank" value="7"></property>
</bean>
</beans>
MainClass.java
package com.javalec.spring_ex_10_1;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
Car car = ctx.getBean("car",Car.class);
car.getCarInfo();
Graphic graphic = ctx.getBean("graphic",Graphic.class);
graphic.getGraphicInfo();
}
}
MVC(MODEL-VIEW-CONTROLLER)
: 사용자 인터페이스, 데이터 논리 제어를 구현하는데 사용되는 소프트웨어 디자인 패턴
소프트 웨어의 비즈니스 로직과 화면을 구분
<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>/*</url-pattern>
</filter-mapping>
Model
클래스를 이용하여 데이터 전달클래스에 @RequestMapping 적용
메소드에 @RequestMapping 적용
view.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
view.jsp입니다.---
</body>
</html>
HomeController
package com.javalec.spring_12_2;
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("board/view")
public String view() {
return "board/view";
}
}
HomeController .java
package com.javalec.spring_12_3;
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("board/title")
public String title(Model model) {
model.addAttribute("id",30);
return "board/title";
}
}
title.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
title.jsp입니다.
id : ${id}
</body>
</html>
shopping.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
shopping.jsp입니다.
</body>
</html>
shopping2.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
shopping2.jsp입니다.
</body>
</html>
HomeController
package com.javalec.spring_12_5;
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("shopping")
public String shopping() {
return "shopping";
}
}
MyController
package com.javalec.spring_12_5;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping("shopping2")
public String shopping2() {
return "shopping2";
}
}
HomeController.java
package com.javalec.spring_12_6;
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
@RequestMapping("/board")
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("write")
public String write(Model model) {
model.addAttribute("id", "aaa");
return "board/write";
}
}
write.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
write.jsp입니다.
id : ${id}
</body>
</html>
HomeController .jsp
package com.javalec.spring_12_ex_1;
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("board/content")
public String view() {
return "board/content";
}
}
content.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
content.jsp입니다.<br>
<!-- <img src="spring_ex_12_1/google.png"> -->
<!-- <img src="/spring_ex_12_1/google.png"> -->
<img src="../resources/google.png">
<img src="../resources/googlelogo.png">
</body>
</html>
applicationCTX.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 https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://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.javalec.spring_12_ex_1" />
</beans:beans>
HomeController
package com.javalec.spring_ex_12_1a;
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("car/tesla")
public String view() {
return "car/tesla";
}
}
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 https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://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/" />
<resources mapping="/carResources/**" location="/carResources/" />
<!-- 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.javalec.spring_ex_12_1a" />
</beans:beans>
tesla.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
tesla.jsp 입니다.<br>
1. 모델S <img src="../carResources/modelS.png"><br>
2. 모델X <img src="../carResources/modelX.png"><br>
3. 모델Y <img src="../carResources/modelY.png">
</body>
</html>