'Web'에 해당되는 글 10건

  1. 2018.12.26 [Spring Boot] Spring boot + MariaDB + Mybatis 연동 3
  2. 2018.11.28 [Spring] Spring 개요
  3. 2018.10.30 [css] Media Queri
  4. 2018.10.24 [CSS] CSS란
  5. 2018.10.23 [JSP] 예외 페이지 1
  6. 2018.10.23 [JSP] forward action
2018. 12. 26. 21:59



Spring Boot logo, brand

Spring boot

 

1. 설정


JDK version : 1.8

STS version : STS 3.9.7 RELEASE

(Eclipse version : Eclipse Java EE IDE for Web Developers)



이클립스 사용시 필수 플러그인

l  Spring Tools 3(aka Spring Tool Suite 3(STS))

l  BuildShip Gradle Integration 3.0

l  Gradle IDE Pack 3.8x+1.0x


(Maven 사용시 Gradle 관련 플러그인을 설치하지 않아도 무방)

(이클립스가 아닌 따로 STS(Spring Tool Suite)를 설치해서 사용해도 무방) 

STS 설치 주소:https://spring.io/tools3/sts/all

 


Eclipse Properties Setting

 

이클립스 상단 > File > Properties

General > Content Types > Text 아래 항목을 확인하여 Default Encoding UTF-8로 되어 있는지 확인하고 ISO-8859-1등 다른 Encoding으로 되어 있는 것이 있으면 전부 UTF-8로 변경

 

General > Workspace > Text file encoding : Other/UTF-8 로 변경

General > Workspace > New text file line delimeter : Other/Unix 로 변경

Web > CSS Files > Encoding : UTF-8 (또는 ISO 10646/Unicode(UTF-8)) 로 변경합니다.

Web > HTML Files > Encoding : UTF-8 (또는 ISO 10646/Unicode(UTF-8)) 로 변경

Web > JavaServer Faces Tool > Validation : 모든 Validate... 항목 해제

Web > JSP Files > Encoding : UTF-8 (또는 ISO 10646/Unicode(UTF-8)) 로 변경

Web > JSP Files > Validate... 항목 해제

XML > XML Files > Encoding : UTF-8 (또는 ISO 10646/Unicode(UTF-8)) 로 변경

 

General > Show heap status : 체크

General > Compare/Patch > Ignore white space : 체크

General > Editors > Text Editors > Show line numbers : 체크

General > Editors > Text Editors > Spelling > Enable spell checking : 해제

Java > Editor > Save Actions > Perform the selected actions on save : 해제

JavaScript > Editor > Save Actions > Perform the selected actions on save : 해제

Validation > Suspend all validators : 체크



출처http://javafactory.tistory.com/1466?category=618816 [FreeLife의 저장소]


 



1-1. Spring boot 프로젝트 생성하기



Package explorer > 우클릭 > new > other > spring starter project 검색 후 NEXT



Name > 프로젝트 이름 입력

(위 사진은 캡쳐용이라서 SpringBootTest_3가 아닌 SpringBootTest_1로 생성 해주세요)


Type > maven 선택 (Gradle 사용자 Gradle 선택)

(gradle이 좋다고 하지만 아직 익숙하지 않아 maven으로 예제 진행하겠습니다.)


Packaging > war


Group > package명 입력 (x.y 형식)


Artifact > Artifact명 입력 (프로젝트 이름과 동일(자동))


NEXT




web> web 선택 (다른 옵션들도 있지만 최초 생성 시에는 선택하지 않는게 좋다고 한다)

Finish

 

프로젝트 생성 후 jar를 파일들을 모두 가져올 때까지 기다린다.


프로젝트 생성 완료 후 모습


프로젝트 선택, 우 클릭 > Run as > Spring boot App 실행



1-2. 웹 브라우저 > localhost:8080 입력 후 아래 페이지가 나오는지 확인한다.





 


tip. Server port 설정 방법



src/main/resources/Application properties > server.port:포트번호 입력



2. Database 연동하기


예제에서는 MariaDBMybatis를 사용하여 진행하겠습니다.



2-0. database와 table 생성


mariaDB 실행 후 다음 쿼리 문 입력.


[database 생성]

create database testdb;


[table 생성]

create table t_list(

       SEQ int,

       ITEMID varchar(50)

);


[data 입력]

insert into t_list values (1, "A");

insert into t_list values (2, "B");

insert into t_list values (3, "D");

insert into t_list values (4, "E");

insert into t_list values (5, "H");




2-1 pom.xml 작성하기


[pom.xml]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        <!-- This is a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <!-- This is for JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
 
        
        <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId
        </dependency>
 
        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
 
        <!-- Need this to compile JSP, 
            tomcat-embed-jasper version is not working, no idea why -->
        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>
 
        <!-- Optional, test for static content, bootstrap CSS-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
        
        <!-- for mariaDB -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>1.3.2</version>
        </dependency>
        
        <!-- for mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
 
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
cs


위 dependency들을 pom.xml에 추가.



프로젝트 우클릭 후 Maven > Update Project 선택



해당 프로젝트 체크 후 'OK' 클릭 후 Update가 완료 될 때 까지 대기




2-2. application.properties 작성


2-2-1. datasource 설정


[src/main/resources > application.properties]

1
2
3
4
5
#mariaDB
spring.datasource.driverClassName=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/데이터베이스명
spring.datasource.username=사용자명
spring.datasource.password=
cs


line 2 : jdbc 설정

line 3 : 데이터베이스 설정 (DB에서 create database dbname;로 만든 것)

line 4 : 사용자 설정

line 5 : 비밀번호 설정



2-2-2 jsp 설정


1
2
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
cs


line 1 : 경로 설정

line 2 : 확장자 설정



2-2-3. application.properties에 설정한 경로대로 WEB-INF 폴더 생성

[src/main/webapp/WEB-INF/jsp]



jsp 폴더 안에 main.jsp와 dbTest.jsp 생성


[main.jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
 
 
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>MAIN PAGE</title>
</head>
<body>
    <h1>THIS IS TEST PAGE</h1>
</body>
</html>
cs



[dbTest.jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
 
 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <table>
        <tr>
            <th>SEQ</th>
            <th>ITEMID</th>
        </tr>
 
 
        <c:forEach var="list" items="${list}">
            <tr>
                <td><p>${list.SEQ}</p></td>
                <td><p>${list.ITEMID}</p></td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>
cs




2-3. DatabaseConfig 작성


Database에 접속하고 session을 관리하는 class를 생성해야함. 실제 DB에 대한 부분.


[com.example.SpringBootTest.DatabaseConfig.java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.example.SpringBootTest;
 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@MapperScan(basePackages="com.example.SpringBootTest.dao")
@EnableTransactionManagement
public class DatabaseConfig {
 
    @Bean
    public  SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return sessionFactory.getObject();
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
      final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
      return sqlSessionTemplate;
    }
 
}
cs


@Configuration 

이 클래스는 Database 에 대한 접속 정보를 나타내고, 일반 Bean 이 나닌 Configuration으로 설정되어 있어야 한다. (실제로는 그 하위에 Bean을 두 개 더 생성한다)



@MapperScan(basePackages="com.simplify.sample")

최신 Spring Boot 에서는 dao를 dao라고 명시하지 않고, mapper 라는 이름으로 별도 정의하고 있다. 따라서 어떤 패키지에서 mapper들을 scan할 것인가를 최상위에 annotation으로 정의하여 주고 있다. 다중 Database에 접근해야 하는 경우, 이 클래스를 두 개를 만들어 두고 scan할 대상 mapper 들을 패키지 구조상에서 분리해 두는 것도 하나의 방법이라고 할 수 있다.



@EnableTransactionManagement

TransactionManager를 적용할 것인지에 대해 설정하는 annotation 이다.



@Bean SqlSessionFactory

DataSource 를 parameter로 받아, sqlSessionFactory를 생성하는 Bean 이다. 아래 있는 SqlSessionTemplate Bean 생성 시 인자로 넘겨주기 위해서 사용된다. 즉, 여기서 만들어진 기본정보, 설정값 등을 이용해서 SqlSessionTemplate를 만들게 되는 것이다.



.setMapperLocations()

실제 Query 문이 존재하는 xml파일들의 위치를 지정해 준다. 여기서는 mybatis/mapper 폴더 하위에 있는 모든 xml을 명시했다. 이 경로는 실제로는 src/main/resource 하위에 존재한다. ①이 폴더 구조 자체가 생성되어 있지 않거나, ②그 폴더에 mapper xml 이 하나도 없으면, ③혹은 그 xml 의 문법에 오류가 있으면 초기 구동 시점에 에러가 발생한다. 측, 초기에 mapper들의 위치 정보만을 지정하는 것이 아니라, 해당 mapper xml 들에 오류가 있는지 문법 체크까지 모두 한 뒤에 Factory가 생성되게 되는 것이므로, 이 부분을 다룰 때에는 중간중간 실행하여 오류가 발생하지는 않는지 꼭 확인하면서 지나가야 한다.



@Bean SqlSessionTemplate

실제 DB접속에 이용되는 SqlSessionTemplate를 생성하여 반환하는 Bean 이다. 실제 코드상에서 이용된다고 보면 된다.




여기까지 구현하고 실행하여 정상적으로 구동되는지 반드시 확인한다.


출처: https://4urdev.tistory.com/46 [Simplify]






2-4. DTO 클래스 작성


[com.example.SpringBootTest.dto.TestDTO]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.example.SpringBootTest.dto;
 
public class TestDTO {
    private int SEQ;
    private String ITEMID;
 
    public TestDTO() {
 
    }
 
    public TestDTO(int sEQ, String iTEMID) {
        super();
        SEQ = sEQ;
        ITEMID = iTEMID;
    }
 
    public int getSEQ() {
        return SEQ;
    }
 
    public void setSEQ(int sEQ) {
        SEQ = sEQ;
    }
 
    public String getITEMID() {
        return ITEMID;
    }
 
    public void setITEMID(String iTEMID) {
        ITEMID = iTEMID;
    }
 
}
 
cs


DB에 만들 컬럼명과 동일하게 생성할 것



2-5. DbMapper 인터페이스 작성


[com.example.SpringBootTest.dao.DbMapper]

1
2
3
4
5
6
7
8
9
10
package com.example.SpringBootTest.dao;
 
import java.util.List;
 
import com.example.SpringBootTest.dto.TestDTO;
 
public interface DbMapper {
    public List<TestDTO> getList() throws Exception;
}
 
cs






2-6. DbService 클래스 작성


[com.example.SpringBootTest.service.DbService]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.SpringBootTest.service;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.example.SpringBootTest.dao.DbMapper;
import com.example.SpringBootTest.dto.TestDTO;
 
@Service
public class DbService {
    
    @Autowired
    DbMapper dbmapper;
    
    public List<TestDTO> getList() throws Exception{
        
        return dbmapper.getList();
        
    }
}
 
cs






2-7. controller 클래스 작성


[com.example.SpringBootTest.controller]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.example.SpringBootTest.controller;
 
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import com.example.SpringBootTest.dto.TestDTO;
import com.example.SpringBootTest.service.DbService;
 
@Controller
public class TestController {
 
    @Autowired
    DbService dbService;
    
    @RequestMapping("/")
    public String main() {
        return "main";
    }
    
    
    
    @RequestMapping("/dbTest")
    public ModelAndView dbTest() throws Exception {
        
        List<TestDTO> list = new ArrayList<TestDTO>();
        list = dbService.getList();
        
        
        
        return new ModelAndView("dbTest""list", list);
    }
}
 
cs





2-8. mapper.xml 작성


src/main/resources 에 mapper 폴더 생성 후 안에 databasemapper.xml 생성




[src/main/resources/mapper/databasemapper.xml]

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.SpringBootTest.dao.DbMapper">
    <select id="getList" resultType="com.example.SpringBootTest.dto.TestDTO">
        SELECT * FROM t_list
    </select>
</mapper>
 
 
 
cs


namespace는 mapper interface에 대한 풀 패키지 명을 입력.

resultType은 결과값의 타입을 입력한다. 예제의 반환 타입은 DTO객체이므로 DTO객체의 풀 패키지 명을 입력한다.


id는 mapper interface의 해당 쿼리문을 실행시킬 메서드명과 동일하게 작성한다.



모든 패키지와 파일들을 작성 완료 후 모습은 다음과 같다.






3. 실행


프로젝트 선택 후 우클릭 > Run As > Spring Boot App 선택






[Exception 발생 없이 실행이 완료된 모습]



웹 브라우저 주소창에 localhost:8282 입력





주소창에 localhost:8282/dbTest 입력



많이 부족한 포스팅이지만 궁금한 점이나 잘못된 점 있으면 댓글 남겨주세요!



 

'Web > Spring Framework' 카테고리의 다른 글

[Spring] Spring 개요  (0) 2018.11.28
Posted by PAYJAY
2018. 11. 28. 17:02

스프링 프레임워크(Spring Framework)


개발자 피보탈 소프트웨어

최근 버전 5.0.1 / 2017년 10월 24일 (12달 전)

운영 체제 크로스 플랫폼 (멀티 플랫폼)

플랫폼 자바 가상 머신

종류 애플리케이션 프레임워크

라이선스 아파치 라이선스 2.0

웹사이트 (영어) http://www.springsource.org



스프링 프레임워크(Spring Framework)는 자바 플랫폼을 위한 오픈소스 애플리케이션 프레임워크로서 간단히 스프링(Spring)이라고도 불린다. 동적인 웹 사이트를 개발하기 위한 여러 가지 서비스를 제공하고 있다. 대한민국 공공기관의 웹 서비스 개발 시 사용을 권장하고 있는 전자정부 표준프레임워크의 기반 기술로서 쓰이고 있다.



특징


1. 경량 컨테이너로서 자바 객체를 직접 관리한다. 각각의 객체 생성, 소멸과 같은 라이프 사이클을 관리하며 스프링으로부터 필요한 객체를 얻어올 수 있다.


2. 스프링은 POJO(Plain Old Java Object) 방식의 프레임워크이다. 일반적인 J2EE 프레임워크에 비해 구현을 위해 특정한 인터페이스를 구현하거나 상속을 받을 필요가 없어 기존에 존재하는 라이브러리 등을 지원하기에 용이하고 객체가 가볍다.


3. 스프링은 제어 반전(IoC : Inversion of Control)을 지원한다. 컨트롤의 제어권이 사용자가 아니라 프레임워크에 있어서 필요에 따라 스프링에서 사용자의 코드를 호출한다.


4. 스프링은 의존성 주입(DI : Dependency Injection)을 지원한다. 각각의 계층이나 서비스들 간에 의존성이 존재할 경우 프레임워크가 서로 연결시켜준다.


5. 스프링은 관점 지향 프로그래밍(AOP : Aspect-Oriented Programming)을 지원한다. 따라서 트랜잭션이나 로깅, 보안과 같이 여러 모듈에서 공통적으로 사용하는 기능의 경우 해당 기능을 분리하여 관리할 수 있다.


6. 스프링은 영속성과 관련된 다양한 서비스를 지원한다. iBATIS나 Hibernate 등 이미 완성도가 높은 데이터베이스 처리 라이브러리와 연결할 수 있는 인터페이스를 제공한다.


7. 스프링은 확장성이 높다. 스프링 프레임워크에 통합하기 위해 간단하게 기존 라이브러리를 감싸는 정도로 스프링에서 사용이 가능하기 때문에 수많은 라이브러리가 이미 스프링에서 지원되고 있고 스프링에서 사용되는 라이브러리를 별도로 분리하기도 용이하다.






(출처:위키백과)





'Web > Spring Framework' 카테고리의 다른 글

[Spring Boot] Spring boot + MariaDB + Mybatis 연동  (3) 2018.12.26
Posted by PAYJAY
2018. 10. 30. 02:19



미디어 쿼리css3 모듈 중 하나로 사이트에 접속하는 장치에 따라 특정한 CSS 스타일을 사용하도록 해준다. 미디어 쿼리를 이용한 사이트는 다른 기기로 접속할 때마다 레이아웃이 바뀐다.

사용자가 어떤 미디어를 사용하는가에 따라 사이트의 형태가 바뀌도록 CSS를 작성하는 것을 미디어 쿼리라고 한다.


<미디어 쿼리 구문>

@media [only | not] 미디어 유형 [and 조건] * [and 조건]


<style> 태그 사이에 사용하며 대소문자를 구분하지 않는다.


ex)


@media screen and (min-width:200px) and (max-width:500px){

          

}


미디어 유형은 screen이며 최소 너비 200px이고 최대 너비가 500px일 때 적용한 CSS를 정의한다.

 

<style>

Body{

           <!-- 문서 기본 배경 -->

           Background: url(images/bg0/jpg) no-repeat fixed;

           Background-size: cover;

}

@media screen and (max-width:1024px){

<!-- 화면 너비가 1024px 이하일 때 배경 -->

           Background: url(images/bg1/jpg) no-repeat fixed;

           Background-size: cover;

}

@media screen and (max-width:768px){

<!-- 화면 너비가 768px 이하일 때 배경 -->

           Background: url(images/bg2/jpg) no-repeat fixed;

           Background-size: cover;

}

@media screen and (max-width:320px){

<!-- 화면 너비가 320px 이하일 때 배경 -->

           Background: url(images/bg3/jpg) no-repeat fixed;

           Background-size: cover;

}

 

</style>


'Web > CSS' 카테고리의 다른 글

[CSS] CSS란  (0) 2018.10.24
Posted by PAYJAY
2018. 10. 24. 01:08





CSS

 

CSSCascading Style Sheet의 약자

CSSHTML 요소들이 각종 미디어에서 어떻게 보이는가를정의하는데 사용되는 스타일 시트 언어이다. 대부분의 웹 브라우저들은 모두 CSS를 지원한다.

CSS 사용 이유

HTML은 문서 구조를 표현하기에 적합한 마크업 언어라서 화면상에 컨텐츠를 깔끔하게 보여주기에 한계가 있다.

CSS를 사용하면 HTML에서 지원하지 않는 다양한 스타일의 표현이 가능하다.

작업의 효율성 향상

CSS를 사용하면 문서의 컨텐츠와 스타일을 분리할 수 있다. 웹 페이지의 스타일을 별도의 파일로 저장할 수 있게 해주므로 사이트의 전체 스타일을 손쉽게 제어할 수 있다.

또한 웹 사이트의 스타일을 일관성 있게 유지할 수 있게 해주면 그에 따른 유지 보수 또한 쉬워진다.

(출처: DevKuma)



Html 태그에 글자색을 바꿀수있따

글자의 정렬방식

배경색 지정

이미지 지정

 

사용의 편의성과 일괄성

Html 문서가 등장한 목적은 간단하고 빠르게 인터넷 상에 정보를 공유할 수 있는 문서를 만드는 것


[문법]

<style>

           선택자{속성: 속성값; 속성: 속성값;}

</ style >


인라인 스타일

태그에 직접 스타일 지정

하나의 태그에만 원하는 스타일 지정

같은 스타일을 사용하는 태그가 많으면 코드가 많아짐

 


'Web > CSS' 카테고리의 다른 글

[css] Media Queri  (0) 2018.10.30
Posted by PAYJAY
2018. 10. 23. 19:45




예외 페이지



예외적인 상황이 발생했을 경우 웹 컨테이너에서 제공되는 기본적인 예외페이지가 사용자에게는 다소 불편할 수도 있다 (ex)Tomcat 예외페이지) 이러한 기본적으로 제공되는 페이지가 아니라 개발자가 제작한 페이지를 사용자에게 보여줄 수 있다.


1.     Page 지시자를 이용한 예외 처리

A.     <%@ page errorPage=”errorPage.jsp”%>

B.      해당 페이지에서 예외 발생 시 설정한 페이지로 이동

C.      에러페이지에서는 해당 페이지가 에러 발생시 보여지는 페이지라는 것을 명시를 해줘야한다.

D.     <%@ page isErrorPage=”true”%> è defaultfalse이므로 true로 바꿔줘야한다.

E.      <%= exception.getMessage()%> è 에러메세지 출력. page지시자에서 false로 설정 되어있으면 exception객체를 참조할 수 없다.

F.      <%response.setStatus(200)%> è 우리가 만드는 페이지는 에러를 출력해주기만 하는 페이지, 즉 정상적인 페이지이다. 해당 페이지가 정상인 페이지라는 것을 설정하기 위해 사용.


ex)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!—에러 발생 페이지-->
 
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    <%@ page errorPage="errorTest.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <%
        int i = 40/0;
    %>
</body>
</html>
 
cs

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!—에러 표시 페이지-->
 
<%@ page language="java" contentType="text/html; charset=EUC-KR"
 
    pageEncoding="EUC-KR"%>
 
    <%@ page isErrorPage="true" %>
 
    <% response.setStatus(200); %>
 
<!DOCTYPE html>
 
<html>
 
<head>
 
<meta charset="EUC-KR">
 
<title>Insert title here</title>
 
</head>
 
<body>
 
           에러 발생<br>
 
           <%=exception.getMessage() %>
 
</body>
 
</html>
cs

 

 

 

2.     Web.xml 파일을 이용한 에러 페이지 지정

A.     <error-page> : 에러페이지 지정.

B.      <error-code> : 에러상태 코드 지정. 코드별로 지정.

C.      <exception-type> : 익셉션을 지정한다. 익셉션 별로 지정.

D.     <location> : 에러 페이지 위치 지정.

 


ex)

<error-page>

<error-code>404</error-code>

<location>/error404.jsp</location>

</error-page>

 

<error-page>

<error-code>404</error-code>

<location>/error500.jsp</location>

</error-page>

 

<error-page>

<exception-type>java.lang.NullPionterException</exception-type>

<location>/errorNull.jsp</location>

</error-page>




'Web > JSP' 카테고리의 다른 글

[JSP] forward action  (0) 2018.10.23
[JSP] EL & JSTL  (0) 2018.10.21
[JSP] MVC  (0) 2018.10.20
[JSP] 웹 프로그래밍 JSP와 Servlet  (0) 2018.10.16
Posted by PAYJAY
2018. 10. 23. 17:00



forward액션

Include액션과 유사. 현재 페이지의 제어권을 완전히 다른 페이지로 전달

브라우저 URL에는 최종 전달된 파일명 아닌 최초 호출한 파일명 보임

 

만약 from.jsp 파일에서 to.jsp파일로 요청을 이동시키는 경우 from.jsp에서 생성하던 결과는 모두 없어진다.

새로 이동한 to.jsp에서 생성한 결과를 브라우저에 출력시키면 url주소는 /from.jsp로 보인다.

하지만 실제 결과는 to.jsp이다.


[주 활용방법]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%
String name = request.getParameter(“name”);
String toURI = null;
 
If(name.equals(“LEE”)){
    toURI = “lee.jsp”;
}else if(name.equals(“PARK”){
    toURI = “park.jsp”;
else if(name.equals(“KIM”){
    toURI = “kim.jsp”;
}
%>
<jsp:forward page=<%= toURI %>” />
 
cs


위와 같은 형태가 전형적인 forward 태그 사용법이다. 조건에 따라서 그에 맞는 페이지로 분기시키는 것. 위의 경우는 name의 값에 따라 페이지가 forward 되고 있다.


'Web > JSP' 카테고리의 다른 글

[JSP] 예외 페이지  (1) 2018.10.23
[JSP] EL & JSTL  (0) 2018.10.21
[JSP] MVC  (0) 2018.10.20
[JSP] 웹 프로그래밍 JSP와 Servlet  (0) 2018.10.16
Posted by PAYJAY