Bean 
xml -> config

Config.xml

package ex09;
//xml에서 설정한 빈을 java로 설정한 컨테이너로 가져오기

import java.util.Date;

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


@Configuration //Config클래스를 스프링 환경설정으로 사용함
@ImportResource("classpath:ex09/appContext.xml") //**xml로 설정한 것을 자바로 가져오는 문장**
public class Config {
	
	@Bean(name="e1")
	public Emp getEmp() {
		return new Emp("James",7799,"Sales");
	}
	
	@Bean
	public ServiceImpl service() {
		ServiceImpl s=new ServiceImpl();
		s.setEmp(this.getEmp());
		return s;
	}
	
	@Bean
	public Date today() {
		return new Date();
	}
}

appContext.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">
	
	<!-- xml에서 설정한 객체를 java Config서 가져오기 -->
	
	<!-- Martin 7123 Sales 값을 생성자 injection으로 주입하세요-->
	<!-- 기본생성자가 없을때 -->
	<bean id="exmlObj" class="ex09.Emp">
		<constructor-arg value="Martin" type="String"/>
		<constructor-arg value="7123" type="int"/>
		<constructor-arg value="Sales"/>
	</bean>

</beans>

SpringAppTest.java

package ex09;

import java.util.Date;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringAppTest {

	public static void main(String[] args) {
		// 1. e1을 룩업하여 해당 객체의 toString()호출해보기
		ApplicationContext ctx=new AnnotationConfigApplicationContext(Config.class);
		Emp e1=ctx.getBean("e1",Emp.class);
		System.out.println(e1.toString());
		
		// 2. ServiceImpl빈을 룩업하여 test()메소드 호출해보기
		ServiceImpl e2=ctx.getBean("service",ServiceImpl.class);
		e2.test1();
		
		
		// 3. Date객체 룩업하여 toString()호출해보기
		System.out.println(ctx.getBean("today",Date.class).toString());
		
		// 4. exmlObj를 룩업하여 출력하기
		Emp e3=ctx.getBean("exmlObj",Emp.class);
		System.out.println(e3);

	}

}

config -> 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: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">

	<!-- java Config에서 설정한 객체를 xml에 가져오기.
		beans 태그에 xmlns:context="http://www.springframework.org/schema/context" 속성 추가
		
		xsi:schemaLocation 에
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
		추가해야함
		
		처음에 만들때 혹시라도 빼먹었으면 밑에 Namespaces들어가서 추가할 수 있다.
	 -->
	 <context:annotation-config/>
	<!-- context:annotation-config 는 자바로 설정한 빈들의 어노테이션을 활성화 시켜준다. -->
	<bean id="config" class="ex10.Config"/>
	<!-- Config빈을 등록한다. -->
	
	<bean id="exmlObj" class="ex10.Emp">
		<constructor-arg value="Tom" type="String"/>
		<constructor-arg value="7123" type="int"/>
		<constructor-arg value="Sales"/>
	</bean>
	
</beans>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
NodeJS
oracleDB

oracledb모듈 설치  =>  npm i oracledb --s

form에서 제출 post방식 => user/member.js에 joinEnd로 연결 (req.body 에 값 담김) => user객체만들어 전달 =>
userdb에 값을 Insert실행 => dbconfig 정보로 접속 후 Connection및 execute => message로 render =>
결과창 보여주고 이동 

dbconfig.js

module.exports={
    connectString:'localhost:1521/XE',
    user:'myshop',
    password:'tiger'
}//db연결정보만 내보내는 파일

//생성할 것들
/*
create table node_member(
num number(8) primary key,
name varchar2(30) not null,
userid varchar2(20) unique not null,
pwd varchar2(20) not null,
email varchar2(200),
indate date default sysdate
);

create sequence node_member_seq nocache;
*/

userdb.js

//oracledb모듈 설치
//npm i oracledb --s
//dao역할

var db=require('oracledb')
var dbconfig=require('./dbconfig.js') //db연동하는 문장
db.autoCommit=true;//자동 커밋

exports.userInsert=(user,req,res)=>{ //member.js의 joinEnd에서 넘겨받은 값으로 sql문 처리
    //console.dir(user);
    //db연결
    db.getConnection(dbconfig,function(err,con){ //비동기방식 : (function)값을 받을게 있으면 콜백함수에서 매개변수(con)       (db연결하는메소드)
        if(err) throw err;
        var sql="insert into node_member values(";
            sql+=" node_member_seq.nextval,:name,:userid,:pwd,:email,sysdate)"; //:mame = user가 가져온 key값
            con.execute(sql,user,function(err,result){ //sql문 실행시키는거
                if(err) throw err;
                con.close(function(err){
                    //실행 결과 받아와 처리하기
                    if(err) throw err;
                    console.log(JSON.stringify(result));
                    var n=parseInt(result.rowsAffected); //result의 rowsAffected(영향받은 레코드 수)
                    var data={};
                    if(n>0){
                        data.msg='회원가입 성공';
                        data.loc='/'
                    }else{
                        data.msg='회원가입 실패';
                        data.loc='javascript:history.back()';
                    }
                    res.render('message',data); //view로 보내는 문장
                    //views/message.ejs

                })//con.close();
            })//con.execute();
    })//db.getConnect()
}//userInsert()

//DML (insert, update, delete)문장 => result의 rowsAffected(영향받은 레코드 수)
//DQL (select) 문장 => result의 rows (2차원 배열)
exports.listUser=function(req,res){
    db.getConnection(dbconfig,function(err,con){
        if(err) throw err;
        var sql="select num,name,userid,pwd,email,to_char(indate,'yyyy-mm-dd') indate from node_member order by num desc";
        con.execute(sql,function(err,result){
            if(err) throw err;
            con.close(function(err){
                if(err) throw err;
                //console.dir(result);
                var data={
                    userData:result.rows, //2차원 배열
                    total:result.rows.length //회원수
                }
                //res.send("<h1>회원 목록 가져오는 중....</h1>")
                res.render('user/list',data);
            })
        })
    })
}

form.ejs

<%- include ('../top') %>
<%- include ('../nav') %>
<div class="container" style="height:500px">
    <h1 class="text-center mt-5"><%=title%></h1>
    <div class="col-md-10 offset-md-1 p-5">
    <form name="mf" id="mf" method="post" action="join" onsubmit="return check()">
    <table class="table">
        <tr>
            <th width="20%">이름</th>
            <td width="80%">
                <input type="text" name="name" id="name" class="form-control" placeholder="Name">
            </td>
        </tr>
        <tr>
            <th width="20%">아이디</th>
            <td width="80%">
                <input type="text" name="userid" id="userid" class="form-control" placeholder="User Id">
            </td>
        </tr>
        <tr>
            <th width="20%">비밀번호</th>
            <td width="80%">
                <input type="password" name="pwd" id="pwd" class="form-control" placeholder="PassWord">
            </td>
        </tr>
        <tr>
            <th width="20%">이메일</th>
            <td width="80%">
                <input type="text" name="email" id="email" class="form-control" placeholder="Email">
            </td>
        </tr>
        <tr>
            <td colspan="2" class="text-center">
                <button type="submit" class="btn btn-outline-success">회원가입</button>
                <button type="reset" class="btn btn-outline-warning">다시쓰기</button>
            </td>
        </tr>
    </table>
</form>
</div>
</div>
<script>
    function check(){
        if(!mf.name.value){
            alert('이름을 입력하세요');
            mf.name.focus();
            return false;
        }
        if(!mf.userid.value){
            alert('아이디를 입력하세요');
            mf.userid.focus();
            return false;
        }
        if(!mf.pwd.value){
            alert('비밀번호를 입력하세요');
            mf.pwd.focus();
            return false;
        }
        return true;

    }
</script>

<%- include ('../foot') %>

list.ejs

<%- include ('../top') %>
<%- include ('../nav') %>
<div class="container" style="height:500px">
    <h1 class="text-center mt-5"><%=title%></h1>
    <div class="col-md-10 offset-md-1 p-5">
    <form name="mf" id="mf" method="post" action="join" onsubmit="return check()">
    <table class="table">
        <tr>
            <th width="20%">이름</th>
            <td width="80%">
                <input type="text" name="name" id="name" class="form-control" placeholder="Name">
            </td>
        </tr>
        <tr>
            <th width="20%">아이디</th>
            <td width="80%">
                <input type="text" name="userid" id="userid" class="form-control" placeholder="User Id">
            </td>
        </tr>
        <tr>
            <th width="20%">비밀번호</th>
            <td width="80%">
                <input type="password" name="pwd" id="pwd" class="form-control" placeholder="PassWord">
            </td>
        </tr>
        <tr>
            <th width="20%">이메일</th>
            <td width="80%">
                <input type="text" name="email" id="email" class="form-control" placeholder="Email">
            </td>
        </tr>
        <tr>
            <td colspan="2" class="text-center">
                <button type="submit" class="btn btn-outline-success">회원가입</button>
                <button type="reset" class="btn btn-outline-warning">다시쓰기</button>
            </td>
        </tr>
    </table>
</form>
</div>
</div>
<script>
    function check(){
        if(!mf.name.value){
            alert('이름을 입력하세요');
            mf.name.focus();
            return false;
        }
        if(!mf.userid.value){
            alert('아이디를 입력하세요');
            mf.userid.focus();
            return false;
        }
        if(!mf.pwd.value){
            alert('비밀번호를 입력하세요');
            mf.pwd.focus();
            return false;
        }
        return true;

    }
</script>

<%- include ('../foot') %>

user/member.js

var userdb = require('../../model/userdb.js')

exports.join=function(req,res){
    //views/user/join.ejs
    var data={title:"Member Join"};
    res.render('user/join',data); 
    //res.send("<h1>회원가입</h1>");
}
exports.joinEnd=function(req,res){
    //post => req.body
    //get => req.query
    var name=req.body.name;
    var userid=req.body.userid;
    var pwd=req.body.pwd;
    var email=req.body.email;

    var user={ //사용자가 입력한 값 (key : value)
        name:name,
        userid:userid,
        pwd:pwd,
        email:email
    };
    userdb.userInsert(user,req,res);
    //res.send("<h2>회원 가입 처리 중...</h2>");
    //res.send("<h2>"+JSON.stringify(user)+"</h2>"); 
    // JSON.stringify = Object를 문자열화

}
exports.list=function(req,res){
	userdb.listUser(req,res);
}

app.js

var http=require('http'),
express=require('express'),
path=require('path'),
fs=require('fs'),
static=require('serve-static'),
bodyParser=require('body-parser');

//사용자 정의 모듈 불러오기/////////////////////////
//var routes =require('./routes/index.js'); 정석
var routes =require('./routes'); //생략해도됌
var user=require('./routes/user/member.js')
//////////////////////////////////////////////

var app=express();
app.set('port',3333);
app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');

app.use('/',static(path.join(__dirname,'public')));
//post방식일 때 설정
app.use(bodyParser.urlencoded({extended:true}))

//라우팅 처리////////////////////////////////////
app.get('/', routes.index)
app.get('/join',user.join);
app.post('/join',user.joinEnd); // /join << 주소위치
app.get('/users',user.list);

////////////////////////////////////////////////

http.createServer(app).listen(app.get('port'),function(){
    console.log('http://localhost:'+app.get('port'));
})

//command.propertice?? 같은 느낌이다.

message.ejs

<script>
    alert('<%=msg%>');
    location.href='<%=loc%>';
</script>

+ Recent posts