Spring IntelliJ 활용법
서버를 구축했다면 이제 컨트롤러 클래스를 만들어줘야 한다.
@Controller로 어노테이션 기능으로 추가하고
@GetMapping ( / ) 중에 ( / )는 주소인데 주소값이 없으니 가장 디폴트로 실행된다.
내용은 String 타입을 리턴하고 , 메소드명은 index , 실행하면 String 값 "index"를 리턴한다.
IntelliJ에서는 리턴한 값 내용을 찾아서 그 내용을 가진 jsp를 실행하게 된다.
버튼 1 , 2번은 onclick 이벤트로 누르면 각각 fun1() , fun2() 함수를 실행한다.
a 태그로 각각 hello3 , hello4 , hello5 링크를 만들었다.
fun1() 함수는 누르면 hello1이라는 jsp파일을 찾아가서 실행한다.
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/">index.jsp로 돌아가기</a>
<form action="/form-param1" method="get">
<input type="text" name="p1"><br>
<input type="text" name="p2"><br>
<input type="submit" value="전송"><br>
</form>
<form action="/form-param2" method="post">
<input type="text" name="p3"><br>
<input type="text" name="p4"><br>
<input type="submit" value="전송"><br>
</form>
</body>
</html>
다시 index로 돌아가는 a 태그와
각각 get방식 , post 방식을 가진 form 태그가 있다.
여기서 이제 중요한 name값은 입력한 값을 가지는 이름이다.
form 타입의 전송버튼을 누르면 입력했던 값이 action 속성값으로 전송된다.
그러면 Controller에도 각 메서드를 만들어놔야 한다.
@GetMapping("/form-param1")
public String parameter1 (HttpServletRequest request) {
String v1 = request.getParameter("p1");
String v2 = request.getParameter("p2");
System.out.println("p1 = " + v1);
System.out.println("p2 = " + v2);
return "index";
}
@RequestMapping(value = "/form-param2", method = RequestMethod.POST)
public String parameter2 (@RequestParam String p3, @RequestParam String p4) {
// 변수이름과 파라미터 변수이름을 같게하면 생략가능하다.
System.out.println("p3 = " + p3 + ", p4 = " + p4);
return "index";
}
form-param1부터 보면
IntelliJ는 이렇게 값을 전달하면 자체적으로 HttpServletRequest 타입의 request 객체에 값을 보관하기 때문에
매개 변수로 request를 주고
getParameter로 그 값을 출력한 것이다.
form-param2에선 변숫값 p3 , p4가 매개변수에 같은 이름이기 때문에 생략이 가능하다.
index의 a 태그 hello4 링크를 누르게 되면
@GetMapping("/hello3")
public String hello3(Model model) {
String s1 = "안녕하세요";
model.addAttribute("m1",s1);
return "hello3";
}
Controller에서도 반응할 수 있게 GetMapping 값을 가진 메서드를 만들어놓고
이번엔 Model 타입의 model 객체에 addAttribute로 값을 수정해서 리턴할 때 보낼 수 있다.
<%--
Created by IntelliJ IDEA.
User: user
Date: 2023-04-21
Time: 오후 2:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>hello4.jsp</h2>
<h3>학생정보</h3>
학번 : ${student.id} <br>
이름 : ${student.studentName}<br>
학번 : ${student.studentNumber}<br>
한방에 : ${student}
</body>
</html>
${} 스프링문법을 사용해서 가져온 model을 뜯어서 내용을 출력할 수 있다.
이번엔 hello5 요청을 처리하는 메소드를 만들어서
studentDTO 객체를 담는 ArrayList를 선언해서 학생들 정보를 담고 리스트를 모델에 담아서 테이블로 출력해 보겠다.
package com.icia.ex1.dto;
import lombok.*;
@Getter // 모든 getter 생성
@Setter // 모든 setter 생성
@ToString // tostring 생성
@NoArgsConstructor // 기본 생성자 생성
@AllArgsConstructor // 모든 매개변수를 가진 생성자 생성
public class StudentDTO {
private Long id;
private String studentName;
private String studentNumber;
}
lombok을 이용해서 간단하게 메서드를 만들 수 있다.
dto파일은 따로 디렉터리를 만들어둔다.
index.jsp파일에 a태그를 이용해 hello5를 호출하고 , 컨트롤러에서 그 메서드를 처리해야 한다.
private StudentDTO newStudent(int i) {
StudentDTO studentDTO = new StudentDTO();
studentDTO.setId((long) i);
studentDTO.setStudentName("학생"+i);
studentDTO.setStudentNumber("11111110"+i);
return studentDTO;
}
학생들 정보를 넣을 메소드를 생성한다.
@GetMapping("/hello5")
public String hello5(Model model) {
List<StudentDTO> list = new ArrayList<>();
for(int i=0; i<=10; i++) {
list.add(newStudent(i));
}
model.addAttribute("studentList",list);
return "hello5";
}
10명의 학생을 리스트에 넣을 것이니 i <=10;으로 주고 for문을 돌려서 list에 저장하고 model에 그 list를 넣고 hello5로 전달한다.
<%--
Created by IntelliJ IDEA.
User: user
Date: 2023-04-21
Time: 오후 2:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="/resources/css/bootstrap.css">
<script src="/resources/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h2>hello5.jsp</h2>
<table class="table table-dark table-hover">
<tr>
<th>id</th>
<th>이름</th>
<th>학번</th>
</tr>
<%--items = 반복할 대상 , var : 반복변수 --%>
<%-- for(StudentDTO s: studentList)--%>
<c:forEach items="${studentList}" var="s">
<tr>
<td>${s.id}</td>
<td>${s.studentName}</td>
<td>${s.studentNumber}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
테이블을 만들고 for문으로 돌려서 tr , td 태그를 채운다.
<c:forEach items="${studentList}" var="s">
</c:forEach>
문구는
for(Student s : studentList)와 같다.
items = 반복할 대상, var는 반복변수이다.
잘 출력되는 것을 볼 수 있다, ( 부트스트랩 적용 )