본문 바로가기

Back-End/Java

[Spring] 웹에서 파라미터 전달받아 출력하기

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<form action="/" method="get">
	id: <input name="id" type="text"> //id text box
	<input value="보내기" type="submit"> //submit 버튼
</form>

사용자로부터 값을 입력받아 컨트롤러로 전달할 페이지입니다.




컨트롤러에서 처리할 2가지 방법을 소개합니다.


1. Model 방식

HomeController.java

package com.example.spring; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping(value = "/", method = RequestMethod.GET) //경로 public String home(Locale locale, Model model, HttpServletRequest request) { logger.info("Welcome home! The client locale is {}.", locale); String testId = request.getParameter("id"); //웹에서 전달받은 값 model.addAttribute("testId", testId ); return "formComplete"; //리턴될 jsp 경로 } }



2. ModelAndView 방식

HomeController.java

package com.example.spring;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		
		String testId = request.getParameter("id"); //웹에서 전달받은 값
		
		mv.addObject("testId", testId );
		mv.setViewName("formComplete"); //리턴될 jsp 경로
		
		return mv;
	}