본문 바로가기

JSP/기본다지기

JSP 4일차 필기 (전역변수, 메소드)

L04Jsp 프로젝트의 WebContent안에 L03GlobalV.jsp 생성.


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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>전역변수와 서블릿 생성자에 대해 알아보자!</title>
</head>
<%!
//servlet은 페이지를 처음 한 번 요청시 생성자가 호출한다.
//->자기 자신을 생성자로 가지고 있다.
//서블릿에서 main()을 대신하는 것은 doGet()
//main() a()를 호출하려면 생성자를 생성하고 호출해야한다. new Class().a();
//doGet()에서는 바로 호출 가능 a();
//자기 자신은 생성자 없이 호출 가능함.
//public L03GlobalV(){}//JSP는 생성자를 만들 수 없다. servlet은 가능.
int a = 10;
public int a(){
    int a = 20;
    return a;
}
%>
<body>
<h1>자바처럼 전역변수와 메소드를 설정하고 불러오자</h1>
<%
//PrintWriter out = response.getWriter();가 생략되어 있음.
out.print("<h3>전역변수: "+this.a+"</h3>");
out.print("<h3>a().a : "+a()+"</h3>");
a();
%>
</body>
</html>
cs


JSP에서 메소드 사용하기.


L04Method.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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>method를 이용해서 성적프로그램을 만들자</title>
</head>
<%!
public String gradeDemo(String str_score){
    int score = Integer.parseInt(str_score);
    String a ="";
    String plus = "";
     switch(score/10){
     case 10case 9: a = "A"break;
     case 8: a = "B"break;
     case 7: a = "C"break;
     case 6: a = "D"break;
     default: a = "F"break;
     }
    plus = (((score+5)/10-score/10)==1||score==100)?"+":"";
    return a+plus;
};
%>
<%String scoreParam = request.getParameter("score");%>
<body>
    <h1>성적 프로그램</h1>
    <h3>당신의 성적은 점 <%=scoreParam%> : 학점은 <%=gradeDemo(scoreParam)%></h3>
</body>
</html>
cs