1. class EncodingFilter 어노테이션 이용
package config;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
//모든 요청에 대해서 EncodingFilter 를 경유하도록 설정
@WebFilter("/*")
public class EncodingFilter implements Filter {
private String charset="utf-8";
// 필터가 load될 때 자동호출되는 코드
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("필터 loading...");
}
// 요청이 있을 때 선처리되는 코드
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding(charset);
//사용자가 요청한 페이지 처리
chain.doFilter(request, response);
}
//웹서버가 stop 될 때 자동 호출
public void destroy() {
System.out.println("필터가 unloading.....");
}
}
2. WEB-INF/web.xml 파일에 필터 매핑
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web Application</display-name>
<!-- 서블릿을 매핑하듯 필터도 같은 방식으로 WEB-INF/web.xml 파일에 매핑함. -->
<!-- filter-name : 필터 클래스 파일 이름. -->
<!-- filter-class : 필터 클래스 경로(애플리케이션 내에서의 절대 경로). -->
<!-- init-param : 필터 클래스에서 사용하려는 파라미터의 이름, 값을 web.xml에서 미리 지정할 수 있음. -->
<filter>
<filter-name>HangulEncodingFilter</filter-name>
<filter-class>com.filter.HangulEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- url-pattern : 해당 애플리케이션 내에서 필터를 적용시키고자 하는 범위. -->
<!-- /* - 애플리케이션 내 모든 post 방식에서 적용(servlet, jsp 구분 없이). -->
<!-- /*.do - 애플리케이션 내 *.do로 이름을 지은 서블릿 post 메소드만 적용. -->
<!-- servlet-name : 애플리케이션 내 특정 서블릿에만 적용할 때 씀.-->
<filter-mapping>
<filter-name>HangulEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
출처: http://diaryofgreen.tistory.com/78 [Day By Day]
class HangulEncodingFilter
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Servlet Filter implementation class ExampleBFilter
*/
public class HangulEncodingFilter implements Filter {
//인코딩을 수행할 인코딩 캐릭터 셋 지정
String encoding;
//필터 설정 관리자
FilterConfig filterConfig;
/**
* Default constructor.
*/
public HangulEncodingFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
//초기화
//getInitParameter() : web.xml에 초기화해서 지정한 파라미터 값을 불러오는 메소드.
this.filterConfig = fConfig;
this.encoding = fConfig.getInitParameter("encoding");
// System.out.println("debug > init %%%%%%%%%");
}
/**
* @see Filter#destroy()
*/
//destroy : 웹 애플리케이션이 끝날 때 같이 끝남
public void destroy() {
this.encoding = null;
this.filterConfig = null;
// System.out.println("debug > destroy %%%%%%%%%%%");
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//request.setCharacterEncoding("utf-8");
// System.out.println("characterEncoding : " + request.getCharacterEncoding());
if (request.getCharacterEncoding() == null) {
if (encoding != null)
request.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);
}
}
출처: http://diaryofgreen.tistory.com/78 [Day By Day]
3. 멤버 리스트 불러오기
SQL
select * from member2;
drop table member2;
create table member2(
userid VARCHAR2(50) not null primary key,
passwd VARCHAR2(50) not null,
name VARCHAR2(50) not null
);
-- alert table 테이블 add( 컬럼 자료형)
alter table member2 add (reg_date date DEFAULT sysdate );
alter table member2 add ( address VARCHAR2(500) );
alter table member2 add ( tel VARCHAR2(5) );
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('kim', '1111', '김철수', '서울' , '010-343-3433');
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('guisu', '1111', '김기수', '부산' , '010-6565-3433');
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('hong', '1111', '홍길동', '대구' , '010-3244-1113');
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('lee', '1111', '이순신', '청주' , '010-3233-3213');
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('kang', '1111', '강감찬', '수원' , '010-343-4542');
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('superman', '1111', '슈퍼맨', '대전' , '010-1322-8643');
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('bate', '1111', '배트맨', '광주' , '010-4234-8875');
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('spiderman', '1111', '스파이더맨', '강릉' , '010-7543-7433');
insert into MEMBER2 (USERID, PASSWD, NAME, ADDRESS, TEL)
VALUES ('xman', '1111', 'X맨', '인처' , '010-3432-6653');
commit;
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>
<!-- Default set of monitored resources. If one of these changes, the -->
<!-- web application will be reloaded. -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
<Resource name="jdbc/myoracle" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:xe"
username="java" password="1111" maxTotal="20" maxIdle="10"
maxWaitMillis="-1"/>
</Context>
class DB
package config;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DB {
public static Connection getConn(){
DataSource ds =null;//javax.sql.DataSource
Connection conn=null;
try{
//context.xml 파일을 분석하는 객체
Context context = new InitialContext();
// context.xml 파일의 Resource 태그의 name 속성 검색
// java:comp/env/리소스태그의name
ds=(DataSource)context.lookup("java:comp/env/jdbc/myoracle");
// 커넥션풀에서 커넥션을 리턴받음
conn=ds.getConnection();
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
}
MemberController
package member;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/member_servlet/*")
public class MemberController extends HttpServlet {
private static final long serialVersionUID = 1L;
//요청한 주소(url)
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//컨텍스트 주소(웹프로텍트의 식별자)
String url =request.getRequestURL().toString();
String context=request.getContextPath();
MemberDAO dao =new MemberDAO();
if(url.indexOf("list.do")!=-1){//list.do 이면
Map<String, Object> map =new HashMap<>();
List<MemberDTO> list=dao.memberList();
map.put("list", list);//맵에 자료 저장
map.put("count", list.size());//레코드 갯수
request.setAttribute("map", map);//출력할 변수 저장
String page="/ch09/member_list.jsp";
RequestDispatcher rd
=request.getRequestDispatcher(page);
rd.forward(request, response);//화면 전환
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
class MemberDTO
package member;
public class MemberDTO {
private String userid ;
private String passwd;
private String name;
private String reg_date;
private String address;
private String tel;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReg_date() {
return reg_date;
}
public void setReg_date(String reg_date) {
this.reg_date = reg_date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@Override
public String toString() {
return "MemberDTO [userid=" + userid + ", passwd=" + passwd + ", name=" + name + ", reg_date=" + reg_date
+ ", address=" + address + ", tel=" + tel + "]";
}
}
class MemberDAO
package member;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import config.DB;
public class MemberDAO {
public String loginCheck(String userid, String passwd){
String result=null;
Connection conn=null;
PreparedStatement pstmt =null;
ResultSet rs=null;
try{
conn=DB.getConn();//DB 커넥션 리턴
String sql=" select name from member2 where USERID=? and passwd=? ";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, userid);//1번 물음표
pstmt.setString(2, passwd);//2번 물음표
rs=pstmt.executeQuery();
if(rs.next()){//로그인 성공하면 이름을 저장
result=rs.getString("name");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null)rs.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(pstmt!=null)pstmt.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(conn!=null)conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
return result;
}
public List<MemberDTO> memberList(){
List<MemberDTO> list =new ArrayList<>();
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
conn=DB.getConn();//DB 커넥션 리턴
String sql ="select * from member2 ";
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next()){
MemberDTO dto =new MemberDTO();
dto.setAddress(rs.getString("address"));
dto.setName(rs.getString("name"));
dto.setPasswd(rs.getString("passwd"));
dto.setReg_date(String.valueOf(rs.getTimestamp("reg_date")));
dto.setTel(rs.getString("tel"));
dto.setUserid(rs.getString("userid"));
list.add(dto);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null)rs.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(pstmt!=null)pstmt.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(conn!=null)conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
return list;
}
}
class MemberController
package member;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/member_servlet/*")
public class MemberController extends HttpServlet {
private static final long serialVersionUID = 1L;
//요청한 주소(url)
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//컨텍스트 주소(웹프로텍트의 식별자)
String url =request.getRequestURL().toString();
String context=request.getContextPath();
MemberDAO dao =new MemberDAO();
if(url.indexOf("list.do")!=-1){//list.do 이면
Map<String, Object> map =new HashMap<>();
List<MemberDTO> list=dao.memberList();
map.put("list", list);//맵에 자료 저장
map.put("count", list.size());//레코드 갯수
request.setAttribute("map", map);//출력할 변수 저장
String page="/ch09/member_list.jsp";
RequestDispatcher rd
=request.getRequestDispatcher(page);
rd.forward(request, response);//화면 전환
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
member_list.jsp
<%@page import="member.MemberDTO"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<!-- member_list.jsp -->
<%
Map<String, Object> map
=(Map<String, Object>)request.getAttribute("map");
List<MemberDTO> list=(List<MemberDTO>)map.get("list");
int count =(Integer)map.get("count");
%>
<h2>회원수 : <%= count %></h2>
<table border="1">
<tr>
<th>아이디</th>
<th>이름</th>
<th>비번</th>
<th>가입날짜</th>
<th>주소</th>
<th>전화</th>
</tr>
<%
for(MemberDTO dto : list) {
%>
<tr>
<td><%= dto.getUserid() %></td>
<td><%= dto.getName() %></td>
<td><%= dto.getPasswd() %></td>
<td><%= dto.getReg_date() %></td>
<td><%= dto.getAddress() %></td>
<td><%= dto.getTel() %></td>
</tr>
<% } %>
</table>
</body>
</html>
=>출력
회원수 : 9
아이디 | 이름 | 비번 | 가입날짜 | 주소 | 전화 |
---|---|---|---|---|---|
kim | 김철수 | 1111 | 2017-05-22 16:24:43.0 | 서울 | 010-343-3433 |
guisu | 김기수 | 1111 | 2017-05-22 16:28:26.0 | 부산 | 010-6565-3433 |
hong | 홍길동 | 1111 | 2017-05-22 16:28:26.0 | 대구 | 010-3244-1113 |
lee | 이순신 | 1111 | 2017-05-22 16:28:26.0 | 청주 | 010-3233-3213 |
kang | 강감찬 | 1111 | 2017-05-22 16:28:26.0 | 수원 | 010-343-4542 |
superman | 슈퍼맨 | 1111 | 2017-05-22 16:28:26.0 | 대전 | 010-1322-8643 |
bate | 배트맨 | 1111 | 2017-05-22 16:28:26.0 | 광주 | 010-4234-8875 |
spiderman | 스파이더맨 | 1111 | 2017-05-22 16:28:26.0 | 강릉 | 010-7543-7433 |
xman | X맨 | 1111 | 2017-05-22 16:28:26.0 | 인처 | 010-3432-6653 |
댓글 ( 4)
댓글 남기기