[힌트]
forward.jsp -> 요청파라미터를 읽어서 requestScope에 binding 한뒤 Servlet으로 이동
RegisterMemberServlet : 완성
register_success.jsp : 수정(주민번호 수정)
한글처리 : - Filter
class :
package : member.filter
class name : EncodingFilter
<%@page import="member.dto.MemberDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="mdto" class="member.dto.MemberDTO" scope="request"/>
<jsp:setProperty property="*" name="mdto"/>
<!--<jsp:setProperty property="mileage" value="1000" name="mdto"/>-->
<jsp:forward page="/register_member"/>
<body>
</body>
</html>
package member.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.MemberDTO;
import member.exception.DuplicatedIdException;
import member.exception.DuplicatedRegisterNumberException;
import memver.model.service.MemberManageService;
/**
* Servlet implementation class RegiserMemberServlet
*/
public class RegiserMemberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection = null;
private PreparedStatement preparedStatement = null;
public RegiserMemberServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.요청파라미터 조회
MemberDTO mdto = (MemberDTO)request.getAttribute("mdto");
mdto.setMileage(1000);
//2. Business Logic 처리 - MemberManageService.registerMember()
MemberManageService memberManageService = MemberManageService.getInstance();
String resUrl = null;
try {
memberManageService.registerMember(mdto);
resUrl="/res/register_success.jsp";
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
resUrl="/res/error.jsp";
}
//3. 응답처리 - register_success.jsp, error.jsp
RequestDispatcher dispatcher = request.getRequestDispatcher(resUrl);
dispatcher.forward(request, response);
}
}
<%@page import="member.dto.MemberDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="/menu.jsp"/>
<h2>가입 환영합니다.</h2>
<h3>가입 시 입력한 정보입니다. </h3>
ID : ${requestScope.mdto.id }
Password : ${requestScope.mdto.password }
이름 : ${requestScope.mdto.name }
주민번호 : ${requestScope.mdto.registerNumber1 } - ${requestScope.mdto.registerNumber2 }
마일리지 : ${requestScope.mdto.mileage }<p>
<a href="/${initParam.context_root }/login_form.jsp">로그인</a>
<a href="/${initParam.context_root }/index.jsp">메인페이지</a>
</body>
</html>
package member.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;
public class EncodingFilter implements Filter{
private FilterConfig config;
@Override
public void destroy() {
}
@Override
//Servlet의 service() 역할
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String encoding = config.getInitParameter("encoding");//초기파라미터 조회
//요청에 대한 한글처리
request.setCharacterEncoding(encoding);
System.out.println("doFilter()호출 전 - 사전처리(요청단계)");
chain.doFilter(request, response);//다음 컴포넌트(Filter, Servlet/jsp)로 이동
System.out.println("doFilter 호출 후 - 사후처리(응답단계");
}
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
}
* 결과보기
* 전체 회원 정보 조회하기
메뉴 -> (/getAllMemberInfo)
->GetAllMemberSerlvet
->MemberManagerService.getMemberList() ; ArrayList<MemberDTO>
->MemberDAO.selectAllMember() ; ArrayList<MemberDTO>
->응답 : error.jsp, member_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="/menu.jsp"/>
<h1>회원관리</h1>
<a href='/${initParam.context_root }/register_form.jsp'>회원가입폼</a><br>
<a href='/${initParam.context_root }/login_form.jsp'>로그인폼</a>
<a href='/${initParam.context_root }/getAllMemberInfo'>전체 회원 조회</a>
</body>
</html>
package member.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class GetAllMemberInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetAllMemberInfoServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
MemberManageService memberManageService = MemberManageService.getInstance();
String resUrl = null;
try {
ArrayList<MemberDTO> list = memberManageService.getMemberList();
request.setAttribute("member_list", list);
resUrl ="/member_list.jsp";
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
resUrl = "/res/error.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(resUrl);
dispatcher.forward(request, response);
}
}
<%@page import="member.dto.MemberDTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
<body>
<jsp:include page="/menu.jsp"/>
<h2>모든 회원 목록조회</h2><hr><p>
<table width="500" border="1" cellspacing="0">
<tr align="center">
<td>순번</td><td>아이디</td><td>이름</td><td>주민번호</td><td>마일리지</td>
</tr>
<c:forEach items="${requestScope.member_list }" var="member_list" varStatus="cnt">
<tr align="center">
<td>${cnt.count }</td><td>${member_list.id }</td><td><a href="/servlet_member/SearchMemberByID?id=${member_list.id }">${member_list.name }</a></td><td>${member_list.registerNumber1 }-${member_list.registerNumber2 }</td><td>${member_list.mileage }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
package member.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import member.dto.MemberDTO;
import member.util.DatabaseUtility;
public class MemberDAO {
private static MemberDAO instance = new MemberDAO();
private DatabaseUtility dbUtil;
private MemberDAO(){
dbUtil = DatabaseUtility.getInstance();
}
public static MemberDAO getInstance(){
return instance;
}
/*
* id로 회원 정보를 조회하야 return 하는 메소드
* @param id 조회할 회원 ID
* @return
* @throws SQLException
*/
public MemberDTO selectMemberById(String id)throws SQLException{
//조회된 결과가 없다면 mto에 null값이 넘어간다.
MemberDTO mto= null;
Connection conn=null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select id, password, name, register_number1, register_number2, mileage from member where id=?";
try{
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rset = pstmt.executeQuery();
if(rset.next()){
mto = new MemberDTO(rset.getString(1),rset.getString(2),rset.getString(3),rset.getString(4),rset.getString(5),rset.getInt(6));
}
}finally{
dbUtil.close(rset, pstmt, conn);
}
return mto;
}
/*
* 주민번호로 회원 정보를 조회하는 메소드
* @param registerNumber1 주민번호 앞6자리
* @param registerNumber2 주민번호 뒤7자리
* @return
* @thows SQLException
*/
public MemberDTO selectMemberByregisterNumber(String registerNumber1, String registerNumber2)throws SQLException{
MemberDTO mto= null;
BasicDataSource ds = dbUtil.getDataSource();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select id, password, name, register_number1, register_number2, mileage from member where register_Number1=? and register_Number2=?";
try{
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, registerNumber1);
pstmt.setString(2, registerNumber2);
rset = pstmt.executeQuery();
if(rset.next()){
mto = new MemberDTO(rset.getString(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6));
}
}finally{
dbUtil.close(rset, pstmt, conn);
}
return mto;
}
/*
* 회원정보를 DB에 insert하는 메소드
* @param mto 등록할 회원 정보
* @throws SQLEception
*/
public void insertMember(MemberDTO mto)throws SQLException{
BasicDataSource ds = dbUtil.getDataSource();
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into member (id, password, name, register_number1, register_number2, mileage) values(?,?,?,?,?,?)";
try{
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, mto.getId());
pstmt.setString(2, mto.getPassword());
pstmt.setString(3, mto.getName());
pstmt.setString(4, mto.getRegisterNumber1());
pstmt.setString(5, mto.getRegisterNumber2());
pstmt.setInt(6, mto.getMileage());
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 삽입되었습니다.");
}finally{
dbUtil.close(pstmt, conn);
}
}
public ArrayList<MemberDTO> selectAllMember() throws SQLException{
ArrayList<MemberDTO> list = new ArrayList<MemberDTO>();
BasicDataSource ds = dbUtil.getDataSource();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select id, password, name, register_number1, register_number2, mileage from member";
try{
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
MemberDTO mto = new MemberDTO(rset.getString(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6));
list.add(mto);
}
}finally{
dbUtil.close(rset, pstmt, conn);
}
return list;
}
}
package memver.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import member.dto.MemberDTO;
import member.exception.DuplicatedIdException;
import member.exception.DuplicatedRegisterNumberException;
import member.model.dao.MemberDAO;
public class MemberManageService {
//회원 관리 비지니스 로직을 처리하는 Business Service 클래스
private static MemberManageService instance = new MemberManageService();
private MemberDAO dao;
private MemberManageService(){
dao = MemberDAO.getInstance();
}
public static MemberManageService getInstance(){
return instance;
}
//가입 처리 메소드
public void registerMember(MemberDTO mto)throws SQLException, DuplicatedIdException, DuplicatedRegisterNumberException{
//1. 등록된 ID가 있는 지 체크
// - 이미 등록된 ID라면 DuplicatedIdException를 발생시킨다.
if(dao.selectMemberById(mto.getId())!=null){
throw new DuplicatedIdException(mto.getId()+"는 이미등록된 아이디 입니다.");
}
//2. 등록된 주민번호가 있는 지 체크
// - 이미 등록된 주민번호라면 DuplicatedRegisterNumberException 발생시킨다.
if(dao.selectMemberByregisterNumber(mto.getRegisterNumber1(), mto.getRegisterNumber2())!=null){
throw new DuplicatedRegisterNumberException("는 이미 가입된 주민번호 입니다.");
}
//3. 디비에 회원정보 등록 처리
dao.insertMember(mto);
// 전체 회원 목록 조회
}
public ArrayList<MemberDTO> getMemberList() throws SQLException{
return dao.selectAllMember();
}
}
* 결과 보기
* 검색 : 마일리지 범위로 회원정보 조회하기
search_form.jsp(검색 조건 입력페이지) - 요청 파라미터 : 시작~끝 마일리지
->SearchByMileageRangeServlet() - url : /searchByMileageRange
->MemberManagerService.searchMemberByMileageRange(int start, int end) : ArrayList<MemberDTO>
->MemberDAO.selectMemberByMileageRange(int start, int end) : ArrayList<MemberDTO>
응답 -> search_result.jsp, error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<font size="2" color="red">${requestScope.error_message }</font><br>
마일리지 검색하기<hr><p>
<form action="/${initParam.context_root }/searchByMileageRange" method="post">
범위 : <input type = "text" name="startMileage">~<input type = "text" name="endMileage">
<input type="submit" value="검색">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="/menu.jsp"/>
<h2> ${requestScope.title } </h2><hr><p>
조회범위 : ${requestScope.search_value }
<table width="500" border="1" cellspacing="0">
<tr align="center">
<td>순번</td><td>아이디</td><td>이름</td><td>주민번호</td><td>마일리지</td>
</tr>
<c:forEach items="${requestScope.searchMileageRangeMemberList }" var="member_list" varStatus="cnt">
<tr align="center">
<td>${cnt.count }</td><td>${member_list.id }</td><td><a href="/servlet_member/SearchMemberByID?id=${member_list.id }">${member_list.name }</a></td><td>${member_list.registerNumber1 }-${member_list.registerNumber2 }</td><td>${member_list.mileage }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<a href='/${initParam.context_root }/index.jsp'>메인페이지</a>
<c:choose>
<c:when test="${sessionScope.memberDTO == null }">
<a href='/${initParam.context_root }/register_form.jsp'>회원가입폼</a>
<a href="/${initParam.context_root }/login_form.jsp">로그인폼</a>
<a href="/${initParam.context_root }/search_form.jsp">검색</a>
</c:when>
<c:otherwise>
<a href='/${initParam.context_root }/logout'>로그아웃</a>
<a href="/${initParam.context_root }/getMemberInfo">회원정보조회</a>
<a href="/${initParam.context_root }/modifyForm">회원정보 수정</a>
<a href="/${initParam.context_root }/removeMember">회원 탈퇴</a>
</c:otherwise>
</c:choose>
<a href="/${initParam.context_root }/getAllMemberInfo">전체 회원정보 조회</a>
<hr width="700" align="left" noshade="noshade">
package member.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import member.dto.MemberDTO;
import member.util.DatabaseUtility;
public class MemberDAO {
private static MemberDAO instance = new MemberDAO();
private DatabaseUtility dbUtil;
private MemberDAO(){
dbUtil = DatabaseUtility.getInstance();
}
public static MemberDAO getInstance(){
return instance;
}
/*
* id로 회원 정보를 조회하야 return 하는 메소드
* @param id 조회할 회원 ID
* @return
* @throws SQLException
*/
public MemberDTO selectMemberById(String id)throws SQLException{
//조회된 결과가 없다면 mto에 null값이 넘어간다.
MemberDTO mto= null;
Connection conn=null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select id, password, name, register_number1, register_number2, mileage from member where id=?";
try{
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rset = pstmt.executeQuery();
if(rset.next()){
mto = new MemberDTO(rset.getString(1),rset.getString(2),rset.getString(3),rset.getString(4),rset.getString(5),rset.getInt(6));
}
}finally{
dbUtil.close(rset, pstmt, conn);
}
return mto;
}
/*
* 주민번호로 회원 정보를 조회하는 메소드
* @param registerNumber1 주민번호 앞6자리
* @param registerNumber2 주민번호 뒤7자리
* @return
* @thows SQLException
*/
public MemberDTO selectMemberByregisterNumber(String registerNumber1, String registerNumber2)throws SQLException{
MemberDTO mto= null;
BasicDataSource ds = dbUtil.getDataSource();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select id, password, name, register_number1, register_number2, mileage from member where register_Number1=? and register_Number2=?";
try{
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, registerNumber1);
pstmt.setString(2, registerNumber2);
rset = pstmt.executeQuery();
if(rset.next()){
mto = new MemberDTO(rset.getString(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6));
}
}finally{
dbUtil.close(rset, pstmt, conn);
}
return mto;
}
/*
* 회원정보를 DB에 insert하는 메소드
* @param mto 등록할 회원 정보
* @throws SQLEception
*/
public void insertMember(MemberDTO mto)throws SQLException{
BasicDataSource ds = dbUtil.getDataSource();
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into member (id, password, name, register_number1, register_number2, mileage) values(?,?,?,?,?,?)";
try{
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, mto.getId());
pstmt.setString(2, mto.getPassword());
pstmt.setString(3, mto.getName());
pstmt.setString(4, mto.getRegisterNumber1());
pstmt.setString(5, mto.getRegisterNumber2());
pstmt.setInt(6, mto.getMileage());
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 삽입되었습니다.");
}finally{
dbUtil.close(pstmt, conn);
}
}
public ArrayList<MemberDTO> selectAllMember() throws SQLException{
ArrayList<MemberDTO> list = new ArrayList<MemberDTO>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select id, password, name, register_number1, register_number2, mileage from member";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
list.add(new MemberDTO(rset.getString(1), rset.getString(2),
rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6)));
}
}finally{
dbUtil.close(rset, pstmt, conn);
}
return list;
}
public ArrayList<MemberDTO> selectMemberByMileageRange(int startMileage, int endMileage)throws SQLException {
ArrayList<MemberDTO> searchMileageRangeMemberList = new ArrayList<MemberDTO>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
// String sql = "select id, password, name, register_number1, register_number2, mileage from member where mileage>=? and mileage<=?";
String sql = "select id, password, name, register_number1, register_number2, mileage from member where mileage between ? and ?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, startMileage);
pstmt.setInt(2, endMileage);
rset = pstmt.executeQuery();
while(rset.next()){
searchMileageRangeMemberList.add(new MemberDTO(rset.getString(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6)));
}
}finally{
dbUtil.close(rset, pstmt, conn);
}
return searchMileageRangeMemberList;
}
}
package member.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class SearchByMileageRangeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SearchByMileageRangeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int startMileage = 0;
int endMileage = 0;
MemberManageService memberManageService = MemberManageService.getInstance();
ArrayList<MemberDTO> list;
String resUrl = null;
try{
startMileage = Integer.parseInt(request.getParameter("startMileage"));
endMileage = Integer.parseInt(request.getParameter("endMileage"));
}catch(NumberFormatException e){
e.printStackTrace();
request.setAttribute("error_message", e.getMessage()+"숫자를 넣어주세요");
RequestDispatcher dispatcher = request.getRequestDispatcher("/search_form.jsp");
dispatcher.forward(request, response);
return;
}
try {
list = memberManageService.selectMemberByMileageRange(startMileage,endMileage);
request.setAttribute("searchMileageRangeMemberList", list);
request.setAttribute("title", "마일리지 범위로 조회 결과");
request.setAttribute("search_value", startMileage+"~"+endMileage);
resUrl = "/res/search_result.jsp";
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
resUrl = "/res/error.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(resUrl);
dispatcher.forward(request, response);
}
}
package memver.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import member.dto.MemberDTO;
import member.exception.DuplicatedIdException;
import member.exception.DuplicatedRegisterNumberException;
import member.model.dao.MemberDAO;
public class MemberManageService {
//회원 관리 비지니스 로직을 처리하는 Business Service 클래스
private static MemberManageService instance = new MemberManageService();
private MemberDAO dao;
private MemberManageService(){
dao = MemberDAO.getInstance();
}
public static MemberManageService getInstance(){
return instance;
}
//가입 처리 메소드
public void registerMember(MemberDTO mto)throws SQLException, DuplicatedIdException, DuplicatedRegisterNumberException{
//1. 등록된 ID가 있는 지 체크
// - 이미 등록된 ID라면 DuplicatedIdException를 발생시킨다.
if(dao.selectMemberById(mto.getId())!=null){
throw new DuplicatedIdException(mto.getId()+"는 이미등록된 아이디 입니다.");
}
//2. 등록된 주민번호가 있는 지 체크
// - 이미 등록된 주민번호라면 DuplicatedRegisterNumberException 발생시킨다.
if(dao.selectMemberByregisterNumber(mto.getRegisterNumber1(), mto.getRegisterNumber2())!=null){
throw new DuplicatedRegisterNumberException("는 이미 가입된 주민번호 입니다.");
}
//3. 디비에 회원정보 등록 처리
dao.insertMember(mto);
}
// 전체 회원 목록 조회
public ArrayList<MemberDTO> getMemberList() throws SQLException{
return dao.selectAllMember();
}
//마일리지 범위로 조회
public ArrayList<MemberDTO> selectMemberByMileageRange(int startMileage, int endMileage)throws SQLException {
return dao.selectMemberByMileageRange(startMileage, endMileage);
}
}
* 결과보기
* 쿼리에서 문자열 더하고 넣는 방법.
select * from member where name like '%'||?||'%';
pstmt.setString(1,name);
"a"+"b"
'a'||'b'
-> 주말에 위에것 사용해서 이름으로 모든 정보 조회하기 해보기!
* 로그인 처리
login_form.jsp
-> LoginServlet - Business Logic처리, session처리
->Service.getMemberById(String id) : MemberDTO
->DAO.selectMemberbyId(String id) : MemberDTO
응답 : login_success.jsp(로그인 성공) login_form.jsp(실패)
error.jsp(exception)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${sessionScope.memberDTO != null }">
<jsp:forward page="/res/member_details.jsp"/>
</c:if>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<c:if test="${requestScope.error_message!=null }">
<font color="red">${requestScope.error_message }</font>
</c:if>
<body>
<jsp:include page="/menu.jsp"/>
<form action="/${initParam.context_root }/login" method="post">
<table>
<tr>
<td><h2>로그인</h2><p></td>
</tr>
<tr>
<td>id</td><td><input type="text" name="id"></td>
</tr>
<tr>
<td>password</td><td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="로그인"><input type="reset" value="초기화"></td>
</tr>
</table>
</form>
</body>
</html>
package member.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 요청파라미터 조회
String id = request.getParameter("id");
String password = request.getParameter("password");
//서비스 instance 받아오기
MemberManageService memberManageService = MemberManageService.getInstance();
HttpSession httpSession = request.getSession();
String resUrl = null;
try {
MemberDTO mto = memberManageService.getMemberById(id);
//아이디가 맞는 경우
if(mto!=null){
//아이디가 맞고 비밀번호도 맞는 경우
if(mto.getPassword().equals(password)){
//세션으로 로그인 정보 넘기기
httpSession.setAttribute("memberDTO", mto);
resUrl = "/res/login_success.jsp";
}
else{//아이디는 맞고 비밀번호는 틀린경우
resUrl = "/login_form.jsp";
request.setAttribute("error_message", "비밀번호가 틀립니다.");
}
}else{//아이디도 틀리고 비밀번호도 틀린경우
resUrl = "/login_form.jsp";
request.setAttribute("error_message", "아이디가 틀립니다.");
}
} catch (SQLException e) {
e.printStackTrace();
resUrl = "/res/error.jsp";
request.setAttribute("error_message", e.getMessage());
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher(resUrl);
requestDispatcher.forward(request, response);
}
}
<%@page import="member.dto.MemberDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="/menu.jsp"/>
${sessionScope.memberDTO.id } 님환영합니다.<p>
이름 : ${sessionScope.memberDTO.name }<br>
패스워드 : ${sessionScope.memberDTO.password }<br>
주민번호 : ${sessionScope.memberDTO.registerNumber1 }-${sessionScope.memberDTO.registerNumber2 }<br>
마일리지 : ${sessionScope.memberDTO.mileage }<br>
<a href='/${initParam.context_root }/logout'>로그아웃</a>
<a href='/${initParam.context_root }/getMemberInfo'>회원정보조회(로그인한 회원의 정보)</a>
<!--<input type="button" value="회원정보조회" onClick="location.href='/${initParam.context_root }/getMemberInfo'"> -->
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="/menu.jsp"/>
<c:if test="${requestScope.error_message!=null }">
실행 도중 오류가 발생했습니다.<br>
오류 내용 ${error_message }
</c:if>
<a href='/${initParam.context_root }/index.jsp'>메인페이지로 이동</a>
</body>
</html>
* 결과
'프로그래밍 > JSP Programming' 카테고리의 다른 글
2012-5-13 MVC를 활용한 회원관리 전체 소스 (0) | 2012.05.13 |
---|---|
2012-5-13 MVC패턴을 활용한 이름으로 회원 조회하기(like 사용) (0) | 2012.05.13 |
2012-5-10 Connection Pool - BasicDataSource (0) | 2012.05.10 |
2012-5-10 Connection Pool과 DataSource (0) | 2012.05.10 |
2012-5-10 MVC를 이용한 회원 등록하기 (0) | 2012.05.10 |