Knowing which files are in which folder is crucial since the structure is more complex than other projects and we have to know where to put the correct files. 

When you run the program, the web.xml file will be the first to read. There are basic settings in the web.xml.

Let's take a look at web.xml.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<!-- Language Encoding -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- The definition of the Root Spring Container shared by all Servlets 
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

<servlet-name> is appServlet, and we can set or change the pattern. 

<filter> and <filter-mapping> is for encoding Korean values into UTF-8 with the post method. Once you set the encoding here in the web.xml, you don't need to set the encoding in the other files. If the language you or your company use is not English, you always have to take care of encoding, but with Spring, it is the only thing you need to do. 

web.xml is connected to servlet-context.xml and root-context.xml. 

servlet-context.xml

<?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/" />
	<resources mapping="/css/**" location="/WEB-INF/css/" />
	<resources mapping="/fonts/**" location="/WEB-INF/fonts/" />
	<resources mapping="/js/**" location="/WEB-INF/js/" />
	<!-- 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.ch.hello" />
</beans:beans>

In servlet-context.xml, the configuration file of Spring, you will see the extension of the view files and the directory of the view files. It is set in InternalResourceViewResolver. You must save on this route otherwise it won't run. 

Base-package has to be reversed 

 

Controller classes are in the src-main-java-com-ch-hello. The classes have annotations. 

In the HomeController.java, you see the @RequestMapping annotation  with /hello, /color, and /gugu, and you can omit the slash. 

HomeController.java

package com.ch.hello;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
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 = "/hello", method = RequestMethod.GET)
	public String hello(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		model.addAttribute("serverTime", formattedDate);
		return "home";
	}

	@RequestMapping("/color")
	public String color(Model model) {
		String[] color = { "red", "orange", "yellow", "green", "blue", "navy", "violet" };
		int num = (int) (Math.random() * 7);
		model.addAttribute("color", color[num]);
		return "color";
	}

	@RequestMapping("/gugu")
	public String gugu(Model model) {
		int num = (int) (Math.random() * 8) + 2;
//		int a = num / 0;
		model.addAttribute("num", num);
		return "gugu";
	}
	/*
	 * @ExceptionHandler(ArithmeticException.class) 
	 * public String err() { 
	 * return
	 * "arr-err"; }
	 */
}

@RequestMapping(value = "/hello", method = RequestMethod.GET) -> this format is the original, but you can also write like this: @RequestMapping("/color"). 

In the controller classes, you must use at least one of the following annotations: @Controller, @RequestMapping, @RequestParam, or @ModelAttribute. 

@Controller annotation is the most used annotation.

@RequestMapping annotation is to receive the client's request. 

@Controller
public class HomeController {
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		model.addAttribute("serverTime", formattedDate);
		return "home";
	}
}

@RequestParam is to receive the name as a value, and its role is the same as request.getParameter("name").

@Controller
public class HomeController {
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(@RequestParam(“name”) String name, Model model) {
}
}

@ModelAttribute is for receiving the value with the DTO class.

@Controller
public class HomeController {
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(@ModelAttribute BoardDTO board, Model model) {
	}
}

 

To demonstrate these concepts, I will show you an example. 

person.jsp

<form action="addr">

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Person</title>
</head>
<body>
	<h2>Name and Address</h2>
	<form action="addr">
		Name : <input type="text" name="name">
		<p>
		Address : <input type="text" name="addr">
		<p>
			<input type="submit" value="Submit">
	</form>
</body>
</html>

The name value will be passed to the Dispatcher Servlet and Controller class.

PersonController.java(Controller Class) receives the name value with the @RequestMapping annotation. It used to be the Handler, but now the annotations take its role. 

PersonController.java

package com.ch.hello;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class PersonController {
	// String name = request.getParameter("name") 
	// @RequestParam("name") String name 
	@RequestMapping("/addr")
	public String addr(@RequestParam("name") String name, 
					   @RequestParam("addr") String addr, 
					   Model model) {
		model.addAttribute("name", name);
		model.addAttribute("addr", addr);
		return "addr";
	}

	@RequestMapping("/addr2")
	public String addr2(@ModelAttribute Person p, Model model) {
		System.out.println("name: "+ p.getName());
		System.out.println("addr: "+ p.getAddr());
		
		model.addAttribute("person", p);
		return "addr2";
	}
}

addr -> @RequestParam

To print out the values, we use EL. 

addr.jsp -> @RequestParam

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>${name }, your address is ${addr }.
</body>
</html>

Person.java

 <form action="addr2">

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Person</title>
</head>
<body>
	<h2>Name and Address</h2>
		 <form action="addr2">
		Name : <input type="text" name="name">
		<p>
		Address : <input type="text" name="addr">
		<p>
			<input type="submit" value="Submit">
	</form>
</body>
</html>

addr2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body> Name: ${person.name }<br> 
Address: ${person.addr }
</body>
</html>

addr2 -> @RequestMapping

 

Sometimes, the datatypes of the controller classes are not String type. We will see the example of it. 

SampleController.java

package com.ch.hello;

import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {
	@RequestMapping("/sample")
	public SampleVo sample() {
		SampleVo sv = new SampleVo();
		sv.setMno(23);
		sv.setFirstName("Meadow");
		sv.setLastName("Cho");
		return sv;
	}

	@RequestMapping("/list")
	public List<SampleVo> list() {
		List<SampleVo> list = new ArrayList<SampleVo>();
		for (int i = 1; i <= 10; i++) {
			SampleVo sv = new SampleVo();
			sv.setMno(i);
			sv.setFirstName("Dodo");
			sv.setLastName("Cox" + i);
			list.add(sv);
		}
		return list;
	}
}

@RestController annotation is a new annotation from Spring version 4.0. The sample method has a DTO class in this controller class, and the list method has a List. 

 

DTO Class datatype

List datatype

 

+ Recent posts