이번 포스트에서는 Spring framwork에서 다양한 JSP form tag 를 사용하는 프로그램을 작성할 것이다.
IntelliJ를 이용하여 webapp을 설정하고 Maven 프로젝트를 설정한다.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SpringExample-Form</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringExample-Form Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Servlet Dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringExample-Form</finalName>
</build>
</project>
Model - User.java
View - user.jsp(입력) & users.jsp(결과확인)
Controller - UserController.java
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.example"})
public class MVCConfig implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver resolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
ViewResolver에서 view의 주소를 설정해주어 URL path를 설정해준다.
package com.example.config;
import com.example.config.MVCConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class < ? > [] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Class < ? > [] getServletConfigClasses() {
return new Class[] {
MVCConfig.class
};
}
@Override
protected String[] getServletMappings() {
return new String[] {
"/"
};
}
}
이전 포스팅과 내용은 동일하다
package com.example.model;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String[] favoriteFramework;
private String gender;
private String favoriteNumber;
private String country;
}
lombok을 사용하여 코드의 길이를 줄였다.
달라진점은 boolean type과 String[]를 추가하여서 사용하였다.
package com.example.controller;
import com.example.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user(){
User user = new User();
user.setFavoriteFramework((new String[]{
"Spring MVC",
"Struts 2"
}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb") User user, ModelMap model){
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks",user.getFavoriteFramework());
model.addAttribute("gender", user.getGender());
model.addAttribute("favoriteNumber", user.getFavoriteNumber());
model.addAttribute("country", user.getCountry());
return "users";
}
@ModelAttribute("webFrameworkList")
public Object[] getWebFrameworkList(){
List< String > webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Structs 1 ");
webFrameworkList.add("Structs 2 ");
webFrameworkList.add("Apache Wicket");
return webFrameworkList.toArray();
}
@ModelAttribute("numbersList")
public List <String> getNumbersList(){
List <String> numbersList = new ArrayList<String>();
numbersList.add("1");
numbersList.add("2");
numbersList.add("3");
numbersList.add("4");
return numbersList;
}
@ModelAttribute("countryList")
public Map <String,String> getCountryList(){
Map<String, String > countryList = new HashMap < String, String> ();
countryList.put("US", "United States");
countryList.put("CH", "China");
countryList.put("SG", "Singapore");
countryList.put("MY", "Malaysia");
return countryList;
}
}
이번 포스팅에서 가장많이 바뀐부분은 Controller라고 할 수 있다.
ModelAndView는 처음 user 객체에 대한 초기 설정을 해주는 메서드다.
먼저 객체를 생성하고, favoriteFramework를 "Spring MVC"와 "Struts 2"로 설정해준다.
또한 gender은 "M" 으로 설정해준다.
반환값으로 modelAndView를 "user","command"의 key값과 생성한 user의 객체의 value값을 반환한다.
user.jsp에서 입력된 값의 데이터들을 user.get형식으로 가져와서 model.addAttribute로 View(users 결과 페이지)페이지로 넘겨준다.
List에 들어갈 값들을 추가한 다음 배열 형식으로 return 해준다. 이 값들은 favoriteFramework에서 설정할 값들이다.
마찬 가지로 model의 country를 설정하는 메서드이며 List대신 HashMap을 사용하여 값을 추가하였다.
HashMap?
HashMap은 Key와 Value값으로 데이터를 저장을 한다. Key값은 중복될 수 없으며, Value값은 Key값이 다를 경우에만 중복될 수 있다.
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%><%@ page isELIgnored="false" %>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "addUser">
<table>
<tr>
<td>
<form:label path = "username">User Name</form:label>
</td>
<td>
<form:input path = "username" />
</td>
</tr>
<tr>
<td>
<form:label path = "password">Password</form:label>
</td>
<td>
<form:password path = "password" />
</td>
</tr>
<tr>
<td>
<form:label path = "address">Address</form:label>
</td>
<td>
<form:textarea path = "address" rows = "5" cols = "30" />
</td>
</tr>
<tr>
<td>
<form:label path = "receivePaper">Subscribe Newsletter</form:label>
</td>
<td>
<form:checkbox path = "receivePaper" />
</td>
</tr>
<tr>
<td>
<form:label path = "favoriteFramework">Favorite Web Frameworks</form:label>
</td>
<td>
<form:checkboxes items = "${webFrameworkList}" path = "favoriteFramework" />
</td>
</tr>
<tr>
<td>
<form:label path = "gender">Gender</form:label>
</td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male" />
<form:radiobutton path = "gender" value = "F" label = "Female" />
</td>
</tr>
<tr>
<td>
<form:label path = "favoriteNumber">Favorite Number</form:label>
</td>
<td>
<form:radiobuttons path = "favoriteNumber" items = "${numbersList}" />
</td>
</tr>
<tr>
<td>
<form:label path = "country">Country</form:label>
</td>
<td>
<form:select path = "country">
<form:option value = "NONE" label = "Select"/>
<form:options items = "${countryList}" />
</form:select>
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td>
<% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%>
</td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
<tr>
<td>Favourite Number</td>
<td>${favoriteNumber}</td>
</tr>
<tr>
<td>Country</td>
<td>${country}</td>
</tr>
</table>
</body>
</html>
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
상단에 form tag의 library를 사용하기 위해서 jsp파일 상단에 이 코드를 작성하였다.
https://www.javaguides.net/2018/10/spring-mvc-jsp-form-tags-tutorial.html