본문 바로가기
SPRING

230220_기본

by 경 훈 2023. 2. 20.

스프링 : FrameWork : 작업틀

: 자바프로그램은 spring

DI : 의존적 관계 .. 객체를 외부파일 (.xml)에 가져옴

데이터베이스 : 오라클 -> 마이바티스 이용

                        타일즈 : 

환경설정이 필요해서 .. 필요한 라이브러리를 공급

 

스프링은 의존적주입(DI) => 외부에서 자료를 가져옴

1. XML 파일에서 가져오는 방식

  - 생성자

  - Setter

2. 자바 파일에서 가져오는 방식 ... 클래스와 메소드 구성

 * 클래스는 반드시 @Configuration 으로 어노테이션

 * 메소드는 반드시 @Bean 으로 어노테이션

 

Spring에서 자료 전송 3가지

1. Model

2. Model and View

3. Command

 

package com.ezen.kim;

public class TwosuDTO {
	int one,two;
	public TwosuDTO() {
	}
	public TwosuDTO(int one, int two) {
		super();
		this.one = one;
		this.two = two;
	}
	public int getOne() {
		return one;
	}
	public void setOne(int one) {
		this.one = one;
	}
	public int getTwo() {
		return two;
	}
	public void setTwo(int two) {
		this.two = two;
	}
	public void out() {
		System.out.println(one+"+"+two+"="+(one+two));
	}
}

 

package com.ezen.kim;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class TwosuMain {

	public static void main(String[] args) {
		String path = "classpath:twosu.xml";
		AbstractApplicationContext aac = new GenericXmlApplicationContext(path);
		TwosuDTO ts = aac.getBean("two",TwosuDTO.class);
		ts.out();
	}
}

 

<?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">
<bean id="two" class="com.ezen.kim.TwosuDTO">
	<constructor-arg value="23"></constructor-arg>
	<constructor-arg value="45"></constructor-arg>
</bean>

</beans>

 

<?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">
<bean id="two" class="com.ezen.kim.TwosuDTO">
	<property name="one" value="56"/>
	<property name="two" value="22"/>
</bean>

</beans>

package com.ezen.kim;

public class S2DTO {
	String name;
	int age;
	String phone;
	int kor,eng,mat;
	public S2DTO() {
	}
	public S2DTO(String name, int age, String phone) {
		super();
		this.name = name;
		this.age = age;
		this.phone = phone;
	}
	public int getKor() {
		return kor;
	}
	public void setKor(int kor) {
		this.kor = kor;
	}
	public int getEng() {
		return eng;
	}
	public void setEng(int eng) {
		this.eng = eng;
	}
	public int getMat() {
		return mat;
	}
	public void setMat(int mat) {
		this.mat = mat;
	}
	public void out() {
		System.out.println("이름:"+name);
		System.out.println("나이:"+age);
		System.out.println("전화번호:"+phone);
		System.out.println("국어:"+kor);
		System.out.println("영어:"+eng);
		System.out.println("수학:"+mat);
	}
}

 

package com.ezen.kim;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class S2Main {

	public static void main(String[] args) {
		String path ="classpath:S2.xml";
		AbstractApplicationContext aac = new GenericXmlApplicationContext(path);
		S2DTO s2dto = aac.getBean("s2",S2DTO.class);
		s2dto.out();
	}
}

 

<?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">
<bean id="s2" class="com.ezen.kim.S2DTO">
	<constructor-arg value="홍길동"/>
	<constructor-arg value="25"/>
	<constructor-arg value="010-1234-4567"/>
	<property name="kor" value="90"></property>
	<property name="eng" value="80"></property>
	<property name="mat" value="95"></property>
</bean>

</beans>

package ezen.com.kim5;

public class MyinfoDTO {
	String name;
	int age;
	String phone;
	public MyinfoDTO() {
	}
	public MyinfoDTO(String name, int age, String phone) {
		super();
		this.name = name;
		this.age = age;
		this.phone = phone;
	}
	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 getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public void out() {
		System.out.println("이름:"+name);
		System.out.println("나이:"+age);
		System.out.println("전화번호:"+phone);
	}
}

 

package ezen.com.kim5;

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

@Configuration
public class MyinfoConfig {
	
	@Bean
	public MyinfoDTO koko() {
		MyinfoDTO dto = new MyinfoDTO();
		dto.setName("홍길동");
		dto.setAge(55);
		dto.setPhone("010-1234-4567");
		return dto;
	}
}

 

package ezen.com.kim5;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyinfoMain {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext acac = 
				new AnnotationConfigApplicationContext(MyinfoConfig.class);
		MyinfoDTO dto = acac.getBean("koko",MyinfoDTO.class);
		dto.out();
	}
}

 

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>ezen.com</groupId>
	<artifactId>kim5</artifactId>
	<name>day1_005</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/cglib/cglib -->
		<dependency>
		    <groupId>cglib</groupId>
		    <artifactId>cglib</artifactId>
		    <version>3.2.10</version>
		</dependency>
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="save2" method="post">
		<table border="1" align="center">
			<tr>
				<th>이름</th>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<th>나이</th>
				<td><input type="text" name="age"></td>
			</tr>
			<tr>
				<th>전화번호</th>
				<td><input type="text" name="phone"></td>
			</tr>
			<tr>
				<th>국어</th>
				<td><input type="text" name="kor"></td>
			</tr>
			<tr>
				<th>영어</th>
				<td><input type="text" name="eng"></td>
			</tr>
			<tr>
				<th>수학</th>
				<td><input type="text" name="mat"></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="전송">
					<input type="reset" value="초기화">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table border="1" align="center">
		<tr>
			<th>이름</th><th>나이</th><th>전화번호</th>
			<th>국어</th><th>영어</th><th>수학</th>
			<th>총점</th><th>평균</th>
		</tr>
		<tr>
			<td>${name}</td><td>${age}</td><td>${phone}</td>
			<td>${kor}</td><td>${eng}</td><td>${mat}</td>
			<td>${tot}</td><td>${avg}</td>
		</tr>
	</table>
</body>
</html>

 

package com.ezen.kim;

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

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

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

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping(value="/in") //외부에서 호출받는 곳
	public String ko1() {
		return "input"; //가장 먼저 실행되는 JSP파일
	}
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public String ko2(HttpServletRequest request,Model mo) {
		int a = Integer.parseInt(request.getParameter("one"));
		int b = Integer.parseInt(request.getParameter("two"));
		mo.addAttribute("a", a);
		mo.addAttribute("b", b);
		return "out"; //입력받은 자료들을 out.jsp 파일로 보냄
	}
	
	@RequestMapping(value="/in2")
	public String ko3() {
		return "input2";
	}
	
	@RequestMapping(value="/save2",method = RequestMethod.POST)
	public String ko4(HttpServletRequest request,Model mo) {
		DecimalFormat df = new DecimalFormat("#,##0.0");
		String name = request.getParameter("name");
		int age = Integer.parseInt(request.getParameter("age"));
		String phone = request.getParameter("phone");
		int kor = Integer.parseInt(request.getParameter("kor"));
		int eng = Integer.parseInt(request.getParameter("eng"));
		int mat = Integer.parseInt(request.getParameter("mat"));
		int tot = kor+eng+mat;
		double avg = (double)tot/3;
		mo.addAttribute("name",name);
		mo.addAttribute("age",age);
		mo.addAttribute("phone",phone);
		mo.addAttribute("kor",kor);
		mo.addAttribute("eng",eng);
		mo.addAttribute("mat",mat);
		mo.addAttribute("tot",tot);
		mo.addAttribute("avg",df.format(avg));
		return "out2";
	}
}

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table border="1" align="center">
		<tr>
			<th>이름</th><th>나이</th><th>전화번호</th>
			<th>국어</th><th>영어</th><th>수학</th>
			<th>총점</th><th>평균</th>
		</tr>
		<tr>
			<td>${list.name}</td><td>${list.age}</td><td>${list.phone}</td>
			<td>${list.kor}</td><td>${list.eng}</td><td>${list.mat}</td>
			<td>${list.tot}</td><td>${list.avg}</td>
		</tr>
	</table>
</body>
</html>

 

package com.ezen.kim;

public class ScoreDTO {
	String name;
	int age;
	String phone;
	int kor,eng,mat,tot;
	double avg;
	public ScoreDTO() {
	}
	public ScoreDTO(String name, int age, String phone, int kor, int eng, int mat) {
		super();
		this.name = name;
		this.age = age;
		this.phone = phone;
		this.kor = kor;
		this.eng = eng;
		this.mat = mat;
	}
	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 getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public int getKor() {
		return kor;
	}
	public void setKor(int kor) {
		this.kor = kor;
	}
	public int getEng() {
		return eng;
	}
	public void setEng(int eng) {
		this.eng = eng;
	}
	public int getMat() {
		return mat;
	}
	public void setMat(int mat) {
		this.mat = mat;
	}
	public int getTot() {
		return tot;
	}
	public void setTot(int tot) {
		this.tot = tot;
	}
	public double getAvg() {
		return avg;
	}
	public void setAvg(double avg) {
		this.avg = avg;
	}
}

 

package com.ezen.kim;

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

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

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

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping(value="/in") //외부에서 호출받는 곳
	public String ko1() {
		return "input"; //가장 먼저 실행되는 JSP파일
	}
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public String ko2(HttpServletRequest request,Model mo) {
		int a = Integer.parseInt(request.getParameter("one"));
		int b = Integer.parseInt(request.getParameter("two"));
		mo.addAttribute("a", a);
		mo.addAttribute("b", b);
		return "out"; //입력받은 자료들을 out.jsp 파일로 보냄
	}
	
	@RequestMapping(value="/in2")
	public String ko3() {
		return "input2";
	}
	
	@RequestMapping(value="/save2",method = RequestMethod.POST)
	public String ko4(HttpServletRequest request,Model mo) {
		DecimalFormat df = new DecimalFormat("#,##0.0");
		String name = request.getParameter("name");
		int age = Integer.parseInt(request.getParameter("age"));
		String phone = request.getParameter("phone");
		int kor = Integer.parseInt(request.getParameter("kor"));
		int eng = Integer.parseInt(request.getParameter("eng"));
		int mat = Integer.parseInt(request.getParameter("mat"));
		int tot = kor+eng+mat;
		double avg = (double)tot/3;
		ScoreDTO dto = new ScoreDTO();
		dto.setName(name);
		dto.setAge(age);
		dto.setPhone(phone);
		dto.setKor(kor);
		dto.setEng(eng);
		dto.setMat(mat);
		dto.setTot(tot);
		dto.setAvg(avg);
		mo.addAttribute("list",dto);
		return "out2";
	}
}

 

<!-- 한글깨짐 방지 --> 
    <!-- filter와 filter-mapping을 만들어 준다. -->
    <filter> 
        <!-- filter안에는 filter-name, filter-class, init-param을 추가해 준다.
              filter-name은 원하는대로 지정해도됨 -->
        <filter-name>encodingFilter</filter-name> 
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param> 
            <!-- encoidng값을 UTF-8로 만들어 준다. -->
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

'SPRING' 카테고리의 다른 글

230227_MyBatis  (0) 2023.02.27
230224_MyBatis  (0) 2023.02.24
230223_MyBatis  (0) 2023.02.23
230222_기본  (0) 2023.02.22
230221_기본  (0) 2023.02.21

댓글