웹개발 교육/Spring
[67일] spring (4) - 계산
ewok
2022. 11. 1. 14:37
새 프로젝트 생성 : spring03_web
의존성 추가
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.58</version>
</dependency>
WEB-INF - views - bbs, login 폴더 & start.jsp 생성 (jsp와 같은 뷰페이지는 모두 views 폴더에서 관리)
static에 css, js 폴더 생성, images는 기존에 있던 images 폴더 넣기
한글 인코딩
application.properties - 우클릭 - Properties에서 utf-8
application.properties
이전 시간(spring02_mvc 프로젝트)의 application.properties의 내용 복사
#주석
#/src/main/resources/application.properties 환경설정 파일
#Spring Boot는 WAS(Tomcat) 내장되어 있음(기본port번호 8080)
#톰캣서버의 http port번호 변경
server.port=9095
#주의사항 JSP, Thymeleaf, Mustache는 공통으로 사용할 수 없음
#JSP를 뷰페이지로 사용할 경우 pom.xml에 라이브러리 추가해야 함
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
서버 상태 확인하기
Spring02WebApplication.java를 spring boot app으로 run
HomeController 클래스 생성
HomeController.java
package kr.co.itwill;
public class HomeController {
public HomeController() {
System.out.println("-----HomeController()객체 생성됨");
}//end
}//class end
어노테이션 추가
package kr.co.itwill;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
//URL에서 요청, 응답이 가능한 클래스 지정. 자동 객체 생성됨(의존성 주입)
@Controller
public class HomeController {
public HomeController() {
System.out.println("-----HomeController()객체 생성됨");
}//end
//결과 확인 http://localhost:9095/home.do
//요청 명령어 등록하고, 실행의 주체는 메소드(함수)
@RequestMapping("/home.do")
public ModelAndView home() {
ModelAndView mav = new ModelAndView();
//application.properties 환경설정 참조
// /WEB-INF/views/start.jsp (prefix + ViewName + suffix)
mav.setViewName("start");
//request영역에 값 올리기
mav.addObject("message", "어서오세요!!");
return mav;
}//home() end
}//class end
start.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>start.jsp</title>
</head>
<body>
<h3>환영합니다~~</h3>
${requestScope.message}<br>
${message}<br>
</body>
</html>
새 패키지 생성
CalcController.java
package kr.co.itwill.test01;
import org.springframework.stereotype.Controller;
//URL에서 요청 명령어를 읽어서 실행해주는 클래스. 자동으로 객체 생성된다(의존성 주입)
@Controller
public class CalcController {
public CalcController() {
System.out.println("-----CalcController()객체 생성됨");
}//end
}//class end
package kr.co.itwill.test01;
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.servlet.ModelAndView;
//URL에서 요청 명령어를 읽어서 실행해주는 클래스. 자동으로 객체 생성된다(의존성 주입)
@Controller
public class CalcController {
public CalcController() {
System.out.println("-----CalcController()객체 생성됨");
}//end
//URL에서 요청한 명령어를 등록
//@RequestMapping(value="", method=GET | POST)
//결과 확인 http://localhost:9095/add.do?no1=3&no2=5
// /add.do 명령어를 get방식으로 요청하면
@RequestMapping(value="/add.do", method = RequestMethod.GET)
public ModelAndView add(HttpServletRequest req) {
//사용자가 요청한 값 가져오기
int no1 = Integer.parseInt(req.getParameter("no1"));
int no2 = Integer.parseInt(req.getParameter("no2"));
int result = no1 + no2;
//View 페이지로 이동하기 위한 클래스
//->Model
//->ModelAndView
ModelAndView mav = new ModelAndView();
//application.properties 환경설정의 prefix와 suffix 참조
// /WEB-INF/views/calcResult.jsp 뷰페이지로 이동
mav.setViewName("calcResult");
//공유장소 request영역에 값 올리기
req.setAttribute("no1", no1);
req.setAttribute("no2", no2);
req.setAttribute("result", result);
req.setAttribute("message", "<h3>두수 사이의 합</h3>");
req.setAttribute("img", "<img src='images/monkey.png'>");
return mav;
}//add() end
}//class end
calcResult.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>calcResult.jsp</title>
</head>
<body>
<h1>계산결과</h1>
<h2>1)JSP</h2>
<%=request.getAttribute("message") %>
숫자1 : <%=request.getAttribute("no1") %><br>
숫자2 : <%=request.getAttribute("no2") %><br>
결과 : <%=request.getAttribute("result") %><br>
<%=request.getAttribute("img") %>
<hr>
<h2>2)EL</h2>
${requestScope.message}<br>
숫자1 : ${requestScope.no1}<br>
숫자2 : ${requestScope.no2}<br>
결과 : ${requestScope.result}<br>
${requestScope.img }
<hr>
<h2>3)EL</h2>
${message}<br>
숫자1 : ${no1}<br>
숫자2 : ${no2}<br>
결과 : ${result}<br>
${img==null ? "" : img}
</body>
</html>
CalcController.java
//결과확인 http://localhost:9095/sub.do?no1=3&no2=5
@RequestMapping(value = "/sub.do", method = RequestMethod.GET)
public ModelAndView sub(HttpServletRequest req) {
int no1 = Integer.parseInt(req.getParameter("no1"));
int no2 = Integer.parseInt(req.getParameter("no2"));
int result = no1 - no2;
ModelAndView mav = new ModelAndView();
mav.setViewName("calcResult");
//request 영역에 값 올리기
mav.addObject("no1", no1);
mav.addObject("no2", no2);
mav.addObject("result", result);
mav.addObject("message", "<h3>두수 사이의 차</h3>");
mav.addObject("img", "<img src='images/yellowstar.png'>");
return mav;
}//sub() end
//결과확인 http://localhost:9095/mul.do?no1=3&no2=5
@RequestMapping(value = "/mul.do", method = RequestMethod.GET)
public ModelAndView mul(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {
int no1 = Integer.parseInt(req.getParameter("no1"));
int no2 = Integer.parseInt(req.getParameter("no2"));
int result = no1 * no2;
ModelAndView mav = new ModelAndView();
mav.setViewName("calcResult");
req.setAttribute("no1", no1);
req.setAttribute("no2", no2);
req.setAttribute("result", result);
req.setAttribute("message", "<h3>두수 사이의 곱</h3>");
req.setAttribute("img", "<img src='images/angel.png'>");
return mav;
}//mul() end
@RequestMapping(value = "/div.do", method = RequestMethod.GET)
public ModelAndView div(HttpServletRequest req) {
int no1 = Integer.parseInt(req.getParameter("no1"));
int no2 = Integer.parseInt(req.getParameter("no2"));
int result = no1 / no2;
ModelAndView mav = new ModelAndView();
mav.setViewName("calcResult");
req.setAttribute("no1", no1);
req.setAttribute("no2", no2);
req.setAttribute("result", result);
req.setAttribute("message", "<h3>두수 나누기</h3>");
req.setAttribute("img", "<img src='images/smile.png'>");
return mav;
}//div() end
새 클래스 생성
ComputeController.java
package kr.co.itwill.test01;
import org.springframework.stereotype.Controller;
@Controller
public class ComputeController {
public ComputeController() {
System.out.println("-----ComputeController()객체 생성됨");
}//end
}//class end
package kr.co.itwill.test01;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ComputeController {
public ComputeController() {
System.out.println("-----ComputeController()객체 생성됨");
}//end
//요청 명령어를 처리하는 메소드 매개변수의 유연성
//@RequestParam("요청변수명") 자료형 변수명
//->사용자가 요청한 값을 직접 변수에 저장 가능하다
//결과 확인 http://localhost:9095/diff.do?no1=3&no2=5
@RequestMapping("/diff.do") //GET | POST 모두 허용
public ModelAndView diff(@RequestParam("no1") int a, @RequestParam("no2") int b) {
int result = Math.abs(a-b); //두 수 사이의 차이
ModelAndView mav = new ModelAndView();
mav.setViewName("calcResult");
mav.addObject("no1", a);
mav.addObject("no2", b);
mav.addObject("result", result);
mav.addObject("message", "<h3>두수 사이의 차이</h3>");
mav.addObject("img", "<img src='images/yellowstar.png'>");
return mav;
}//diff() end
}//class end
//결과 확인 http://localhost:9095/max.do?no1=3&no2=5
//사용자가 요청한 값을 매개변수로 직접 저장 가능하다
//->단, 요청변수명과 매개변수명이 동일해야 한다
@RequestMapping("/max.do")
public ModelAndView max(int no1, int no2) {
int result = Math.max(no1, no2);
ModelAndView mav= new ModelAndView();
mav.setViewName("calcResult");
mav.addObject("no1", no1);
mav.addObject("no2", no2);
mav.addObject("result", result);
mav.addObject("message", "<h3>두수 중 큰 값</h3>");
mav.addObject("img", "<img src='images/Ruby2.png'>");
return mav;
}//max() end