본문 바로가기

Java/java 기초

Spring 셋팅 설정

프로젝트 구조 

 

순서

dynamic web project 로 프로젝트 시작
-> 프로젝트에 우클릭 configure -> convert maven project  (기존 자바 EE프로젝트를 maven형태의 프로젝트로 변환)

프로젝트에 우클릭 -> javaEE tools -> generate deploy 클릭(web.xml생성)

 

 

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sample01</groupId>
  <artifactId>sample01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  <!-- maven 사이트에서 spring-webmvc에 필요한 파일을 다운 받아라(복붙하면 받고 있음) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.2.0.RELEASE</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>1.7.25</version>
			<!-- <scope>test</scope> -->
		</dependency>
  </dependencies>
  
</project>

 

WebContent  WEB-INF에 있는 web.xml 값 설정하기
(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" version="3.1">
  <display-name>sample01</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>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
				/WEB-INF/spring/servlet-context.xml
			</param-value>
		</init-param>

		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- 한글 설정 -->
	<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>
</web-app>



WEB-INF에 spring 폴더 생성및  spring 폴더 내부에 
servlet-context.xml 생성   (prefix와 suffix를 정해주면, dispatcher가 알아서 view를 찾을 수 있게 된다 

 

<?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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.3.xsd">

	<!-- Spring MVC annotation(주석문)을 사용하기 위한 설정 -->
	<context:annotation-config/>
	
	<!-- xml 객체 생성 -->
	<!-- ViewResolver 설정(사용자의 view의 위치, 확장자명)-->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property> <!-- 경로 -->
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<!-- 사용자지정 -->
	<!-- java의 공통 패키지 -->
	<context:component-scan base-package="bit.com.a"/>

</beans>






Java Resource폴더 우클릭 -> TestController생성(servlet-context에서 지정한 java의 공통 패키지 이름과 패키지명을 맞춰주면된다 해당 프로젝트에서는 패키지명을 bit.com.a로 지정하였다)

 

 

 

TestController

 

package bit.com.a;

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

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

@Controller
public class TestController {

	@RequestMapping(value = "hello", method = {RequestMethod.GET, RequestMethod.POST})
	public String hello(Model model, Locale locale) {
		System.out.println("TestController hello");
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		
		// 짐싸!
		model.addAttribute("serverTime", formattedDate);
		
		//ModelAndView 로 return 해주지 않아도 된다 String 형식으로 주로 사용
		return "hello";
	}
}

RequestMapping은 WebServlet("/") 와 비슷한 역할을 하며 GET, POST방식으로 지정해서 받을수 있다.

@RequestMapping("hello")를 사용하면 그냥 바로 get방식의 hello로 넘어간다 

 

 

index.jsp

<%@ 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>
<a href="hello">hello</a>
</body>
</html>

a태그를 클릭하면 hello가지정되어 RequestMapping을 타고 간다. 

 

WEB-INF안에 views를 폴더명으로 하는 hello.jsp생성

<%@ 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>
hello
</body>
</html>

 

 

log4j(System.out이 무겁기때문에 대신 값을 나타내주는 라이브러리)

JavaResource에 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="bit.com.a">
		<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>

Logger을 활용한 print출력 

package bit.com.a;

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;

@Controller
public class TestController {

	//가벼움
		private static Logger logger = LoggerFactory.getLogger(TestController.class);
		
	@RequestMapping("hello")
	public String hello(Model model, Locale locale) {
		
//		System.out.println("TestController hello");
		logger.info("TestController hello " + new Date());
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		
		// 짐싸!
		model.addAttribute("serverTime", formattedDate);
		
		//ModelAndView 로 return 해주지 않아도 된다 String 형식으로 주로 사용
		return "hello";
	}
}

출력 결과

'Java > java 기초' 카테고리의 다른 글

Mybatis 시작하기  (0) 2020.02.25
Spring에서 Ajax활용하기  (0) 2020.02.25
JSP, JSTL(el, core), Ajax로 각각 만든 고객 목록 관리 리스트(MVC2)  (0) 2020.01.24
jsp tag  (0) 2020.01.23
Core tag  (0) 2020.01.23