- -- Login.jsp --
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<body>
<h2>** Servlet : Member Login **</h2>
<form action="/Web01/mlogin" method=get>
<table>
<tr><td><label for=id> I D : </label></td>
<td><input type="text" name=id id=id></td>
</tr>
<tr><td><label for=password> PassWord : </label></td>
<td><input type="password" name=password id=password></td>
</tr>
<br>
<input type="submit" value=로그인>
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
<hr>
<% if(request.getAttribute("message")!=null){ %>
=> Message : <%= request.getAttribute("message")%>
<%} %>
|
cs |
처음으로 로그인 페이지를 생성하여
로그인 폼 태그와 input 태그에 입력한 정보를 mlogin 서블릿으로 보내 doGet으로 받는다.
- --mlogin.java--
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
@WebServlet("/mlogin1")
public class MVC2_Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public MVC2_Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// => id 를 먼저 확인 하고 성공일 경우 password 비교 (이점)
// MemberDetail 메소드 사용, id 오류 인지 password 오류 인지 확인이 가능하다.
MemberService Service = new MemberService(); // 모델에 넘겨주기위한 서비스 객체 선언
MemberVO vo = new MemberVO(); // 모델의 정보를 받기위한 vo객체 선언
String url = "";
vo.setId(request.getParameter("id"));
vo = Service.memberDetail(vo);
if(vo!=null) {
// id 비교 성공시 비밀번호 확인.
// String 문자열이기 때문에 기존 저장값과 입력값을 비교하기 위해 equals 사용
if(vo.getPassword().equals(request.getParameter("password"))) {
// Login 성공 -> 로그인 정보를 보관(id, Name) -> Login Success
HttpSession session = request.getSession();
session.setAttribute("Login_id",request.getParameter("id"));
session.setAttribute("Login_Name", vo.getName());
request.setAttribute("message", vo.getName()+"님이 로그인하셨습니다.");
url = "index.jsp";
}else {
// password 오류 발생 -> 로그인 폼
request.setAttribute("message", "password 오류입니다.");
url = "servletTestForm/form05_Login.jsp";
}
}else {
// id 오류 발생 -> 로그인 폼
request.setAttribute("message", "id 오류입니다.");
url = "servletTestForm/form05_Login.jsp";
}
// 3.1) Forward
System.out.println("** Dispatcher 실행 **");
request.getRequestDispatcher(url).forward(request, response);
// Dispatcher => 이동할 대상("ㄴㅇㄴㅁㅇ") . forward(request,response)
// 3.2) Redirect
//response.sendRedirect("servletTestForm/form05_LoginSuccess.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
cs |
input 태그에 입력한 정보와 서블릿(DBconn) 에 존재하는 정보와 비교하는 서블릿커널에서 요청받은 값(id) 가 NULL 값인지 유무를 확인하고 패스워드도 확인한 후 값을 세션객체로 저장 후 url을 통해 전달한다.
(존재하지 않는 id 의 경우 NULL 값을 리턴하기때문에 아래 if문에서 else 문으로 나가 request 객체를 통해 메세지 출력함)
- -- login success.jsp--
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>** Login Success **</title>
</head>
<body>
<h2>** Login Success **</h2>
<h2> ~~~ 안녕하세요 ~~~ </h2>
<pre>
I D : <%=request.getParameter("id") %>
P W : <%=request.getParameter("password") %>
</pre>
=> <%=session.getAttribute("Login_id")%> <%= session.getAttribute("Login_Name") %> 님 반갑습니다.
=> EL 적용 <br>
=> ${Login_Name} 님 반갑습니다 ~~
<br><br><br><hr>
<a href="/Web01/logout">Logout</a>
<a href="/Web01/index.jsp">[Home]</a>
</body>
</html>
|
cs |
- -- index (main).jsp --
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<body>
<h2>안녕하세요</h2>
<hr>
<h3>=> Login 확인 후 memberList 메뉴 표시</h3>
<c:if test="${not empty Login_id}">
<a href = "/Web01/mDetail">MyInfo</a>
<a href = "/Web01/mList">member List</a>
<a href = "/Web01/Logout">Logout</a>
</c:if>
<c:if test ="${empty Login_id }">
<a href = "/Web01/servletTestForm/form05_Login.jsp">Login</a>
<a href = "/Web01/servletTestForm/form05_Join.jsp">Join</a>
</c:if>
<hr>
<c:if test ="${not empty message1 }">
=> Message : ${message1}
</c:if>
|
cs |
로그인 이후 저장된 세션을 통해 (ID가 존재하는 상황)
not empty Login_id 의 값으로 해당하는 링크(서블릿) 을 연결한다.
- -- mvc2_mDetail.java --
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
@WebServlet("/mDetail")
public class MVC2_mDetail extends HttpServlet {
private static final long serialVersionUID = 1L;
public MVC2_mDetail() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ID 확인 (세션을 통해 저장된 정보를 불러옴 (Session 에서 get))
// Session 객체 정의, getAttribute
HttpSession session = request.getSession(false);
String url = "";
String message = "";
// (), (true) 동일 = 세션이 존재하면 존재하는 세션 리턴, 없으면 생성 후 리턴 => null값이 될 수 없음.
// (false) session이 존재하면 존재하는 세션 리턴, 없으면 NULL값 리턴
// => 내정보 수정, 삭제 등 반드시 로그인한 user인지 확인해야 하는 경우
// -> session 이 null인지 확인하는 구문이 필요함.
if(session != null && session.getAttribute("Login_id") != null) {
// 세션이 널값이 아니고 , login_id 값이 널이 아닌경우 실행{
// detail 처리
String id = (String)session.getAttribute("Login_id");
System.out.println("****"+id);
MemberService Service = new MemberService(); // 모델에 넘겨주기위한 서비스 객체 선언
MemberVO vo = new MemberVO(); // 모델의 정보를 받기위한 vo객체 선언
vo.setId(id); // setter 를 이용하여 요청하는 파라미터 값을 저장함.
vo = Service.memberDetail(vo); // service에 존재하는 detail객체를 불러옴.
System.out.println("*****"+vo); // console 창에 제대로 정보가 넘어오는지 확인
if(vo!=null) {
// 받은 값 ( vo ) 를 해 request 객체에 저장
request.setAttribute("apple", vo); //("별칭", Setter 할 객채 )
url = "mvcJsp/mvc2_mDetail.jsp"; // 주소값 저장
}else {
message = "해당하는 정보가 없습니다.";
url = "index.jsp";
}
}else {
// message 출력 후 index.jsp로 이동
message = "로그인 정보가 없습니다.";
url = "servletTestForm/form05_Login.jsp";
}
// 3. 결과
if(message != null && message.length()>0)
request.setAttribute("message", session);
request.getRequestDispatcher(url).forward(request, response); // forward 를 url(경로)로 해서
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
cs |
- -- MemberDAOdetail.java --
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
private static Connection cn = DBConnection.getConnection();
private static Statement st;
private static PreparedStatement pst;
private static ResultSet rs;
private static String sql;
public MemberVO memberListDetail(MemberVO vo) {
sql = "select * from member where id = ?";
try {
pst = cn.prepareStatement(sql); // pst 객체를 생성하고 sql구문의 값을 pst 객체에 전달
pst.setString(1, vo.getId()); // 바인딩 변수에 대한값을 지정
rs = pst.executeQuery(); // 쿼리문 실행
if(rs.next()) { // rs.next -> 1 or 0으로 리턴 (출력될 값이 있으면 1 없다면 null
vo.setId(rs.getString(1));
vo.setPassword(rs.getString(2));
vo.setName(rs.getString(3));
vo.setLev(rs.getString(4));
vo.setBirthd(rs.getString(5));
vo.setPoint(rs.getInt(6));
vo.setWeight(rs.getDouble(7));
}else vo = null;
} catch (Exception e) {
System.out.println("** sql Detail 에러발생 => "+e);
vo = null;
}
return vo;
}
|
cs |
memberListDetail 에 존재하는 sql 구문을통해 prepareStatement 값을 세션에서의 파라미터값으로 저장하고 출력하여 해당 객체를 vo로 리턴받아 if문을 통해 널 값이 아닌지 확인 후 url 을통해 view로 이동한다.
- -- mvc2_mDetail.jsp--
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<%@ 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>
<html>
<head>
<meta charset="UTF-8">
<title> **MVC2 MemberList Detail **</title>
<style>
table tr {
height: 40;
}
.a{
background-color: yellow
}
</style>
</head>
<body>
<h2>**MVC2 MemberList Detail **</h2>
<table>
<tr><td class = a>I D</td><td>${apple.id}</td></tr>
<tr><td class = a>Password</td><td>${apple.password}</td></tr>
<tr><td class = a>Name</td><td>${apple.name}</td></tr>
<tr><td class = a>level</td><td>${apple.lev}</td></tr>
<tr><td class = a>Birthday</td><td>${apple.birthd}</td></tr>
<tr><td class = a>Point</td><td>${apple.point}</td></tr>
<tr><td class = a>Weight</td><td>${apple.weight}</td></tr>
</table>
</body>
</html>
|
cs |
요청 -> 저장한 값을 테이블 형태로 출력
실습 예제를 수행 한 후
처음 작성했을 때, 로그인 창에서 입력을 해도 login_success로 넘어가지지 않고,
illegalstateexception 에러발생 하고,
로그인을 성공하여도, index.jsp 으로 왔을 때, 다시 null로 리턴을 받아 empty id의 if문을 설정받았기도 했었으며,
memberDetail 화면에서 테이블이 불려지지도 않았었다.
기본적으로 문제는 오탈자가 99%였고, 나머지 1%는 서버의 중복실행이 문제였다.
별칭의 값을 넘겨줄때나 서블릿 매핑 값을 주고받을 때는 꼭 오탈자 확인을 해야 하고,
꼭 서버의 실행 여부와 웹페이지의 흐름을 파악하는 것이 제일 중요하다고 느낀 예제 실습이다.
'공부 > 예제 실습' 카테고리의 다른 글
Spring Paging (0) | 2022.06.08 |
---|---|
Spring (Mybatis) (0) | 2022.05.10 |
MVC2 모델 게시판 작성(조회수 증가와 자신이 작성한 글에 조회수 증가X) (0) | 2022.04.15 |