스프링

To do list
* web.xml 에 applicationContext.xml 로딩하도록 설정
* UserController 와 UserDao 의존관계 설정

 

 

pom.xml

		<!-- mysql db연결 관련 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>
		<dependency>
			<groupId>org.bgee.log4jdbc-log4j2</groupId>
			<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
			<version>1.16</version>
		</dependency>

 

 

applicationContext.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="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-4.3.xsd">
	
	<context:annotation-config />
	
	<!-- mySQL DB연결위한 작업 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy">
		</property>
		<property name="url" value="jdbc:log4jdbc:mysql://127.0.0.1:3306/team4"></property>
		<property name="username" value="wjheo"></property>
		<property name="password" value="1111"></property>
	</bean>
	
	
	<bean id="userDao" class="com.java.dao.users.UserDao">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
</beans>

 

logback.xml

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

	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-4level [%logger.%method:%line]-%msg%n</pattern>
		</layout>
	</appender>



	<appender name="LOGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>/WEB-INF/logback.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>logback.%d{yyyy-MM-dd}.log</fileNamePattern>
			<!-- 30일 지난 파일은 삭제한다. -->
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-4level [%logger.%method:%line]- %msg %n</pattern>
		</encoder>
	</appender>



	<!-- 로그의 레벨( 지정된 로그 레벨 이상만 수집 ) : DEBUG < INFO < WARN < ERROR < FATAL -->
	<logger name="com.java" level="DEBUG" />
	<logger name="org.springframework" level="INFO" />
	<logger name="org.springframework.web.bind.annotation.support.HandlerMethodInvoker" level="INFO" />
	<logger name="org.springframework.web.servlet.DispatcherServlet" level="INFO" />

    
    <root level="INFO">
        <appender-ref ref="CONSOLE" />
    </root>

</configuration>


 

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<!-- Appenders -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-5p: %c - %m%n" />
		</layout>
	</appender>
	
	<!-- Application Loggers -->
	<logger name="com.java.web">
		<level value="info" />
	</logger>
	
	<!-- 3rdparty Loggers -->
	<logger name="org.springframework.core">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.beans">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.context">
		<level value="info" />
	</logger>

	<logger name="org.springframework.web">
		<level value="info" />
	</logger>

	<!-- Root Logger -->
	<root>
		<priority value="warn" />
		<appender-ref ref="console" />
	</root>
	
</log4j:configuration>

 

log4jdbc.log4j2.properties

log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator



 

 

SQL

DROP TABLE IF EXISTS USERS;

CREATE TABLE USERS (
	userId  varchar(12) NOT NULL,
	password varchar(12) NOT NULL,
	name varchar(20) NOT null,
	email varchar(50),
	primary key (userId)
);

INSERT INTO USERS VALUES('javajigi', 'password', '자바지기', 'javajigi@slipp.net');

 

 

 

class User

package com.java.dto;

public class User {

	private String userId; 
	private String password;
    private	String name;
    private String email;
    
    
	public User() {

	}
	public User(String userId, String password, String name, String email) {
		super();
		this.userId = userId;
		this.password = password;
		this.name = name;
		this.email = email;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	@Override
	public String toString() {
		return "User [userId=" + userId + ", password=" + password + ", name=" + name + ", email=" + email + "]";
	}	
    
    

}

 

package com.java.dao.users;


import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import com.java.dto.User;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.*;



public class UserDao extends JdbcDaoSupport{
	
	private static final Logger logger =LoggerFactory.getLogger(UserDao.class);
	
	@PostConstruct
	public void initialize(){
		ResourceDatabasePopulator populator=new ResourceDatabasePopulator();
		//populator.addScript(new ClassPathResource("slipp.sql"));
		//DatabasePopulatorUtils.execute(populator, getDataSource());
		logger.info("database initialized success!");
	}


	public User findById(String userId) {
		String sql =" select * from USERS where userId =?";
		
		RowMapper<User> rowMapper =new RowMapper<User>() {
			@Override
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				
				return new User(
						rs.getString("userId"),
						rs.getString("password"),
						rs.getString("name"),
						rs.getString("email")
						);
			}
		};
		return getJdbcTemplate().queryForObject(sql, rowMapper, userId);
	}

	
	public void create(User user) {
		String sql =" insert into USERS values(?, ? , ? , ?) ";
		getJdbcTemplate().update(sql, user.getUserId(), user.getPassword(), user.getName(), user.getEmail());
	}
	
    
    
}




 

 

class UserController

 

package com.java.web;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.java.dao.users.UserDao;
import com.java.dto.User;

@Controller
@RequestMapping("/users")
public class UserController {
	
	private static final Logger logger=LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserDao userDao;
	
	@RequestMapping("/form")
	public String form(){
		logger.debug("User : {} " , "test");
		return "users/form";
	}
	
	@RequestMapping(value="", method=RequestMethod.POST)
	public String create(User user){
		logger.debug("User : {} " , user);
		userDao.create(user);
		logger.debug("Database : {} " , userDao.findById(user.getUserId()));
		return "users/form";
	}
	
	
	
	
}




 

 

 

 

 

 

 

 

spring

 

about author

PHRASE

Level 60  머나먼나라

사람의 성(性)은 천리(天理)와 같은 것이다. 천리에는 거짓이나 잘못된 점이 없다. 따라서 사람의 성(性)은 결코 도리(道理)에 어긋나서는 안 되는 것이다. 성(性)은 선(善)이다. 정이천(程伊川)이 한 말. -근사록

댓글 ( 4)

댓글 남기기

작성