이번엔 실제로 서블릿을 이용하여 로그인 페이지를 만들었다. 아직은 미완성이지만
처음에 서블릿 공부를 시작하고보다는 많이 이해가 가고 있다 아직은 멀었지만 로그인 페이지를 완성하고 게시판까지 만들면 완전하게 이해를 할 것이라 믿는다 🙂
MemberService
package service;
import Servlet.MemberDAO;
import model.MemberVO;
public class MemberService {
private MemberDAO memberdao;
public MemberService() {
memberdao = MemberDAO.getInstance();
}
public boolean login(String id, String pwd) {
MemberVO membervo = memberdao.checkid(id);
// 로그인 아이디 없으면 실패
if(membervo == null) {
return false;
}
else
{
if(membervo.getPwd().equals(pwd))
return true;
else
return false;
}
}
}
MemberVO
package model;
public class MemberVO {
private String id;
private String pwd;
private String name;
public MemberVO() {
System.out.println("member 생성자 호출");
}
public MemberVO(String id, String pwd, String name) {
this.id=id;
this.pwd=pwd;
this.name=name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPw(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "MemberVO [id="+id +", pwd=" +pwd +"]";
}
}// end class
LoginServlet
package Servlet;
import java.io.IOException;
import service.MemberService;
import java.util.List;
import service.MemberService;
import model.MemberVO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
private MemberService service;
public LoginServlet(){
service= new MemberService();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get start");
doHandle(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post start");
doHandle(req, resp);
}
/* private void doHandle(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charest=utf-8");
System.out.println("doHandle start");
List<MemberVO> membersList = memberDAO.listMembers();
req.setAttribute("membersList", membersList);
RequestDispatcher dispatch = req.getRequestDispatcher("/test01/login.jsp");
dispatch.forward(req,resp);
}*/ //전체 조회하는 소스
protected void doHandle(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doHandle start");
String contextPath = req.getContextPath();
String reqUri = req.getRequestURI();
System.out.println("1");
if(reqUri.equals(contextPath + "/login.do")) {
System.out.println("2");
String id = req.getParameter("id");
String pw = req.getParameter("pwd");
System.out.println("여기까지");
if(service.login(id, pw)) {
req.setAttribute("msg", "로그인 성공");
req.getSession().setAttribute("id", id);
System.out.println("3");
}
else {
req.setAttribute("msg","로그인 실패");
}
req.getRequestDispatcher("loginResult.jsp").forward(req, resp);
}
else if(reqUri.equals(contextPath + "/loginForm.do")) //loginForm보여줘
{
req.getRequestDispatcher("loginForm.jsp").forward(req, resp);
}
else if(reqUri.equals(contextPath + "/main.do")) //main보여줘
{
if(req.getSession().getAttribute("id") == null)
{
resp.sendRedirect("loginForm.do");
//계속 실행되기 때문에 꼭 리턴해줘야함
return;
}
req.getRequestDispatcher("main.jsp").forward(req, resp);
}
}
}
MemberDAO
package Servlet;
import model.MemberVO;
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 java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import model.MemberVO;
public class MemberDAO {
private DataSource dataFactory;
private Connection conn;
private PreparedStatement pstmt;
private static String URL="jdbc:oracle:thin:@localhost:1521:XE" ;
private static String USERNAME="hr";
private static String PASSWORD="1234";
private static MemberDAO instance;
public static MemberDAO getInstance(){
if(instance == null)
instance = new MemberDAO();
return instance;
}
// public MemberDAO() {
// try {
// Context ctx = new InitialContext();
// Context envContext = (Context) ctx.lookup("java:/comp/env");
// dataFactory =(DataSource) envContext.lookup("jdbc/oracle");
// } catch (Exception e) {
//
// e.printStackTrace();
// }
//
//
// }// end MemberDAO
private MemberDAO(){
try { //5.생성자에서 커넥션 얻기
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
public List<MemberVO> listMembers(){
List<MemberVO> memberList = new ArrayList<MemberVO>();
try {
conn = dataFactory.getConnection();
String qry = "SELECT * FROM tb_user"; //SQL문 작성
pstmt = conn.prepareStatement(qry); //PrepareStatmennt 객체를 생성 하면서 SQl문을 인자로 전달
System.out.println(qry);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
String id = rs.getString("id");
String pwd = rs.getString("pwd");
String name = rs.getString("name");
MemberVO memberVO = new MemberVO(id,pwd,name);
memberList.add(memberVO);
};
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return memberList;
}// end ListMembers()
public void addMember(MemberVO m) {
try {
conn=dataFactory.getConnection();
String id = m.getId();
String pwd = m.getPwd();
String name =m.getName();
String qry = "INSERT INTO tb_user(user_id,user_pw,user_name)" + "VALUES(?,?,?)";
System.out.println(qry);
pstmt = conn.prepareStatement(qry);
pstmt.setString(1, "id");
pstmt.setString(2, "pw");
pstmt.setString(3, "name");
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public MemberVO checkid(String id) {
String sql= "SELECT * FROM tb_user where id =?";
PreparedStatement pstmt = null;
MemberVO membervo = null;
ResultSet rs = null;
try {
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next() ) {
membervo = new MemberVO();
membervo.setId(rs.getString("id"));
membervo.setName(rs.getString("pwd"));
membervo.setName(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if( pstmt != null && !pstmt.isClosed())
pstmt.close();
if( rs != null && !rs.isClosed())
pstmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
return membervo;
}
}// end class
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="web01.MemberDTO"%>
<%@page import="java.util.ArrayList" %>
<%@page import="web01.MemberDAO"%>
http://www.w3.org/TR/html4/loose.dtd>">
//////////////////////////////////////////////////////////////////////////
function check(){
System.out.println("check start");
if (document.getElementById("id").value == ""){
alert("아이디를 입력해 주세요.");
return false;
}
else if (document.getElementById("pwd").value == ""){
alert("아이디를 입력해 주세요.");
return false;
}
}// id/pwd 유효성 검사 ////////////////////////////////////////////////////////
loginResult.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
http://www.w3.org/TR/html4/loose.dtd>">
<%
String msg = (String) request.getAttribute("msg");
%>
<%= msg %>
main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
http://www.w3.org/TR/html4/loose.dtd>">
<%= session.getAttribute("id") %> 님 환영합니다.
'">
코드 설명은 나중에 완성하면 하고 싶다.. 아직은 오류가 많다 .. 흰색 화면만 뜬다..
아마도 서블릿에서 JSP로 넘어가는 과정에서 오류가 있지 않을까 싶다 내일 강사님한테 물어봐야겠다 암튼 ㅂㅇ !
'Programming > Back-end Language' 카테고리의 다른 글
[Spring] The import org.springframework.boot.test cannot be resolved 해결 방법 (0) | 2022.02.21 |
---|---|
[JAVA]Call by value와 Call by referenece (0) | 2022.02.13 |
[JAVA] Servlet 로그인 페이지 만들기 (1) (1) | 2022.01.05 |
[JAVA] 서블릿 경로설정과 Cycle (0) | 2022.01.04 |
[JAVA] 서블릿 (GET/POST)전송방식 (0) | 2022.01.04 |