728x90
반응형
👩💻 자바 개발자 양성과정 55일차
- SpringMVC에서 POST/GET가져오기
- 로그인 구현
- 회원가입 구현
- POST 한글 값 깨짐 해결
아침에 엄마가 눈이왔다고 했다 11월에 벌써 눈이라니..
쌓인 눈은 아니여서 바로 사라졌지만 이불속이 너무 아늑하게 느껴져서 오늘은 집에서 온라인 수업을 들었다.
SpringMVC에서 POST/GET가져오기
🚩 첫번째, HttpServletRequest를 이용한 방법
package com.example.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.vo.UserVO;
@Controller
public class ReuestController {
// 첫번째, HttpServletRequest를 이용한 방법
@RequestMapping(value = "/confirm", method = RequestMethod.GET) // /biz/confirm
public String confirm(HttpServletRequest request, Model model) {
String userid = request.getParameter("userid");
String passwd = request.getParameter("passwd");
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String gender = request.getParameter("gender");
model.addAttribute("userid", userid);
model.addAttribute("passwd", passwd);
model.addAttribute("name", name);
model.addAttribute("age", age);
model.addAttribute("gender", gender);
return "confirm"; // /WEB-INF/views + /confirm + .jsp
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Impormation</title>
</head>
<body>
<h3>HttpServletRequest을 이용한 방법</h3>
userid : ${username}<br>
passwd : ${passwd}<br>
name : ${name}<br>
age : ${age}<br>
gender : ${gender}
</body>
</html>
🚩 두번째, @RequestParam을 이용한 방법
package com.example.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.vo.UserVO;
@Controller
public class ReuestController {
// 두번째, @RequestParam을 이용한 방법
@RequestMapping(value = "/confirm1", method = RequestMethod.GET) // /biz/confirm1
public String confirm1(@RequestParam("userid") String userid, @RequestParam("passwd") String passwd,
@RequestParam("name") String name, @RequestParam("age") int age, @RequestParam("gender") String gender,
Model model) {
model.addAttribute("userid", userid);
model.addAttribute("passwd", passwd);
model.addAttribute("name", name);
model.addAttribute("age", age);
model.addAttribute("gender", gender);
return "confirm1"; // /WEB-INF/views + /confirm1 + .jsp
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Impormation</title>
</head>
<body>
<h3>@RequestParam을 이용한 방법</h3>
userid : ${userid}<br>
passwd : ${passwd}<br>
name : ${name}<br>
age : ${age}<br>
gender : ${gender}
</body>
</html>
🚩 세번째, @RequestParam을 이용한 방법 2 - addAttribute에 vo타입을 담아 넘기기
package com.example.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.vo.UserVO;
@Controller
public class ReuestController {
// 세번째,@RequestParam을 이용한 방법 - 2 addAttribute에 vo타입을 담아 넘기기
@RequestMapping(value = "/confirm2", method = RequestMethod.GET) // /biz/confirm2
public String confirm2(@RequestParam("userid") String userid, @RequestParam("passwd") String passwd,
@RequestParam("name") String name, @RequestParam("age") int age, @RequestParam("gender") String gender,
Model model) {
UserVO user = new UserVO();
user.setUserid(userid);
user.setPasswd(passwd);
user.setName(name);
user.setAge(age);
user.setGender(gender);
model.addAttribute("userinfo", user);
return "confirm2"; // /WEB-INF/views + /confirm2 + .jsp
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="user" value="${userinfo}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Impormation</title>
</head>
<body>
<h3>@RequestParam을 이용한 방법 - 2 addAttribute에 vo타입을 담아 넘기기</h3>
userid : ${userinfo.userid}<br>
passwd : ${userinfo.passwd}<br>
name : ${userinfo.name}<br>
age : ${userinfo.age}<br>
gender : ${userinfo.gender}
</body>
</html>
🚩 네번째, Data Commander 2 - 스프링을 이용하는 방법
\src\main\java\com\example\controller\ReuestController.java
package com.example.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.vo.UserVO;
@Controller
public class ReuestController {
// 네번째,스프링을 이용하는 방법
@RequestMapping(value = "/confirm3", method = RequestMethod.GET) // /biz/confirm3
public String confirm3(UserVO user) {
return "confirm3"; // /WEB-INF/views + /confirm3 + .jsp
}
}
\src\main\webapp\WEB-INF\views\confirm3.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="user" value="${userVO}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Impormation</title>
</head>
<body>
<h3>스프링을 이용하는 방법</h3>
userid : ${user["userid"]}<br>
passwd : ${user.passwd}<br>
name : ${user.name}<br>
age : ${user.age}<br>
gender : ${user.gender}
</body>
</html>
🚩 네번째, @PathVariable 이용한 방법
package com.example.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.vo.UserVO;
@Controller
public class ReuestController {
// 다섯번째, @PathVariable 이용한 방법
@RequestMapping(value = "/confirm4/{userid}/{passwd}/{name}/{age}/{gender}", method = RequestMethod.GET)
public String confirm4(@PathVariable String userid, @PathVariable String passwd, @PathVariable String name,
@PathVariable int age, @PathVariable String gender, Model model) {
model.addAttribute("userinfo", new UserVO(userid, passwd, name, age, gender));
return "confirm4"; // /WEB-INF/views + /confirm4 + .jsp
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="user" value="${userinfo}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Impormation</title>
</head>
<body>
<h3>@PathVariable 이용한 방법</h3>
userid : ${user["userid"]}<br>
passwd : ${user.passwd}<br>
name : ${user.name}<br>
age : ${user.age}<br>
gender : ${user.gender}
</body>
</html>
🚩 로그인 구현
\src\main\java\com\example\biz\HomeController.java
package com.example.biz;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.example.vo.UserVO;
import lombok.extern.java.Log;
/**
* Handles requests for the application home page.
*/
@Controller
@Log
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam("userid") String userid, @RequestParam("passwd") String passwd, Model model) {
log.info("post방식");
model.addAttribute("userid", userid);
model.addAttribute("passwd", passwd);
return "login"; // /WEB-INF/views + /login + .jsp
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(@RequestParam("userid") String userid, @RequestParam("passwd") String passwd) {
log.info("get방식");
ModelAndView mav = new ModelAndView();
mav.addObject("userid", userid);
mav.addObject("passwd", passwd);
mav.setViewName("login");
return mav;
}
}
\src\main\webapp\resources\login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 폼</title>
</head>
<body>
<form method="POST" action="/biz/login">
아이디 : <input type="text" name="userid" /><br />
패스워드 : <input type="password" name="passwd" /><br />
<input type="submit" value="로그인하기" />
</form>
</body>
</html>
\src\main\webapp\WEB-INF\views\login.jsp
<%@ 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>
아이디 : ${userid} <br />
패스워드 : ${passwd}
</body>
</html>
🚩 회원가입 구현 + POST 한글 값 깨짐 해결방법
package com.example.biz;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.example.vo.UserVO;
import lombok.extern.java.Log;
/**
* Handles requests for the application home page.
*/
@Controller
@Log
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(UserVO user) {
log.info(user.toString());
return "register"; // /WEB-INF/views + /register + .jsp
}
}
위에서 파라미터를 UserVO user로 사용할 수 있었던 건
POST로 받아오는 name들이 UserVO내 요소들과 이름이 같기 때문이다.
만약 달랐다면 어떻게 되는지 보여준다. | |
UserVO package com.example.vo; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class UserVO { private String userid; private String passwd; private String name; private int age; private String gender; } |
register.html <form method="POST" action="/biz/register"> 아이디 : <input type="text" name="userid1" /><br /> 패스워드 : <input type="password" name="passwd1" /><br /> 이름 : <input type="text" name="name" /><br /> 나이 : <input type="number" name="age" /><br /> 성별 : 남성 <input type="radio" name="gender" value="남성" /> 여성 <input type="radio" name="gender" value="여성" /> <br /> <input type="submit" value="가입하기" /> </form> |
form내 name과 vo요소에 이름이 같은 건 정상적으로 받아오지만, 다른 userid와 passwd는 받아오지 못하는 모습이다. |
\src\main\webapp\resources\register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원가입 폼</title>
</head>
<body>
<form method="POST" action="/biz/register">
아이디 : <input type="text" name="userid" /><br />
패스워드 : <input type="password" name="passwd" /><br />
이름 : <input type="text" name="name" /><br />
나이 : <input type="number" name="age" /><br />
성별 : 남성 <input type="radio" name="gender" value="남성" />
여성 <input type="radio" name="gender" value="여성" /> <br />
<input type="submit" value="가입하기" />
</form>
</body>
</html>
GET에서는 한글이 깨지지 않는데, POST상태에서 가입을 진행해보면 log에 한글이 깨지는 걸 확인할 수 있다.
그래서 web.xml에 필터를 추가해어야 한다.
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
이거 추가해주고 다시 확인해보자.
🚩 Spring Redirect - 회원 구분에 따라 Redirect하기
@RequestMapping(value = "/verify", method = RequestMethod.GET) // /biz/verify?userid=admin
public String verify(@RequestParam("userid") String userid, Model model) {
if (userid.equals("admin")) {
return "redirect:admin";// /biz/admin
}
return "redirect:user"; // /biz/user
// return "redirect:http://www.naver.com"; //절대 경로도 가능
}
// /biz/admin 일때 실행
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public void admin() {
log.info("관리자 안녕!");
}
// /biz/user 일때 실행
@RequestMapping(value = "/user", method = RequestMethod.GET)
public void user() {
log.info("회원 안녕!");
}
http://localhost:8080/biz/verify?userid=admin 로 접속을 하면
/biz/admin 로 이동한다. redirect답게 주소가 바뀌는걸 확인 할 수 있다.
728x90
반응형