<Session>
[Session 변수 선언] | [Session 변수 사용] |
HttpSession session = req.getSession(); session.setAttribute("세션변수명",값); |
- in JSP <%@ page session="true" %> seesion.getAttribute("세션변수명")을 참조 |
- in Controller HttpSession session = req.getSession(); session.getAttribute("세션변수명",값)을 참조 |
model attribute 파일은 jsp에게만 전달된다. |
<코드>
HomeController : logout부분을 추가했다
package com.human.springboot;
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 jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
@Controller
public class HomeController {
@GetMapping("/home")
public String dohome(HttpServletRequest req,Model model) {
HttpSession sinfo =req.getSession();
if(sinfo.getAttribute("userid")==null) {
model.addAttribute("logininfo",
"<a href='/login'>로그인</a> <a href='/signin'>회원가입</a>");
}else {
model.addAttribute("logininfo",
sinfo.getAttribute("userid")+" <a href='/logout'>로그아웃</a>");
}
return "home";
}
@GetMapping("/logout")
public String doLogout(HttpServletRequest req) {
HttpSession sinfo = req.getSession();
sinfo.invalidate();
return "redirect:/home";
}
@GetMapping("/login")
public String showlogin() {
return "login";
}
@PostMapping("/doLogin")
public String doLogin(HttpServletRequest req) {
String loginid = req.getParameter("loginid");
String pwd= req.getParameter("passcode");
System.out.println("loginid["+loginid+"] pwd ["+pwd+"]");
HttpSession sinfo=req.getSession();
if(loginid.equals("yeon")&&pwd.equals("123")) {
sinfo.setAttribute("userid",loginid);
}
return "redirect:/home";
}
@GetMapping("/signin")
public String dosignin() {
return "signin";
}
}
<결과>
로그인한 화면 | 로그아웃을 누르면 |
![]() |
![]() |
<코드>
homecontroller
package com.human.springboot;
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 jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
@Controller
public class HomeController {
@GetMapping("/home")
public String dohome(HttpServletRequest req,Model model) {
HttpSession sinfo =req.getSession();
if(sinfo.getAttribute("userid")==null) {
model.addAttribute("logininfo",
"<a href='/login'>로그인</a> <a href='/signin'>회원가입</a>");
}else {
model.addAttribute("logininfo",
sinfo.getAttribute("userid")+" <a href='/logout'>로그아웃</a>");
}
return "home";
}
@GetMapping("/logout")
public String doLogout(HttpServletRequest req) {
HttpSession sinfo = req.getSession();
sinfo.invalidate();
return "redirect:/home";
}
@GetMapping("/login")
public String showlogin() {
return "login";
}
@PostMapping("/doLogin")
public String doLogin(HttpServletRequest req) {
String loginid = req.getParameter("loginid");
String pwd= req.getParameter("passcode");
System.out.println("loginid["+loginid+"] pwd ["+pwd+"]");
HttpSession sinfo=req.getSession();
if(loginid.equals("yeon")&&pwd.equals("123")) {
sinfo.setAttribute("userid",loginid);
}
return "redirect:/home";
}
@GetMapping("/signin")
public String dosignin() {
return "signin";
}
@PostMapping("/doSignin")
public String doSignin(HttpServletRequest req) {
HttpSession sinfo = req.getSession();
String loginid = req.getParameter("loginid");
sinfo.setAttribute("userid", loginid);
return "redirect:/login";
}
}
login
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<form method="post" action="/doLogin">
<table>
<tr><td>ID</td><td><input type=text name=loginid value=<%=session.getAttribute("userid") %>></td></tr>
<tr><td>PASSWORD</td><td><input type=password name=passcode ></td></tr>
<tr><td colspan=2 align=center>
<input type=submit value='로그인'>
<input type=reset value='비우기'>
</td></tr>
</table>
</form>
</body>
</html>
<결과>
/sigin | 로그인버튼 누른후 |
![]() |
![]() |
<코드>
sigin [비밀번호 체크하기]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signin</title>
</head>
<body>
<form action="/doSignin" method="post" id=frmSignin>
<table>
<th colspan="2"><h2>회원가입</h2></th>
<tr><td>아이디 </td><td><input type="text" style="width: 130px;" name="loginid" placeholder="아이디 입력."></td></tr>
<tr><td>비밀번호 </td>
<td><input type="password" style="width: 130px;" name="passcode" placeholder="비밀번호 입력."></td></tr>
<tr><td>비밀번호확인 </td>
<td colspan="2"><input type="password" style="width: 130px;" name="checkpasscode" placeholder="비밀번호 다시 확인.">
<span id="same" size="'5"></span></td></tr>
<tr >
<td colspan="2" align="left">관심분야<br>
<input id='interest' type="checkbox" name="interest" value="ploitics">정치
<input id='interest' type="checkbox" name="interest" value="economy">경제
<input id='interest' type="checkbox" name="interest" value="society">사회<br>
<input id='interest' type="checkbox" name="interest" value="IT">정보통신
<input id='interest' type="checkbox" name="interest" value="sports">스포츠
<input id='interest' type="checkbox" name="interest" value="finance">금융<br>
<input id='interest' type="checkbox" name="interest" value="talent">연예
<input id='interest' type="checkbox" name="interest" value="realty">부동산
<input id='interest' type="checkbox" name="interest" value="healthy">건강<br><br></td>
</tr>
<tr><td colspan=2 align=center>
<input type=submit value='로그인'>
<input type=reset value='비우기'></td>
</tr>
</table>
</form>
</body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document)
.on('submit','#frmSignin',function(){
if($('input[name=passcode]').val()!=$('input[name=checkpasscode]').val()){
alert('비밀번호와 비밀번호 확인이 서로 다릅니다.');
return false;//submit 중단
}
return true; //submit계속진행
})
</script>
</html>
<결과>
[Spring project 이동방법]
1. 저장(export) : 저장할 프로젝트 선택 후, export>General>Archive File>zip
2. Import : import>General>Existing project into Workspace>zip파일 선택
[Controller 만드는방법]
1. 프로젝트 안에서 Java Resources > /src/main/java > 패키지 안에 java class생성
2. class 이름위에 @Controller 추가하고, import controller
@GetMapping(URL)
@PostMapping(URL)
@RequestMapping(URL)
@RequestMapping(value=URL, method=RequestMethod.GET/POST)
Lombok
class Member{
String id;
String name;
// getter/setter
}
GET | 주소창을 타고 넘어가기 때문에 서버로 보내는 데이터를 사용자가 그대로 볼 수 있습니다. 그래서 보안에 취약합니다. 최대 255문자까지 데이터를 전송할 수 있다. |
<form method=get QueryString on 주소창 document.location='...' |
POST | POST : html header에 실려서 서버로 데이터가 전달되므로 보안에 강합니다. 255문자 이상의 데이터도 전송할 수 있다. | <form method=post javascript로도 가능 |
<% %> | Scriptlet |
<%! %> | 선언부(여기 선언된 변수는 웹서비스가 재시작할 때까지 값이 유지된다) |
<%= %> | <% out.println(); %> |
<%-- --%> | comment(주석,설명문) |
<%@ %> | directive(지시자) |
<[<%= %>]코드>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
for (int i=2;i<=9;i++){
%>
<%=i+"단<br>"%>
<% for(int j=1;j<=9;j++){ %>
<%=i+"x"+j+"="+(i*j)+"<br>" %>
<%} %>
<%="<br>"%>
<%} %>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
for (int i=2;i<=9;i++){
out.println(i+"단<br>");
for(int j=1;j<=9;j++){
out.println(i+"x"+j+"="+(i*j)+"<br>");
}
out.println("<br>");
}
%>
</body>
</html>
<결과>
<[<%! %>]코드>
선언은 한 번만 해주고 그 값으로 돌아오지 않는다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page session="true" %>
<%!
int global_cnt=0;
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int local_cnt=0;
out.print("<br>local_cnt : ");
out.print(++local_cnt);
out.print("<br>global_cnt : ");
out.print(++global_cnt);
%>
</body>
</html>
<결과>
첫화면 | 새로고침 | 계속 새로고침 : 계속 늘어난다. |
![]() |
![]() |
![]() |
<코드>
절대값
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%!
String str="Hello World";
int a=5, b=-5;
public int abs(int n){
if(n<0){
n=-n;
}
return n;
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=str %><br>
<%=a %>의 절대값:<%=abs(a) %><br>
<%=b %>의 절대값:<%=abs(b) %><br>
</body>
</html>
<결과>
<코드>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.Calendar" %>
<%@ page import="java.text.SimpleDateFormat" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Calendar date = Calendar.getInstance();
SimpleDateFormat today=new SimpleDateFormat("yyyy년 MM월 dd일");
SimpleDateFormat now=new SimpleDateFormat("hh시 mm분 ss초");
%>
오늘은 <b><%=today.format(date.getTime()) %></b>입니다.<br>
지금시각은 <b><%=now.format(date.getTime()) %></b>임니다.
</body>
</html>
<결과>
<코드>
test1
<%@ include file="head.jsp" %>
<%@ include file="footer.jsp" %>
test
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="head.jsp" %>
<%
Calendar date = Calendar.getInstance();
SimpleDateFormat today=new SimpleDateFormat("yyyy년 MM월 dd일");
SimpleDateFormat now=new SimpleDateFormat("hh시 mm분 ss초");
%>
오늘은 <b><%=today.format(date.getTime()) %></b>입니다.<br>
지금시각은 <b><%=now.format(date.getTime()) %></b>입니다.
<%@ include file="footer.jsp" %>
head
<%@ page import="java.util.Calendar" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="myjs.js"></script>
<body>
footer
</body>
</html>
<결과>
<코드>
한글이 깨지지 않게 하기 위해서 한글을 쓴 곳에다가는 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 을 넣어줘야 한다. |
test1
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="head.jsp" %>
안녕하시오!!!
<%@ include file="footer.jsp" %>
<결과>
누가 주4일제로 만들어줬음 조컷당!!!
2023.03.03 (0) | 2023.03.03 |
---|---|
2023.03.02 (0) | 2023.03.02 |
2023.02.27 (0) | 2023.02.27 |
2023.02.24 (0) | 2023.02.24 |
2023.02.23 (0) | 2023.02.23 |