본문 바로가기
JSP Servlet

회원관리 MVC2+HandlerMapping+JSTL

by noddu 2021. 2. 8.
728x90
반응형

 

기존의 MVC 2에서 HandlerMapping할 파일 새로만들기, JSTL사용

 

HashMap - key와 value를 쌍으로 묶어 저장(검색이 빠른게 특징)

 

-DataBase-

create table memiot(
	num number primary key,
	id varchar2(20) not null,
	pass varchar2(20) not null,
	mname varchar2(20) not null,
	mage number(3),
	memail varchar2(50),
mtel varchar2(20)
);

create sequence num_seq;

insert into MEMIOT
values(num_seq.nextval,'admin','admin','관리자',40,'admin@naver.com','010-9999-1000');

select * from memiot;

-Controller(interface)-

●Controller.java

public interface Controller {
 	public String requestHandler(HttpServletRequest request,HttpServletResponse response)
 		throws ServletException, IOException;
}

메소드가필요, 이름을같게하기위해  통일된 메소드를 interface로만들기 - (FrontController 대신해주는역할)

requestHandler  -  FrontController에서 요청이오면 처리하는 메소드라고 표현(다른이름도있음)

url이니까 리턴타입은 String이다,  interface도 String타입으로 하기

 

 


-HandlerMapping-

public class HandlerMapping {
	private HashMap<String, Controller> mappings;
	public HandlerMapping() {
		mappings=new HashMap<String, Controller>();
		setkeyValue();
	}
	public void setkeyValue() {
		//xml,properties파일??
		mappings.put("/list.do", new MemListController());
		mappings.put("/insertForm.do", new MemInsertFormController());
		mappings.put("/insert.do", new MemInsertController());
		mappings.put("/delete.do", new MemDeleteController());
		mappings.put("/content.do", new MemContentController());
		mappings.put("/update.do", new MemUpdateController());
		//mappings.put("/login.do", new MemLoginController());
	}
	public Controller getController(String key) {
		return mappings.get(key);
	}
}

◆HashMap< ? , ? > - Generic타입 - 클래스에서 사용할타입을 외부에서 설정 

key - String(경로니까) , value - Controller(타입)을 넣는다

 

◆setkeyValue에 String(경로)와 Controller들을 등록한다.

 

◆key가 넘어오면 value를 리턴하기위해 String key를 매개변수로 하고

Controller타입의 mappings.get(key)를 리턴하는 메소드 만든다


-Controller(FrontController)-

●MemberFrontController.java

@WebServlet("*.do")
public class MemberFrontController extends HttpServlet {
	protected void service(HttpServletRequest request,
 		HttpServletResponse response)
 			throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	//1. 클라이언트의 요청을 확인하는 작업(요청URL=command)
	String reqUrl=request.getRequestURI();
	//System.out.println(reqUrl);
	String cpath=request.getContextPath();
	//System.out.println(cpath);
	String command=reqUrl.substring(cpath.length());
	System.out.println(command);

// 2. 해당요청에 따른(command) 분기작업(if~else~)
MemberDAO dao=new MemberDAOImpl();
Controller controller=null;
String nextPage=null;

// HandlerMapping ******
HandlerMapping mappings = new HandlerMapping(); //HandlerMapping 객체생성
controller = mappings.getController(command); // controller가 null이라서

// nextPage를 보고 분기작업을 진행
if(controller!=null) {
			nextPage=controller.requestHandler(request, response);
		if(nextPage!=null) {
			if(nextPage.indexOf("redirect:")!=-1) {
			response.sendRedirect(nextPage.split(":")[1]);
			//String[]sp=nextPage.split(":");
			//response.sendRedirect(sp[1]);
		}else {
			RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/member/"+nextPage+".jsp");
			rd.forward(request, response);
			}//	
		}//
	}//
  }
}

1.클라이언트의 요청을 확인하는 작업(요청URL = command)

           (클라이언트에서 요청URL뒤에 command패턴(ex)mode=list)하는 방법도있음)

 

String reqURL=request.getRequestURI(); - :8081뒤의 url찍어내기

String cpath = request.getContextPath(); - MVC02찍어내기
String command = reqURI.substring(capth.lenght()); - URL 에서 MVC02의 길이만큼 substring, 그 뒤에만 찍어내기

                                                                                                                                                             ex) /memList.do라고 나오게

 

 

2. 해당요청에(command)따른 분기작업(if~else~)하기

★HandlerMapping 객체 생성,  해당요청(command)하면 요청한 controller받아와서 get controller

 

 

★HandlerMapping  -  key -> value ▼

                                         쌍으로 저장할수있는 자료구조 = Hashmap

 

 

분기작업 ▼

 

controller가 !=null이면 nextPage를 controller.requestHanlder하게 한다(중복된 부분없애기위해)

 

 

nextPage를 forward방식으로할 controller와 redirect방식으로할 controller를 구분해야함

 

 

if(nextPage!=null)이면서 if nextPage.index("redirect:)!=-1  <= redirect:라는 문자가 있으면

                                                                               redirect로 되게한다음

                                            String  split으로 : 부분 자른다음  [1]번째부터 시작해서 경로가되게,

 

                                                  else면 forward로 되게

 

 

+nextPage+ 에 접두사와 접미사를 붙여놔서 유지보수에 용이하게 만든다

 


-Controller(POJO)-

POJO contoller(action)에는 Servlet이 아닌 POJO(일반Java)를 넣는다

 

●MemListController.java

public class MemListController implements Controller{
@Override
	public String requestHandler(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
// /list.do
// 1. Model연동
MemberDAO dao=new MemberDAOImpl();
List<MemberVO> list=dao.memberList();

// 2. 객체바인딩
request.setAttribute("list", list); // 객체바인딩(request)

// 3. FrontController에게 다음페이지가 어떤페이지인지 페이지 정보를 리턴
String nextPage="list";
return nextPage;
	}
}

nextPage가 어딘지 지정한다

 

●MemInsertFormController.java

public class MemInsertFormController implements Controller{
@Override
	public String requestHandler(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	//String nextPage="WEB-INF/member/insertForm.jsp";
	return "insertForm";
	}
}

return 을 경로로안하고(경로가 바뀌면 유지보수 힘들어짐)

-> insertForm이름만 놔두고 FrontController에 접두사 접미사를 붙여서 유지보수 용이하게

●MemInsertController.java

public class MemInsertController implements Controller{
@Override
	public String requestHandler(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
        
String cpath=request.getContextPath();
MemberDAO dao=new MemberDAOImpl();

String id=request.getParameter("id");
String pass=request.getParameter("pass");
String mname=request.getParameter("mname");
int mage=Integer.parseInt(request.getParameter("mage")); // "111"->111
String memail=request.getParameter("memail");
String mtel=request.getParameter("mtel");
MemberVO vo=new MemberVO(id, pass, mname, mage, memail, mtel);
int cnt=dao.memberInsert(vo);

// 저장성공 후 리스트페이지로... 
String nextPage=null;
if(cnt>0) {
	nextPage="redirect:"+cpath+"/list.do";
}else {
	throw new ServletException("error");
}
	return nextPage;
	}
}

insert성공하면 마찬가지로 nextPage가 어딘지 지정한다

nextPage가 redirect인 경우에 redirect : 이라고 적기(FrontController에서 유지보수위해)

 

 

 

●MemDeleteController.java

public class MemDeleteController implements Controller{
@Override
public String requestHandler(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
    
	String cpath=request.getContextPath(); // /MVC02

MemberDAO dao=new MemberDAOImpl();
int num=Integer.parseInt(request.getParameter("num"));
int cnt=dao.memberDelete(num);
String nextPage=null;
if(cnt > 0) {
	nextPage="redirect:"+cpath+"/list.do"; // redirect
 }else {
 	throw new ServletException("error");
 }
	return nextPage;
	}
}

nextPage가 redirect인 경우에 redirect : 이라고 적기(FrontController에서 유지보수위해)

 

 

●MemContentController.java

public class MemContentController implements Controller{
@Override
public String requestHandler(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
        
	MemberDAO dao=new MemberDAOImpl();
	int num = Integer.parseInt(request.getParameter("num"));
	MemberVO vo=dao.memberContent(num);
    
	request.setAttribute("vo", vo);
	// "WEB-INF/member/content.jsp"
	return "content"; // forward
	}
}

return 을 경로로안하고(경로가 바뀌면 유지보수 힘들어짐)

-> content이름만 놔두고 FrontController에 접두사 접미사를 붙여서 유지보수 용이하게

 

●MemUpdateController.java

public class MemUpdateController implements Controller{
@Override
public String requestHandler(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	String cpath=request.getContextPath();

 	MemberDAO dao=new MemberDAOImpl();
 	int num = Integer.parseInt(request.getParameter("num"));
 	int mage = Integer.parseInt(request.getParameter("mage"));
 	String memail = request.getParameter("memail");
 	String mtel = request.getParameter("mtel");

 	MemberVO vo = new MemberVO();
	vo.setNum(num);
	vo.setMemail(memail);
 	vo.setMtel(mtel);
 	vo.setMage(mage);

 int cnt=dao.memberUpdate(vo);
 String nextPage=null;
 if(cnt>0) {
 	nextPage="redirect:"+cpath+"/list.do";
 }else {
 	throw new ServletException("error");
 }
 	 return nextPage;
	}
}

nextPage가 redirect인 경우에 redirect : 이라고 적기(FrontController에서 유지보수위해)

 

 


-Model-

 

●MemberDAO.java(interface)

public interface MemberDAO {
 public List<MemberVO> memberList(); // 회원전체리스트
 public int memberInsert(MemberVO vo); // 회원가입
 public int memberDelete(int num); // 회원삭제
 public MemberVO memberContent(int num); // 회원1명의 정보가져오기
 public int memberUpdate(MemberVO vo); // 회원정보수정
}

 

 

 

●MemberDAOImpl.java

public class MemberDAOImpl implements MemberDAO{
 	private Connection conn;
 	private PreparedStatement ps;
	 private ResultSet rs;
 	//CRUD
   public void getConnect() {
 		String url="jdbc:oracle:thin:@127.0.0.1:1521:XE";
 		String user="hr";
		String password="hr";
         
 		try {
        		Class.forName("oracle.jdbc.driver.OracleDriver");
			conn=DriverManager.getConnection(url, user, password);
 		} catch (Exception e) {
			e.printStackTrace();
 		}
 }//
 public void dbClose() {
 	try {
 		if(rs!=null) rs.close();
 		if(ps!=null) ps.close();
 		if(conn!=null) conn.close();
 	}catch(Exception e) {
 		e.printStackTrace();
 	}
 }//
	@Override
	public List<MemberVO> memberList() {
		// VO(묶고)->List(담고)
		String SQL="select * from memiot";
		List<MemberVO> list=new ArrayList<MemberVO>();
		getConnect(); // conn=
        
	try {
 		ps=conn.prepareStatement(SQL);
 		rs=ps.executeQuery(); // rs->커서(이동 : next())
        
 		while(rs.next()) {
 			int num=rs.getInt("num");
 			String id=rs.getString("id");
 			String pass=rs.getString("pass");
			String mname=rs.getString("mname");
 			int mage=rs.getInt("mage");
 			String memail=rs.getString("memail");
			 String mtel=rs.getString("mtel");
			 MemberVO vo=new MemberVO(num, id, pass, mname, mage, memail, mtel);
			list.add(vo);
	   }
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		dbClose();
	}
	return list;
}//

public int memberInsert(MemberVO vo) {

	String SQL="insert into memiot values(num_seq.nextval,?,?,?,?,?,?)";
	getConnect(); //conn
	int cnt=-1;// -1(실패, 끝)
	try {
 		ps=conn.prepareStatement(SQL);
 		ps.setString(1, vo.getId());
		 ps.setString(2, vo.getPass());
		 ps.setString(3, vo.getMname());
		 ps.setInt(4, vo.getMage());
 		ps.setString(5, vo.getMemail());
		 ps.setString(6, vo.getMtel());
		 cnt=ps.executeUpdate();//실행
	} catch (Exception e) {
			e.printStackTrace();
            } finally {
				dbClose();
			}
				return cnt;
}//

@Override
public int memberDelete(int num) {
	String SQL="delete from memiot where num = ?";
	getConnect();
	int cnt=-1;
	try {
 	ps=conn.prepareStatement(SQL);
 	ps.setInt(1, num);
 	cnt=ps.executeUpdate();
 	} catch (Exception e) {
		 e.printStackTrace();
 	} finally {
 		dbClose();
 	}
		return cnt;
}//

@Override
public MemberVO memberContent(int num) {
	String SQL = "select * from memiot where num = ?";
	getConnect();
	MemberVO vo=null;
	try {
 	ps=conn.prepareStatement(SQL);
 	ps.setInt(1, num);
 	rs=ps.executeQuery();
    
	if(rs.next()) {
 		num=rs.getInt("num");
 		String id=rs.getString("id");
 		String pass=rs.getString("pass");
		String mname=rs.getString("mname");
 		int mage=rs.getInt("mage");
 		String memail=rs.getString("memail");
 		String mtel=rs.getString("mtel");
 		vo=new MemberVO(num, id, pass, mname, mage, memail, mtel);
	 }
 } catch (Exception e) {
 		e.printStackTrace();
 } finally {
 		dbClose();
 }
return vo;
}//

@Override
public int memberUpdate(MemberVO vo) {
 	//수정
 	int cnt = -1; //실패의 의미로 -1 을 사용
 	String SQL = "UPDATE memiot SET mage=?, memail=?, mtel=? WHERE num=?";
 	getConnect();
    
 try {
		ps = conn.prepareStatement(SQL);
		ps.setInt(1, vo.getMage());
 		ps.setString(2, vo.getMemail());
		ps.setString(3, vo.getMtel());
 		ps.setInt(4, vo.getNum());
		 cnt = ps.executeUpdate(); //실행
 	 } catch(Exception e) {
		 e.printStackTrace();
	 } finally {
		 dbClose();
	 }
	 return cnt;
 	}
}

 

 

 

 

●MemberVO.java

public class MemberVO {
	private int num;
	private String id;
	private String pass;
	private String mname;
	private int mage;
	private String memail;
	private String mtel;
	public MemberVO(int num, String id, String pass, String mname,
 								int mage, String memail, String mtel) {
		super();
		this.num = num;
		this.id = id;
		this.pass = pass;
		this.mname = mname;
		this.mage = mage;
		this.memail = memail;
		this.mtel = mtel;
	}
    
public MemberVO(String id, String pass, String mname, int mage, String memail, String mtel) {
	super();
	this.id = id;
	this.pass = pass;
	this.mname = mname;
	this.mage = mage;
	this.memail = memail;
	this.mtel = mtel;
}
public MemberVO() { }

public int getNum() {
	return num;
}
public void setNum(int num) {
	this.num = num;
}
public String getId() {
	return id;
}
public void setId(String id) {
	this.id = id;
}
public String getPass() {
	return pass;
}
public void setPass(String pass) {
	this.pass = pass;
}
public String getMname() {
	return mname;
}
public void setMname(String mname) {
	this.mname = mname;
}
public int getMage() {
	return mage;
}
public void setMage(int mage) {
	this.mage = mage;
}
public String getMemail() {
	return memail;
}
public void setMemail(String memail) {
	this.memail = memail;
}
public String getMtel() {
	return mtel;
}
public void setMtel(String mtel) {
	this.mtel = mtel;
}

@Override
public String toString() {
		return "MemberVO [num=" + num + ", id=" + id + ", pass=" + pass + ", mname=" +
 		mname + ", mage=" + mage + ", memail=" + memail + ", mtel=" + mtel + "]";
	}
}

 

 


-View-

●JSP -> JSTL로 바꾸기

 

*클라이언트가 바로 view로가지못하게 인위적으로
경로를 WEB-INF(경비실)에 넣으면 view로접근불가
(Controller를 거쳐야만 가능하게)

 

 

표현언어(EL) =>  ${식} - (var, 연산자,... )
test=조건절

 

●list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.util.*" %>
<%@page import="kr.iot.model.*" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> 
<%
	 //String cpath = request.getContextPath();
     //List<MemberVO> list=(List<MemberVO>)request.getAttribute("list");
%>
<c:set var="cpath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Model 3</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{background-color:yellow; border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-baqh{text-align:center;vertical-align:top}
.tg .tg-lqy6{text-align:right;vertical-align:top}
.tg .tg-calz{background-color:#fe0000;font-weight:bold;text-align:center;vertical-align:top}
</style>
<script type="text/javascript">
  function insertForm(){
	 //alert("OK");
	 location.href="${cpath}/insertForm.do";
  }
  function deleteFn(num){
	  //alert(num);
	  location.href="${cpath}/delete.do?num="+num;
  }
</script>
</head>
<body>
☆★회원목록(MVC03 버전 : Frontcontroller + POJO + HandlerMapping-HashMap)★☆
<table class="table table-hover">
<colgroup>
<col style="width: 50px">
<col style="width: 118px">
<col style="width: 101px">
<col style="width: 104px">
<col style="width: 269px">
<col style="width: 157px">
<col style="width: 87px">
</colgroup>
<thead>
  <tr>
    <th class="tg-calz">번호</th>
    <th class="tg-calz">아이디</th>
    <th class="tg-calz">비밀번호</th>
    <th class="tg-calz">이름</th>
    <th class="tg-calz">이메일</th>
    <th class="tg-calz">전화번호</th>
    <th class="tg-calz">삭제</th>
  </tr>
</thead>
<tbody>
 <c:forEach var="vo" items="${list}">
  <tr>
    <td class="tg-baqh">${vo.num}</td>
    <td class="tg-baqh"><a href="${cpath}/content.do?num=${vo.num}">${vo.id}</a></td>
    <td class="tg-baqh">${vo.pass}</td>
    <td class="tg-baqh">${vo.mname}</td>
    <td class="tg-baqh">${vo.memail}</td>
    <td class="tg-baqh">${vo.mtel}</td>
    <td class="tg-baqh"><input type="button" onclick="deleteFn(${vo.num})" value="삭제" class="btn btn-danger"></td>
  </tr>
</c:forEach>
  <tr>
    <td class="tg-lqy6" colspan="7"><input type="button" onclick="insertForm()" value="회원가입" class="btn btn-success"></td>
  </tr>
</tbody>
</table>
</body>
</html>

 

 

●코어

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 

 

●insertForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> 
<%
   //String cpath=request.getContextPath();
%>    
<c:set var="cpath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<title>Insert title here</title>
<style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-baqh{background-color:orange; text-align:center;vertical-align:top}
.tg .tg-c3ow{background-color:skyblue;border-color:inherit;text-align:center;vertical-align:top}
.tg .tg-0pky{background-color:#cbcefb;border-color:inherit;text-align:left;vertical-align:top}
.tg .tg-0lax{background-color:#cbcefb;text-align:left;vertical-align:top}
</style>
</head>
<body>
<form action="${cpath}/insert.do" method="post">
<table class="table" style="undefined;table-layout: fixed; width: 522px">
<colgroup>
<col style="width: 116px">
<col style="width: 406px">
</colgroup>
<thead>
  <tr>  
    <th class="tg-c3ow">아이디</th>
    <th class="tg-0pky"><input type='text' name="id" /></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-c3ow">비밀번호</td>
    <td class="tg-0pky"><input type="password" name="pass"/></td>
  </tr>
  <tr>
    <td class="tg-c3ow">이름</td>
    <td class="tg-0pky"><input type='text' name="mname"/></td>
  </tr>
  <tr>
    <td class="tg-c3ow">나이</td>
    <td class="tg-0pky"><input type='text' name="mage"/></td>
  </tr>
  <tr>
    <td class="tg-c3ow">이메일</td>
    <td class="tg-0pky"><input type='text' name="memail"/></td>
  </tr>
  <tr>
    <td class="tg-baqh">전화번호</td>
    <td class="tg-0lax"><input type='text' name="mtel"/></td>
  </tr>
  <tr>
    <td class="tg-baqh" colspan="2">
      <input type="submit" value="회원가입" class="btn btn-primary"/>
      <input type="reset" value="취소" class="btn btn-danger"/>
    </td>
  </tr>
</body>
</table>
</form>
</body>
</html>

 

 

 

 

 

●content.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="kr.iot.model.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> 
<%
	//String cpath = request.getContextPath();
	//MemberVO vo = (MemberVO)request.getAttribute("vo");
%>    
<c:set var="cpath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<title>${vo.mname}의 상세보기</title>
<style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-baqh{text-align:center;vertical-align:top}
.tg .tg-fs2w{background-color:#cbcefb;font-weight:bold;text-align:center;vertical-align:top}
.tg .tg-0lax{text-align:left;vertical-align:top}
</style>
</head>
<body>
☆★${vo.mname}의 상세보기★☆
<form action="${cpath}/update.do" method="post">
<input type="hidden" name="num" value="${vo.num}"/>
<table class="table" style="undefined;table-layout: fixed; width: 552px">
<colgroup>
<col style="width: 107px">
<col style="width: 445px">
</colgroup>
<thead>
  <tr>
    <th class="tg-fs2w">번호</th>
    <th class="tg-0lax">${vo.num}</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-fs2w">아이디</td>
    <td class="tg-0lax">${vo.id}</td>
  </tr>
  <tr>
    <td class="tg-fs2w">비밀번호</td>
    <td class="tg-0lax">${vo.pass}</td>
  </tr>
  <tr>
    <td class="tg-fs2w">이름</td>
    <td class="tg-0lax">${vo.mname}</td>
  </tr>
  <tr>
    <td class="tg-fs2w">나이</td>
    <td class="tg-0lax"><input type="text" name="mage" value="${vo.mage}"/></td>
  </tr>
  <tr>
    <td class="tg-fs2w">이메일</td>
    <td class="tg-0lax"><input type="text" name="memail" value="${vo.memail}"/></td>
  </tr>
  <tr>
    <td class="tg-fs2w">전화번호</td>
    <td class="tg-0lax"><input type="text" name="mtel" value="${vo.mtel}"/></td>
  </tr>
  <tr>
    <td class="tg-baqh" colspan="2">
      <input type="submit" value="수정하기" class="btn btn-warning"/>
      <input type="reset" value="취소"/ class="btn btn-danger">
      <input type="button" onclick="location.href='${cpath}/list.do'" value="리스트" class="btn btn-success"/>    
    </td>
  </tr>
</tbody>
</table>
</form>
</body>
</html>

 

JSTL연습하기

 

 

Http - 비연결지향 프로토콜

                                                    쿠키에서출발(세션이라는개념으로 사용)

세션 트래킹 기술 -연결지향 프로토콜처럼 보이게하는 기술!

 

 

Bootstrap  -  CSS코드를 모아놓은 프레임워크의 종류
CSS기반의 디자인 템플릿으로 제공한다

 

${안에 들어올려면} - 1.식(var로 되어있는 식)
  2.속성이름(setAttribute돼있어야함)
       request.setAttribute("vo", vo);
(원래는 controller에서함)

●jstl03.jsp

<%@page import="kr.iot.model.MemberVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	//회원정보 1개를 생성해보자
	MemberVO vo = new MemberVO();
	vo.setId("admin");
	vo.setMname("김민관");
	vo.setMemail("redcombo@smhrd.com");
	vo.setMage(24);
	request.setAttribute("vo", vo);
%>

vo 회원정보 생성

getAttribute하기위해 setAttribute를 해준다.

 

●jstl03.jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
 <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<table class="table table-hover">
	<tr>
		<td>아이디</td>
		<td>이름</td>
		<td>이메일</td>
		<td>나이</td>
	</tr>
	<tr>
		<td>${vo.id}</td>
		<td>${vo.mname}</td>
		<td>${vo.memail}</td>
		<td>${vo.mage}</td>
	</tr>
</table>
</body>
</html>

회원정보 테이블 만들기

 

${vo.id} ->Servlet으로 변환할때 ${vo.id}라는 식이 request.getAttribute("vo")로 읽어서 처리한다.

 

 

●jstl04.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="java.util.*" %>
    <%@page import="kr.iot.model.*" %>
 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> 
<%
	List<MemberVO> list = new ArrayList<MemberVO>();
	MemberVO vo = new MemberVO();
	vo.setId("admin");
	vo.setMname("김민관");
	vo.setMemail("redcombo@smhrd.com");
	vo.setMage(24);
	list.add(vo);
	list.add(vo);
	list.add(vo);
	list.add(vo);
	list.add(vo);
	request.setAttribute("list", list);
%>

list로 회원정보

마찬가지로 request.setAttribute 해준다

 

●jstl04.jsp

<!DOCTYPE html>
<html>
<title>Insert title here</title>
<meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<table class="table table-hover">
	<tr>
		<td>아이디</td>
		<td>이름</td>
		<td>이메일</td>
		<td>나이</td>
	</tr>
	<c:forEach var="vo" items="${list}">
	<tr>
		<td>${vo.id}</td>
		<td>${vo.mname}</td>
		<td>${vo.memail}</td>
		<td>${vo.mage}</td>
	</tr>
	</c:forEach>
</table>
</body>
</html>

list가져오기

 

같은 방식이지만 list이기 때문에,

여러가지(list)가져올때는 c:forEach(반복문)과 items로 list를 가져올수있다.

<c: forEach문안에 가져올 vo를 반복하고, 그것은 list들이된다.

반응형

'JSP Servlet' 카테고리의 다른 글

비동기식페이지2(JSON , Ajax)  (0) 2021.02.08
비동기식페이지(JQuery,Ajax,JSON)  (0) 2021.02.08
회원관리 MVC2(forward+FrontController)  (0) 2021.02.08
회원관리 MVC2(forward)  (0) 2021.02.08
물품관리 MVC1  (0) 2021.02.08