반응형
프로젝트를 진행 중에, spring security 를 이용해서 로그인을 하는 과정에서 로그인을 성공한 후에 jsp 로 로그인한 정보를 보내는 과정을 뒤져보는 과정에서 발견한 방법!!!
그건 HttpServletResponse 의 printWriter를 이용한 방법이었다.
1. login.jsp
ajax를 이용하여 spring security 를 이용하여 로그인 프로세스를 타게 했다.
$.ajax({
url: './loginCheck',
data: datas,
type: 'POST',
dataType: 'json',
}).done(function(body) {
console.log(body);
var error = body.response.error;
});
login 로직을 탄 후에 받아오는 데이터 타입을 json으로 정의를 해두었다. 그래서 java에서도 보내는 데이터타입이 json 형태이어야한다. 아니면? 에러뜸!!! 주의해야함
2. AuthenticationSuccessHandlerImpl.java
로그인 로직이 성공했을 때 타게 spring-security.xml 에 설정해둔 implement 에 있는 메서드에 response를 받아오는 변수로 넣어두고 reponse.getWriter().print() 를 이용하여 위에 설정해둔 ajax의 결과값에 보내보자!
※주의! contentType, characterEncoding 을 설정해주어야하고, print할 데이터는 꼭! json 값이어야함!! 아니길원하면 ajax 의 dataType 을 원하는 타입으로 수정하면 된다.
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth) throws IOException, ServletException {
String rUrl = defaultUrl;
res.setContentType("application/json");
res.setCharacterEncoding("utf-8");
String data = "{\"response\":{\"error\":false,\"url\":\""+rUrl+"\", \"id\": \""+"userId"+"\", \"role\": \""+"roleId"+"\"}}";
PrintWriter out = res.getWriter();
out.print(data);
}
3. 로그인 후, console 확인
response object가 보내졌고, 보낸 data가 console에 찍혀있는걸 확인할 수 있다!!!!!
반응형
반응형
'웹앱프로젝트 > Java' 카테고리의 다른 글
[JAVA] Spring Boot 에서 JJWT로 JWT 생성 구현 (1) | 2022.09.05 |
---|---|
[JWT] com.auth0 vs io.jsonwebtoken 어떤 것을 사용할 것이냐? (0) | 2022.09.05 |
AES-256 암호화 과정 (0) | 2022.07.19 |
cmd 창에서 java 파일 compile 해서 실행하기 (0) | 2022.04.18 |
EL으로 List 길이 뿌려주기 (0) | 2022.01.10 |