[Spring] Quick Guide

나만의 빠른 가이드.

  1. STS 설치
  2. Maven 설치
  3. New Spring Legacy Project 생성
  4. pom.xml 수정
  5. Project property 수정
  6. JSTL 파일 변경
  7. Tomcat 설정 변경
  8. MySQL Workbench에서 DB Schema 및 Table 생성
  9. CRUD 구성

STS 설치

Maven 설치

New Spring Legacy Project 생성

pom.xml 수정

Spring version 변경

// before
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
// after
<org.springframework-version>4.3.10.RELEASE</org.springframework-version>

log4j-slf4j 를 dependency에 추가

Library 충돌 문제 해결을 위한 것으로, Spring 3.0 이상의 경우 아래의 코드를 pom.xml 에 추가.

JDBC와 MySQL 사용을 위한 dependency 추가

1
2
3
4
5
6
7
8
9
10
11
12
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>

Project property 수정

  1. Java 의 Version을 1.8 로 변경
  2. Project Facets 검색 > Runtimes 탭에서 Apache Tomcat V7.0 선택

JSTL 파일 변경

  1. 다운로드 : https://mvnrepository.com/artifact/javax.servlet/jstl/1.2
  2. C:\Users\사용자\.m2\repository\javax\servlet\jstl\1.2 경로의 파일 바꿔치기

Tomcat 설정 변경

  1. Eclipse의 Tomcat server 더블 클릭
  2. Server OptionsPublish module contexts to separate XML files 체크
  3. TOMCAT 재구동

한글이 깨질 경우

jsp 파일의 상단에 아래 코드 추가

<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

MySQL Workbench에서 DB Schema 및 Table 생성

예시 Table.

email: VARCHAR(100), PK, NN
password: VARCHAR(20), NN
number: VARCHAR(20)
age: INT(10), UN

CRUD 구성

Data Class 생성

사용할 Data의 Class 생성.

  • src/main/java/com.lazyrodi.crud/User.java
User.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.lazyrodi.crud;
public class User {
private String mEmail;
private String mPassword;
private String mNumber;
private int mAge;
User() {
}
User(String email, String password, String number, int age) {
mEmail = email;
mPassword = password;
mNumber = number;
mAge = age;
}
public String getEmail() {
return mEmail;
}
public String getPassword() {
return mPassword;
}
public String getNumber() {
return mNumber;
}
public int getAge() {
return mAge;
}
public void setEmail(String email) {
mEmail = email;
}
public void setPassword(String password) {
mPassword = password;
}
public void setNumber(String number) {
mNumber = number;
}
public void setAge(int age) {
mAge = age;
}
}

DAO Class 생성

Data와 Database 간 connection을 위한 DAO (Data Access Object) 생성.

  • src/main/java/com.lazyrodi.crud/UserDao.java
UserDao.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.lazyrodi.crud;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class UserDao {
JdbcTemplate mTemplate;
public void setTemplate(JdbcTemplate template) {
System.out.println("[UserDao] Created");
mTemplate = template;
}
public int save(User user) {
System.out.println("[UserDao] save(), email = " + user.getEmail());
String sql = "insert into User(email, password, number, age)"
+ "values('" + user.getEmail() + "','" + user.getPassword() + "','" + user.getNumber() + "', " + user.getAge() + ")";
return mTemplate.update(sql);
}
public int update(User user) {
System.out.println("[UserDao] update(), email = " + user.getEmail());
String sql = "update User set password='" + user.getPassword()
+ "', number='" + user.getNumber()
+ "', age=" + user.getAge()
+ " where email='" + user.getEmail() + "'";
return mTemplate.update(sql);
}
public int delete(String email) {
System.out.println("[UserDao] delete(), email = " + email);
String sql = "delete from User where email='" + email + "'";
return mTemplate.update(sql);
}
public User getUserByEmail(String email) {
System.out.println("[UserDao] getUserByEmail(), email = " + email);
String sql = "select * from User where email=?";
return mTemplate.queryForObject(sql, new Object[] {email}, new BeanPropertyRowMapper<User>(User.class));
}
public List<User> getUsers() {
System.out.println("[UserDao] getUsers()");
return mTemplate.query("select * from User", new RowMapper<User>() {
public User mapRow(ResultSet rs, int row) throws SQLException {
User user = new User();
user.setEmail(rs.getString(1));
user.setPassword(rs.getString(2));
user.setNumber(rs.getString(3));
user.setAge(rs.getInt(4));
return user;
}
});
}
}

Data를 다루기 위한 Controller 생성.

  • src/main/java/com.lazyrodi.crud/UserController.java
UserController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.lazyrodi.crud;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.ModelAndView;
@Controller
public class UserController {
@Autowired
UserDao dao;
@RequestMapping("/userform")
public ModelAndView showform() {
System.out.println("[UserController] showform()");
return new ModelAndView("userform", "command", new User());
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute("user") User user) {
System.out.println("[UserController] save(), email = " + user.getEmail());
dao.save(user);
return new ModelAndView("redirect:/viewuser");
}
@RequestMapping("/viewuser")
public ModelAndView viewuser() {
System.out.println("[UserController] viewuser()");
List<User> userList = dao.getUsers();
return new ModelAndView("viewuser", "list", userList);
}
@RequestMapping(value = "/edituser/{email:.+}")
public ModelAndView edit(@PathVariable("email") String email) {
System.out.println("[UserController] edit(), email = " + email);
User user = dao.getUserByEmail(email);
return new ModelAndView("usereditform", "command", user);
}
@RequestMapping(value = "/editsave", method = RequestMethod.POST)
public ModelAndView editsave(@ModelAttribute("user") User user) {
System.out.println("[UserController] editsave(), email = " + user.getEmail());
dao.update(user);
return new ModelAndView("redirect:/viewuser");
}
@RequestMapping(value = "/deleteuser/{email:.+}", method = RequestMethod.GET)
public ModelAndView delete(@PathVariable("email") String email) {
System.out.println("[UserController] delete(), email = " + email);
dao.delete(email);
return new ModelAndView("redirect:/viewuser");
}
}

Data 추가를 위한 form 생성

  • /src/main/webapp/WEB-INF/views/userform.jsp
userform.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<form:form method="POST" action="/crud/editsave">
<table>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:input path="password" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><form:input path="number" /></td>
</tr>
<tr>
<td>Age</td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Edit save" /></td>
</tr>
</table>
</form:form>
</body>
</html>

Data 수정을 위한 form 생성

  • /src/main/webapp/WEB-INF/views/usereditform.jsp
usereditform.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<form:form method="POST" action="editsave">
<table>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:input path="password" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><form:input path="number" /></td>
</tr>
<tr>
<td>Age</td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Edit save" /></td>
</tr>
</table>
</form:form>
</body>
</html>

Data를 보여주기 위한 view page 생성 (+삭제)

  • /src/main/webapp/WEB-INF/views/viewuser.jsp
viewuser.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>View User</title>
</head>
<body>
<h1>User List</h1>
<table>
<tr>
<th>Email</th>
<th>Password</th>
<th>Phone Number</th>
<th>Age</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="user" items="${list}">
<tr>
<td>${user.email}</td>
<td>${user.password}</td>
<td>${user.number}</td>
<td>${user.age}</td>
<td><a href="edituser/${user.email}">edit</a></td>
<td><a href="deleteuser/${user.email}">delete</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>

servlet에 bean 추가

  • /src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml
servlet-context.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.lazyrodi.crud" />
<beans:bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/스키마이름?characterEncoding=EUCKR&amp;autoReconnect=true&amp;useSSL=false" />
<beans:property name="username" value="MySQL아이디" />
<beans:property name="password" value="비밀번호" />
</beans:bean>
<beans:bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<beans:property name="dataSource" ref="ds" />
</beans:bean>
<beans:bean id="dao" class="com.lazyrodi.crud.UserDao">
<beans:property name="template" ref="jt" />
</beans:bean>
</beans:beans>
Share