package member.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.ForwardDTO;
//모든 Controller 클래스의 type이 되는 interface
// 컨트롤러 로직 처리 메소드를 선언
public interface Controller {
public ForwardDTO execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
package member.controller;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class GetAllMemberInfoController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
MemberManageService memberManageService = MemberManageService.getInstance();
ForwardDTO forwardDTO = null;
try {
ArrayList<MemberDTO> list = memberManageService.getMemberList();
request.setAttribute("member_list", list);
forwardDTO = new ForwardDTO("/member_list.jsp", false);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/res/error.jsp", false);
}
return forwardDTO;
}
}
package member.controller;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class LoginController implements Controller{
public ForwardDTO execute(HttpServletRequest request,HttpServletResponse response) throws Exception{
//1. 요청파라미터 조회
String id = request.getParameter("id");
String password = request.getParameter("password");
//서비스 instance 받아오기
MemberManageService memberManageService = MemberManageService.getInstance();
ForwardDTO forwardDTO = null;
try {
MemberDTO mto = memberManageService.getMemberById(id);
//아이디가 맞는 경우
if(mto!=null){
//아이디가 맞고 비밀번호도 맞는 경우
if(mto.getPassword().equals(password)){
//세션으로 로그인 정보 넘기기
HttpSession httpSession = request.getSession();
httpSession.setAttribute("memberDTO", mto);
forwardDTO = new ForwardDTO("/res/login_success.jsp", false);
}
else{//아이디는 맞고 비밀번호는 틀린경우
request.setAttribute("error_message", "비밀번호가 틀립니다.");
forwardDTO = new ForwardDTO("/login_form.jsp", false);
}
}else{//아이디도 틀리고 비밀번호도 틀린경우
request.setAttribute("error_message", "아이디가 틀립니다.");
forwardDTO = new ForwardDTO("/login_form.jsp", false);
}
} catch (SQLException e) {
e.printStackTrace();
forwardDTO = new ForwardDTO( "/res/error.jsp", false);
request.setAttribute("error_message", e.getMessage());
}
return forwardDTO;
}
}
package member.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
public class LogoutController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
//로그인 여부 체크
MemberDTO memberDTO = (MemberDTO) session.getAttribute("memberDTO");
if (memberDTO != null) {
session.invalidate(); //세션을 지우기
} else {
request.setAttribute("error_message", "먼저 로그인 해주세요");
}
return new ForwardDTO("/login_form.jsp", false);
}
}
package member.controller;
import java.io.IOException;
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.ForwardDTO;
//FrontController 서블릿
public class MemberFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public MemberFrontController() {
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 {
//Controller 수행 전 작업(공통) - 한글처리
request.setCharacterEncoding("utf-8");
//Controller 로직 처리 - Controller 로직 호출
String command = request.getParameter("command");//클라이언트가 어떤 요청을 했는지 조회
System.out.println(command);
Controller controller = null;
if(command.equals("login")){
controller = new LoginController();
}else if(command.equals("logout")){
controller = new LogoutController();
}else if(command.equals("member_list")){
controller = new GetAllMemberInfoController();
}else if(command.equals("register_member")){
controller = new RegisterMemberController();
}else if(command.equals("modify_member_list")){
controller = new ModifyFormController();
}else if(command.equals("member_modify")){
controller = new ModifyMemberController();
}else if(command.equals("member_remove")){
controller = new RemoveMemberController();
}else if(command.equals("member_search")){
controller = new SearchByMileageRangeController();
}else if(command.equals("searchMemberByName")){
controller = new SearchByMemberName();
}
ForwardDTO forwardDTO = null;
try {
forwardDTO = controller.execute(request, response);
} catch (Exception e) {
e.printStackTrace();
forwardDTO = new ForwardDTO("/res/error.jsp", false);
}
//Controller 수행 후 작업(공통) - 응답(View로 수행 이동)
if(forwardDTO.isRedirect()){
response.sendRedirect(forwardDTO.getUrl());
}else{
RequestDispatcher requestDispatcher = request.getRequestDispatcher(forwardDTO.getUrl());
requestDispatcher.forward(request, response);
}
}
}
package member.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
public class ModifyFormController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession httpSession = request.getSession();
MemberDTO memberDTO = (MemberDTO) httpSession.getAttribute("memberDTO");
ForwardDTO forwardDTO = null;
if(memberDTO==null){
httpSession.setAttribute("error_message", "로그인 정보가 없습니다");
forwardDTO = new ForwardDTO("/login_form.jsp", false);
}else{
forwardDTO = new ForwardDTO( "/res/modify_form.jsp", false);
}
return forwardDTO;
}
}
package member.controller;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class ModifyMemberController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession httpSession = request.getSession();
MemberDTO login_info = (MemberDTO) httpSession.getAttribute("memberDTO");
ForwardDTO forwardDTO = null;
if(login_info!= null){//로그인이 된 경우
try {
MemberManageService memberManageService = MemberManageService.getInstance();
MemberDTO mdto = (MemberDTO) request.getAttribute("mdto");
//update 시 오류가 날수 있기 때문에 DB를 먼저 update 하고 session의 값을 바꿔 줘야 한다.
memberManageService.modifyMember(mdto);
mdto.setMileage(login_info.getMileage());
httpSession.setAttribute("memberDTO", mdto);
forwardDTO = new ForwardDTO("/res/member_details.jsp", false);
} catch (SQLException e) {//예외 에러
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/res/error.jsp", false);
}
}else{//로그인이 안 된경우
request.setAttribute("error_message", "로그인 부터 해주세요.");
forwardDTO = new ForwardDTO("/login_form.jsp", false);
}
return forwardDTO;
}
}
package member.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class RegisterMemberController implements Controller{
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//1.요청파라미터 조회
MemberDTO mdto = (MemberDTO)request.getAttribute("mdto");
mdto.setMileage(1000);
//2. Business Logic 처리 - MemberManageService.registerMember()
MemberManageService memberManageService = MemberManageService.getInstance();
ForwardDTO forwardDTO = null;
try {
memberManageService.registerMember(mdto);
forwardDTO = new ForwardDTO("/res/register_success.jsp", false);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/res/error.jsp", false);
}
return forwardDTO;
}
}
package member.controller;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class RemoveMemberController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession httpSession = request.getSession();
MemberDTO memberDTO = (MemberDTO) httpSession.getAttribute("memberDTO");
System.out.println("*****************"+memberDTO);
MemberManageService memberManageService = MemberManageService.getInstance();
ForwardDTO forwardDTO = null;
if (memberDTO != null) {
try {
memberManageService.removeMemberById(memberDTO.getId());
httpSession.invalidate();
forwardDTO = new ForwardDTO("/login_form.jsp", false);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/res/error.jsp", false);
}
} else {
request.setAttribute("error_message", "로그인 정보가 없습니다.");
forwardDTO = new ForwardDTO("/login_form.jsp", false);
}
return forwardDTO;
}
}
package member.controller;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class SearchByMemberName implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//1.한글처리
request.setCharacterEncoding("utf-8");
//2. 요청파라미터 받기
String name = null;
ArrayList<MemberDTO> list = new ArrayList<MemberDTO>();
ForwardDTO forwardDTO = null;
try{
name = request.getParameter("name");
}catch(NullPointerException e){
request.setAttribute("error_message", e.getMessage()+"조회할 이름을 입력해 주세요.");
forwardDTO = new ForwardDTO("/search_form.jsp", false);
return forwardDTO;
}
try{
MemberManageService memberManageService = MemberManageService.getInstance();
list = memberManageService.getSearchByMemberName(name);
request.setAttribute("searchList", list);
request.setAttribute("title", "이름으로 조회 결과");
request.setAttribute("search_value", name);
forwardDTO = new ForwardDTO("/res/search_result.jsp", false);
}catch(SQLException e){
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO( "/res/error.jsp", false);
}
return forwardDTO;
}
}
package member.controller;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.ForwardDTO;
import member.dto.MemberDTO;
import memver.model.service.MemberManageService;
public class SearchByMileageRangeController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws Exception {
int startMileage = 0;
int endMileage = 0;
MemberManageService memberManageService = MemberManageService.getInstance();
ArrayList<MemberDTO> list;
ForwardDTO forwardDTO = 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()+"숫자를 넣어주세요");
forwardDTO = new ForwardDTO("/search_form.jsp", false);
return forwardDTO;
}
try {
list = memberManageService.selectMemberByMileageRange(startMileage,endMileage);
request.setAttribute("searchList", list);
request.setAttribute("title", "마일리지 범위로 조회 결과");
request.setAttribute("search_value", startMileage+"~"+endMileage);
forwardDTO = new ForwardDTO("/res/search_result.jsp", false);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO( "/res/error.jsp", false);
}
return forwardDTO;
}
}
* DTO
package member.dto;
//url값을 가지고 있는 DTO
public class ForwardDTO {
private String url;
private boolean redirect;//true-리다이렉트, false - 요청디스패치
public ForwardDTO() {
super();
// TODO Auto-generated constructor stub
}
public ForwardDTO(String url, boolean redirect) {
super();
this.url = url;
this.redirect = redirect;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isRedirect() {
return redirect;
}
public void setRedirect(boolean redirect) {
this.redirect = redirect;
}
@Override
public String toString() {
return "ForwardDTO [url=" + url + ", redirect=" + redirect + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (redirect ? 1231 : 1237);
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ForwardDTO other = (ForwardDTO) obj;
if (redirect != other.redirect)
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
}
}
package member.dto;
public class MemberDTO {
private String id;
private String password;
private String name;
private String registerNumber1;
private String registerNumber2;
private int mileage;
public MemberDTO() {
super();
}
public MemberDTO(String id, String password, String name,
String registerNumber1, String registerNumber2, int mileage) {
super();
this.id = id;
this.password = password;
this.name = name;
this.registerNumber1 = registerNumber1;
this.registerNumber2 = registerNumber2;
this.mileage = mileage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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 getRegisterNumber1() {
return registerNumber1;
}
public void setRegisterNumber1(String registerNumber1) {
this.registerNumber1 = registerNumber1;
}
public String getRegisterNumber2() {
return registerNumber2;
}
public void setRegisterNumber2(String registerNumber2) {
this.registerNumber2 = registerNumber2;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
@Override
public String toString() {
return "MemberDTO [id=" + id + ", password=" + password + ", name="
+ name + ", registerNumber1=" + registerNumber1
+ ", registerNumber2=" + registerNumber2 + ", mileage="
+ mileage + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + mileage;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((password == null) ? 0 : password.hashCode());
result = prime * result
+ ((registerNumber1 == null) ? 0 : registerNumber1.hashCode());
result = prime * result
+ ((registerNumber2 == null) ? 0 : registerNumber2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MemberDTO other = (MemberDTO) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (mileage != other.mileage)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (registerNumber1 == null) {
if (other.registerNumber1 != null)
return false;
} else if (!registerNumber1.equals(other.registerNumber1))
return false;
if (registerNumber2 == null) {
if (other.registerNumber2 != null)
return false;
} else if (!registerNumber2.equals(other.registerNumber2))
return false;
return true;
}
}
* exception
package member.exception;
public class DuplicatedIdException extends Exception{
public DuplicatedIdException(){}
public DuplicatedIdException(String message){
super(message);
}
}
package member.exception;
public class DuplicatedRegisterNumberException extends Exception{
public DuplicatedRegisterNumberException(){}
public DuplicatedRegisterNumberException(String message){
super(message);
}
}
*DAO
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;
}
public void updateMember(MemberDTO mto) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update member set password=?, name=?, register_Number1=?, register_number2=? where id=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, mto.getPassword());
pstmt.setString(2, mto.getName());
pstmt.setString(3, mto.getRegisterNumber1());
pstmt.setString(4, mto.getRegisterNumber2());
pstmt.setString(5, mto.getId());
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(pstmt, conn);
}
}
public void deleteMemberById(String id) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "delete from member where id=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 삭제되었습니다.");
}finally{
dbUtil.close(pstmt, conn);
}
}
public ArrayList<MemberDTO> searchByMemberName(String name) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList<MemberDTO> list = new ArrayList<MemberDTO>();
String sql = "select id, password, name, register_number1, register_number2, mileage from member where name like '%'||?||'%'";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
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;
}
}
* util
package member.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
//디비 관련과 커넥션을 만들어 놓은 클래스
//싱글톤 패턴을 사용해서 커넥션이 한번만 되도록 설정.
public class DatabaseUtility {
//싱글톤 패턴 - 생성자에서 DataSource객체를 생성해서 instance변수에 할당.
private BasicDataSource dataSource;
private static DatabaseUtility instance = new DatabaseUtility();
private DatabaseUtility(){
dataSource = new BasicDataSource();//객체 생성
//프라퍼티 설정
//1. 연결할 DB와 관련된 설정
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");//BasicDataSource를 사용하면 따로 드라이버 로딩을 해줄 필요가 없다. 바로 처리가능
dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:XE");
dataSource.setUsername("scott");
dataSource.setPassword("tiger");
}
public static DatabaseUtility getInstance(){
return instance;
}
public BasicDataSource getDataSource(){//커넥션을 가져갈 수 있도록 만듬.
return dataSource;
}
public void close(Statement stmt, Connection conn){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void close(ResultSet rset, Statement stmt, Connection conn){
if(rset!=null){
try {
rset.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
* service
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);
}
//ID로 회원 목록조회
public MemberDTO getMemberById(String id) throws SQLException{
return dao.selectMemberById(id);
}
public void modifyMember(MemberDTO mto) throws SQLException{
dao.updateMember(mto);
}
public void removeMemberById(String id)throws SQLException {
dao.deleteMemberById(id);
}
public ArrayList<MemberDTO> getSearchByMemberName(String name) throws SQLException{
return dao.searchByMemberName(name);
}
}
* res
<%@ 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>
<%@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 }/controller?command=logout'>로그아웃</a>
<a href='/${initParam.context_root }/controller?command=modify_member_list'>회원정보조회(로그인한 회원의 정보)</a>
<!--<input type="button" value="회원정보조회" onClick="location.href='/${initParam.context_root }/getMemberInfo'"> -->
</body>
</html>
<%@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><p>
아이디 : ${sessionScope.memberDTO.id }<br>
이름 : ${sessionScope.memberDTO.name }<br>
주민번호 : ${sessionScope.memberDTO.registerNumber1 }-${sessionScope.memberDTO.registerNumber2 }<br>
마일리지 : ${sessionScope.memberDTO.mileage }<br>
<p>
<a href="/${initParam.context_root }/res/modify_form.jsp">회원정보수정</a>
<a href="/${initParam.context_root }/controller?command=member_remove">회원 탈퇴</a>
</p>
</body>
</html>
<%@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><hr><p>
<form action="/${initParam.context_root }/forward.jsp" method="post">
<input type="hidden" name="command" value="member_modify">
<input type="hidden" name="id" value="${sessionScope.memberDTO.id }">
<table width="500">
<tr>
<td>아이디</td><td>${sessionScope.memberDTO.id }</td>
</tr>
<tr>
<td>비밀번호</td><td><input type="text" name="password"></td>
</tr>
<tr>
<td>이름</td><td><input type="text" name="name" value="${sessionScope.memberDTO.name }"></td>
</tr>
<tr>
<td>주민번호</td><td><input type="text" name="registerNumber1" value="${sessionScope.memberDTO.registerNumber1 }">-<input type="text" name="registerNumber2" value="${sessionScope.memberDTO.registerNumber2 }"></td>
</tr>
<tr>
<td>마일리지 ${sessionScope.memberDTO.mileage }</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="정보수정"><input type="reset" value="다시작성"></td>
</tr>
</table>
</form>
</body>
</html>
<%@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><hr><p>
아이디 : ${sessionScope.memberDTO.id }<br>
비밀번호 : ${sessionScope.memberDTO.password }<br>
이름 : ${sessionScope.memberDTO.name }<br>
주민번호 : ${sessionScope.memberDTO.registerNumber }<br>
마일리지 : ${sessionScope.memberDTO.mileage }<br>
</body>
</html>
<%@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>
<%@ 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.searchList }" 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>
* WEB-INF
create table member(
id varchar2(10),
password varchar2(10) not null,
name varchar2(50) not null,
register_number varchar2(13) not null,
mileage number,
constraint member_pk primary key(id)
)
select id, password, name, register_number1, register_number2, mileage from member where name like '%'||?||'%'"
select * from member where id='1111';
delete from member where id='1111';
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<context-param>
<param-name>context_root</param-name>
<param-value>member_servlet_fc</param-value>
</context-param>
<display-name>member_servlet_fc</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>
<description></description>
<display-name>MemberFrontController</display-name>
<servlet-name>MemberFrontController</servlet-name>
<servlet-class>member.controller.MemberFrontController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MemberFrontController</servlet-name>
<url-pattern>/controller</url-pattern>
</servlet-mapping>
</web-app>
* WebContent
<%@page import="member.dto.MemberDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("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="/controller"/>
<body>
</body>
</html>
<%@ 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 }/controller?command=member_list'>전체 회원 조회</a>
</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"%>
<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><br>
<body>
<jsp:include page="/menu.jsp"/>
<form action="/${initParam.context_root }/controller" method="post">
<input type="hidden" name="command" value="login">
<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>
<%@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>
<%@ 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 }/controller?command=logout'>로그아웃</a>
<a href="/${initParam.context_root }/controller?command=modify_member_list">회원정보조회</a>
<a href="/${initParam.context_root }/res/modify_form.jsp">회원정보 수정</a>
<a href="/${initParam.context_root }/controller?command=member_remove">회원 탈퇴</a>
</c:otherwise>
</c:choose>
<a href="/${initParam.context_root }/controller?command=member_list">전체 회원정보 조회</a>
<hr width="700" align="left" noshade="noshade">
<%@ 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"/>
<form action="/${initParam.context_root }/forward.jsp" method="post">
<input type="hidden" name="command" value="register_member">
<table border="1">
<tr>
<td align="center">id</td><td><input type="text" name="id" maxlength="10" size="10"></td>
</tr>
<tr>
<td align="center">pwd</td><td><input type="password" name="password" maxlength="4" size="4"></td>
</tr>
<tr>
<td align="center">이름 : </td><td><input type="text" name="name" maxlength="10" size="10"></td>
</tr>
<tr>
<td align="center">주민번호 : </td>
<td>
<input type="text" name="registerNumber1" maxlength="6" size="6">-
<input type="text" name="registerNumber2" maxlength="7" size="7">
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="가입">
<input type="reset" value="다시작성"></td>
</tr>
</table>
</form>
</body>
</html>
<%@ 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 }/controller?command=member_search" method="post">
범위 : <input type = "text" name="startMileage">~<input type = "text" name="endMileage">
<input type="submit" value="검색">
</form>
<br>
<form action="/${initParam.context_root }/controller" method="post">
이름 : <input type="text" name="name">
<input type="submit" value="이름으로 검색">
<input type="hidden" name="command" value="searchMemberByName">
</form>
</body>
</html>
* 결과보기
* 전체소스(내꺼)
강사님 소스
* ControllerCommandMapping 만들기
package member.controller;
import java.io.IOException;
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.ForwardDTO;
//FrontController 서블릿
public class MemberFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public MemberFrontController() {
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 {
//Controller 수행 전 작업(공통) - 한글처리
request.setCharacterEncoding("utf-8");
//Controller 로직 처리 - Controller 로직 호출
String command = request.getParameter("command");//클라이언트가 어떤 요청을 했는지 조회
System.out.println(command);
Controller controller = ControllerCommandMapping.getController(command);
ForwardDTO forwardDTO = null;
try {
forwardDTO = controller.execute(request, response);
} catch (Exception e) {
e.printStackTrace();
forwardDTO = new ForwardDTO("/res/error.jsp", false);
}
//Controller 수행 후 작업(공통) - 응답(View로 수행 이동)
if(forwardDTO.isRedirect()){
response.sendRedirect(forwardDTO.getUrl());
}else{
RequestDispatcher requestDispatcher = request.getRequestDispatcher(forwardDTO.getUrl());
requestDispatcher.forward(request, response);
}
}
}
package member.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller controller = null;
if(command.equals("login")){
controller = new LoginController();
}else if(command.equals("logout")){
controller = new LogoutController();
}else if(command.equals("member_list")){
controller = new GetAllMemberInfoController();
}else if(command.equals("register_member")){
controller = new RegisterMemberController();
}else if(command.equals("modify_member_list")){
controller = new ModifyFormController();
}else if(command.equals("member_modify")){
controller = new ModifyMemberController();
}else if(command.equals("member_remove")){
controller = new RemoveMemberController();
}else if(command.equals("member_search")){
controller = new SearchByMileageRangeController();
}else if(command.equals("searchMemberByName")){
controller = new SearchByMemberName();
}
return controller;
}
}
'프로그래밍 > JSP Programming' 카테고리의 다른 글
2012-5-15 Oracle Sequence (0) | 2012.05.15 |
---|---|
2012-5-15 MVC를 활용한 게시판만들기 (0) | 2012.05.15 |
2012-5-14 FrontController 패턴 (0) | 2012.05.14 |
2012-5-14 MVC모델을 활용한 회원정보 수정,삭제 (0) | 2012.05.14 |
2012-5-13 MVC를 활용한 회원관리 전체 소스 (0) | 2012.05.13 |