본문 바로가기
✨ Back-end/Servlet

[Servlet] JSP, Servlet, Class 사용하여 이름, 나이, 성적 간단히 출력

by 환풍 2023. 2. 14.
728x90
JSP와 Servlet을 많이 연습해보며 어느정도 다룰 수 있게 되었다.
넘어야 할 산이 하나 또 남아있다. 바로 Class를 연동시켜 데이터를 받아와보자.

 

Student.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
package stu;
 
public class Student {
    //이름, 나이, 성적
    // 매개변수로 멤버를 변경하는 생성자, 기본 생성자.
    // getter, setter
    
    private String name;
    private int age;
    private int score;
    
    public Student() {
        
    }
    
    public Student(String name, int age, int score) {
        super();
        this.name = name;
        this.age = age;
        this.score = score;
    }
    
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public int getScore() {
        return score;
    }
 
    public void setScore(int score) {
        this.score = score;
    }
 
}
cs

클래스로 받아갈 이름, 나이, 성적 변수를 만들고, 생성자와 세터, 게터를 만들었다.

 

reg_stu.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="regStudent" method="post">
<table>
    <tr>
        <td>이름</td>
        <td><input type="text" name="name"></td>
    </tr>
    <tr>
        <td>나이</td>
        <td><input type="text" name="age"> </td>
    </tr>
    <tr>
        <td>성적</td>
        <td><input type="text" name="score"> </td>
    </tr>
    
</table>
<input type="submit" value="등록">
</form>
</body>
</html>
cs

이름, 나이, 성적을 입력할 input 박스를 만들고, form태그를 주어 서블릿파일에 "regStudent" 가 있는 곳으로 찾아가도록 지정해주었다. 메소드는 post.

 

RegstudentServlet.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
import java.io.IOException;
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;
 
import stu.Student;
 
@WebServlet("/regStudent")
public class RegstudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
   
    public RegstudentServlet() {
        super();
       
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //한글 인코딩 얘도 서블릿 맨위에 컨트롤 cv로 깔고 시작.
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        
        //데이터 받기
        String name= request.getParameter("name");
        
        int age = Integer.parseInt(request.getParameter("age"));
        // 이렇게 바꾸어줘야 방법2로 적용가능하다.    
        int score = Integer.parseInt(request.getParameter("score"));
        
        //모든 데이터를 가져갈 Student 객체 생성
        Student s1 = new Student();
        s1.setName(name); // 위에서 전달받은 name값을 s1 네임에 넣어줌.
        s1.setAge(age); // 받은 데이터는 String이라 변환해주기.
        s1.setScore(score);
        
        //방법2
        Student s2 = new Student(name, age, score );
        
        //데이터전달
        request.setAttribute("student", s2);
        
        RequestDispatcher dispatcher = request.getRequestDispatcher("show_stu.jsp");
        dispatcher.forward(request, response);
        
    }
}
 
cs

input type을 text로 받은 값모든 값이 String으로 정의되어 있으므로, age와 score 값을 int형으로 바꾸어주어야한다.

Student 클래스를 만들어 놓았기 때문에

방법 1으로 새로운 s1 객체를 만들어 세터를 이용해 하나하나씩 이름 ,나이 , 성적 값을 초기화 해줄 수 있다.

방법 2를 사용하여 새로운 객체 s2 생성과 동시에 이름, 나이, 성적 값을 초기화하여 데이터를 전달해 줄 수있다. 

 

이후, request.getRequestDispatcher("show_stu.jsp") 의해 show_stu.jsp로 사이트로 이동하여 데이터를 출력한다.

 

show_stu.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
이름 : ${student.name } <br>
나이 : ${student.age } <br>
성적 : ${student.score } <br>
</body>
</html>
cs

student 클래스로부터 받아온 이름, 나이, 성적이므로 ${student. ~~} 와 같은 방식으로 표현 해야한다.

 

최종화면

 

반응형

댓글