Framework/Spring Framework

(22.12.19)Spring ํ”„๋ ˆ์ž„์›Œํฌ : @SessionAttributes๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Database์™€ ์—ฐ๋™ํ•œ ๋กœ๊ทธ์ธ ๊ธฐ๋Šฅ ์ž‘์„ฑํ•˜๊ธฐ

ํ”„๋กœ๊ทธ๋ž˜๋จธ ์˜ค์›” 2022. 12. 19.

โ—โ—Spring framework๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Database์™€ ์—ฐ๋™ํ•˜์—ฌ ๋กœ๊ทธ์ธ ๊ธฐ๋Šฅ ์ž‘์„ฑํ•˜๊ธฐโ—โ—


M : User.java , UserDAO.java
V : loginForm.jsp
C : UserController.java
Service : UserService.java


๋จผ์ € @SessionAttributes, @SessionAttribute ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋กœ๊ทธ์ธ ๊ธฐ๋Šฅ ์ž‘์„ฑํ•˜๊ธฐ

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
 
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
    String uid;
    String pwd;
}
 
cs



UserController.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
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ezen.spring.web.service.UserService;
import com.ezen.spring.web.vo.User;
 
@Controller
@RequestMapping("/login")
public class UserController 
{
    @Autowired
    private UserService svc;
    
    @GetMapping("/loginform")
    public String loginForm()
    {
        return "/user/loginForm";
    }
    @PostMapping("/loginResult")
    @ResponseBody
    public Map<String,Boolean> loginResult(User user)
    {
       boolean ok = svc.login(user);
       Map<String,Boolean> map = new HashMap<>();
       map.put("login", ok);
       return map;
    }
}
cs




UserService.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
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ezen.spring.web.dao.UserDAO;
import com.ezen.spring.web.vo.User;
import jakarta.servlet.http.HttpSession;
 
@Service
public class UserService 
{
    @Autowired
    private UserDAO dao;
    
    private HttpSession session;
    
    @Autowired //setter injection
    public void setSession(HttpSession session) {
        this.session = session;
    }
    
    public boolean login(User user) {
        boolean ok = dao.login(user);
        if(ok) {
            session.setAttribute("userid", user.getUid());
        }
        return ok;
    }
}
cs





UserDAO.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
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
59
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.stereotype.Component;
import com.ezen.spring.web.vo.User;
 
@Component
public class UserDAO {
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    
    private Connection getConn()
    {
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            conn = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:xe""SCOTT""TIGER");
            this.conn = conn;
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public boolean login(User user)
    {
        getConn();
        try {
            String sql = "SELECT * FROM emp2 WHERE ename=? AND empno=?";
            this.pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,user.getUid());
            //.toUpperCase ์†Œ๋ฌธ์ž๋ฅผ ๋Œ€๋ฌธ์ž๋กœ ๋ฐ”๊ฟ”์ฃผ๋Š” ๋ฉ”์†Œ๋“œ
            pstmt.setString(2, user.getPwd());
            this.rs= pstmt.executeQuery();
            
            return rs.next(); // next๋กœ ๊ฐ€๋ฅดํ‚ค๋Š” ํ–‰์ด ์žˆ์œผ๋ฉด true
            
        } 
        catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll();
        }
        return false;
    }
    private void closeAll()
    {
        try {
            if(rs!=null) rs.close();
            if(pstmt!=null) pstmt.close();
            if(conn!=null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
cs




loginForm.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
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>๋กœ๊ทธ์ธ ํผ</title>
<style type="text/css">
    @import url(//fonts.googleapis.com/earlyaccess/jejumyeongjo.css);
    .jm-font{
        font-family: 'Jeju Myeongjo', cursive;
        color: black;
        font-size:3em;}
    #id, #pw{
        font-family: 'Jeju Myeongjo', serif;
        color: black;
        font-size:1.5em;}
    .wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;}
    main {width:fit-content; margin:1em auto; }
    main h3{ text-align: center;}
    form {border:1px solid black; padding:1em;}
    label {display:inline-block; width:3em; text-align: right; padding-right:1em; }
    div.btn { width:fit-content; margin: 0.5em auto; }
</style>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" 
integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous">
</script>
<script type="text/javascript">
function getLogin()
{
    var obj = $('#loginForm').serialize();
    $.ajax({
        url : '/login/loginResult',
        method:'post',
        data : obj,
        cache:false,
        dataType:'json',
        success:function(res){
            alert(res.login ? '๋กœ๊ทธ์ธ ์„ฑ๊ณต':'๋กœ๊ทธ์ธ ์‹คํŒจ');
            if(res.login){
                
            }
        },
        error : function(xhr, status, err){
            alert('์—๋Ÿฌ:' + err);
        }
    });
    return false;
}
</script>
</head>
<body style="background-color: rgb(227,209,254);">
<div class="wrapper" >
<main class="main-font">
<h3 class="jm-font">๐Ÿง‘‍๐Ÿ’ป๋กœ๊ทธ์ธ</h3>
<form id="loginForm" onsubmit="return getLogin();">
    <input type="hidden" name="cmd" value="adminlogin">
    <div id ="id"><label for="uid">์•„์ด๋””</label>
        <input type="text" id="uid" name="uid" style="height:25px">
    </div>
    <p>
    <div id="pw"><label for="pwd">์•”ํ˜ธ</label>
        <input type="password" id="pwd" name="pwd" style="height:25px">
    </div>
    <div class="btn">
        <button type="reset">์ทจ์†Œ</button>
        <button type="submit">๋กœ๊ทธ์ธ</button>
    </div>
</form>
</main>
</div>
</body>
</html>
cs




Spring์— ์žˆ๋Š” session Annotation์„ ํ™œ์šฉํ•˜์—ฌ ๋กœ๊ทธ์ธ ํ•˜๊ณ  ์‚ฌ์šฉ์ž์˜ ์•„์ด๋””๋ฅผ ์„ธ์…˜๊ฐ์ฒด์— ๋‹ด๊ธฐ



@SessionAttributes(" ์„ธ์…˜ ์†์„ฑ์ด๋ฆ„") - ํด๋ž˜์Šค ์œ„์—๋‹ค๊ฐ€ ๋ถ™์ธ๋‹ค. : ์„ธ์…˜์— ์„ ์–ธํ•˜๊ธฐ
@SessionAttribute("์„ธ์…˜ ์†์„ฑ ์ด๋ฆ„") - ๋ฉ”์†Œ๋“œ ํŒŒ๋ผ๋ฏธํ„ฐ : ์„ธ์…˜์—์„œ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๊ธฐ
SessionStatus - ๋ฉ”์†Œ๋“œ ํŒŒ๋ผ๋ฏธํ„ฐ์—
-status.setComplete();

์˜ˆ์‹œ
@Controller
@SessionAttributes("userid")
์š”์ฒญ ํŒŒ๋ผ๋ฏธํ„ฐ userid์˜ ๊ฐ’์„ ์ž๋™์œผ๋กœ ์„ธ์…˜์— ์ €์žฅ,
model.addAttribute("userid","smith")
๋ชจ๋ธ ๋ฐ์ดํ„ฐ์˜ ํ‚ค๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ๋„ ์„ธ์…˜์— ๋“ค์–ด๊ฐ„๋‹ค.



User.java
๋ณ€์ˆ˜๋ช…์„ ์ˆ˜์ •ํ•˜์˜€๋‹ค.

1
2
3
4
5
6
7
8
9
10
11
12
13
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
 
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
    String userid;
    String userpwd;
}
cs




loginForm.jsp
์˜ ๋ณ€์ˆ˜ name์„ ํ†ต์ผ ์‹œ์ผœ์ฃผ๊ธฐ ์œ„ํ•ด ๊ณ ์ณค๋‹ค.

1
2
3
4
5
6
7
8
9
10
11
12
13
<form id="loginForm" onsubmit="return getLogin();">
    <div id ="id"><label for="userid">์•„์ด๋””</label>
        <input type="text" id="userid" name="userid" style="height:25px">
    </div>
    <p>
    <div id="pw"><label for="userpwd">์•”ํ˜ธ</label>
        <input type="password" id="userpwd" name="userpwd" style="height:25px">
    </div>
    <div class="btn">
        <button type="reset">์ทจ์†Œ</button>
        <button type="submit">๋กœ๊ทธ์ธ</button>
    </div>
</form>
cs




UserController.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
59
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.ezen.spring.web.service.UserService;
import com.ezen.spring.web.vo.User;
 
@Controller
@SessionAttributes("userid")
@RequestMapping("/login")
public class UserController 
{
    @Autowired
    private UserService svc;
    
    @GetMapping("/loginform")
    public String loginForm()
    {
        return "/user/loginForm";
    }
    @PostMapping("/loginResult")
    @ResponseBody
    public Map<String,Boolean> loginResult(User user, Model m)
    {
       boolean ok = svc.login(user);
       if(ok) {
           m.addAttribute("userid", user.getUserid());
       }
       Map<String,Boolean> map = new HashMap<>();
       map.put("login", ok);
       return map;
    }
    @GetMapping("/logout")
    @ResponseBody
    public Map<String,Boolean> logout(SessionStatus status){
        status.setComplete();
        boolean logout = status.isComplete();
        Map<String,Boolean> map = new HashMap<>();
        map.put("logout", logout);
        return map;
    }
    @GetMapping("/test")
    @ResponseBody
    public Map<String,String> isLogged(
            @SessionAttribute(name="userid", required=falseString userid){
        
        Map<String,String> map = new HashMap<>();
        map.put("userid", userid);
        return map;
    }
}
cs



์‹คํ–‰ ๊ฒฐ๊ณผ :

๋กœ๊ทธ์ธ ์„ฑ๊ณต

 

session์— userid๊ฐ€ ์ œ๋Œ€๋กœ ์ €์žฅ๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธ



๋กœ๊ทธ์•„์›ƒ ์‹คํ–‰

 

๋กœ๊ทธ์•„์›ƒ ํ•˜๊ณ ๋‚˜๋‹ˆ session์— ์ €์žฅ๋œ ์ •๋ณด๊ฐ€ ์‚ญ์ œ๋œ ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.





๋Œ“๊ธ€