반응형
세션(session)
세션은 쿠키와 달리 저장할 데이터를 서버에 저장
세션 시작(세선을 사용하기 위해 세션 정보 리턴)
HttpSession session = request.getSesstion();
세션 저장
session.setAttribute("이름", 값);
저장된 세션 데이터 가져오기
String id = (String)session.getAttribute("id");
세션 삭제
session.removeAttribute("이름");
세선 종료
session.invalidate();
세션이용 로그인 기능 예제
loginAction.java(servlet 세션이용 예제)
package com.knowhoon.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.knowhoon.dao.LoginDAO;
import com.knowhoon.dto.LoginDTO;
@WebServlet("/loginAction")
public class LoginAction extends HttpServlet {
private static final long serialVersionUID = 1L;
//UUID
public LoginAction() {
super();
}
//get방식 요청
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//한글처리
response.setContentType("text/html;charset=UTF-8");
String id = request.getParameter("id");
String pw = request.getParameter("pw");
LoginDAO dao = new LoginDAO();
LoginDTO dto = new LoginDTO();
dto.setId(id);
dto.setPw(pw);
LoginDTO result = dao.loginAction(dto);
if(result != null && result.getName()!=null){
session.setAttribute("id", result.getId());
session.setAttribute("name", result.getName());
session.setAttribute("no", result.getNo());
System.out.println(session.getAttribute("id"));
System.out.println(session.getAttribute("name"));
System.out.println(session.getAttribute("no"));
response.sendRedirect("./board.jsp");
}else{
System.out.println("로그인 해주세요");
response.sendRedirect("./index.jsp");
}
}
}
logout.java(servlet 세션이용 예제)
package com.knowhoon.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/logout")
public class Logout extends HttpServlet {
private static final long serialVersionUID = 1L;
public Logout() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("get");
HttpSession session = request.getSession();
if(session.getAttribute("id") != null) {
session.removeAttribute("id");
}
if(session.getAttribute("name") != null) {
session.removeAttribute("name");
}
//session.invalidate(); //모든 세션 종료
response.sendRedirect("./index.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post");
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index.jsp</title>
</head> <!-- /loginAction 서블릿으로 전송
java + web -> servlet
java코드 속에 html코드
서블릿 2.5이후 기술은 그냥 사용
서블릿 2.5이전 기술은 web.xml에 설정을 적용
html + java
html코드 속에 자바
-->
<%@ include file="./menu.jsp"%>
<div id="loginbox">
<div id="loginimg">
<img alt="" src="./login.png">
</div>
<div id="logininput">
<form action="./loginAction" method="post">
<input type="text" name="id" maxlength="15" placeholder="아이디를 입력하세요"
required="required"> <input type="password" name="pw"
maxlength="20" placeholder="비밀번호를 입력하세요" required="required"><br>
<button type="submit">LOGIN</button>
<button type="reset">RESET</button>
</form>
</div>
</div>
</body>
</html>
LoginDAO.java
package com.knowhoon.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.knowhoon.dto.LoginDTO;
import com.knowhoon.db.DBConnection;
public class LoginDAO {
public LoginDTO loginAction(LoginDTO dto) {
LoginDTO login = new LoginDTO();
Connection conn = DBConnection.dbConnection();
ResultSet rs = null;
PreparedStatement pstmt = null;
String query = "SELECT * FROM login WHERE id=? AND pw=?";
try {
pstmt = conn.prepareStatement(query);
pstmt.setString(1, dto.getId()); //물음표 위치에 어떤 값
pstmt.setString(2, dto.getPw()); //적어주기 (위치, 값)
rs = pstmt.executeQuery();
if(rs.next()) {
login.setNo(rs.getInt("no"));
login.setName(rs.getString("name"));
login.setId(rs.getString("id"));
login.setPw(rs.getString("pw"));
login.setEmail(rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(rs != null) {rs.close(); }
if(pstmt != null) {pstmt.close(); }
if(conn != null) {conn.close(); }
} catch (SQLException e) {
e.printStackTrace();
}
}
return login;
}
}
LoginDTO.java
package com.knowhoon.dto;
//no, id, pw, name, email
public class LoginDTO {
private int no;
private String id, pw, name, email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
}
반응형
'프로그래밍 > Java 공부' 카테고리의 다른 글
[Java] javax mail Could not convert socket to TLS (1) | 2021.09.18 |
---|---|
자바 Servlet - 세션 이용 글 수정 기능 (0) | 2021.07.07 |
JAVA - Thread(스레드) (0) | 2021.06.30 |
Java_DTO (0) | 2021.06.23 |
Java_PreparedStatement (0) | 2021.06.23 |