이번에는 Interceptro와 ModelAndView를 이용하여 Model과 ViewName을 전달하고자한다.
<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:mvc="http://www.springframework.org/schema/mvc"
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>
-->
<beans:bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>classpath:tiles/*.xml</beans:value>
</beans:list>
</beans:property>
<beans:property name="preparerFactoryClass"
value="org.springframework.web.servlet.view.tiles2.SpringBeanPreparerFactory" />
</beans:bean>
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<beans:property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
</beans:bean>
<context:component-scan base-package="com.myspring.pro30" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*/*.do"/>
<beans:bean class="com.myspring.pro30.common.interceptor.ViewNameInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<!-- 멀티파트 리졸버 -->
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="52428800" />
<beans:property name="maxInMemorySize" value="52428800" />
<beans:property name="defaultEncoding" value="utf-8" />
</beans:bean>
</beans:beans>
위의 코드에서 살펴봐야할 부분은 아래 인터셉터 코드이다.
해당 코드의 경우 /*/*.do로된 실행문이 작동될 경우 인터셉터를 통하여 ViewNameInterceptor 클래스가 실행된다.
<ViewNameInterceptor.class>
package com.myspring.pro30.common.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class ViewNameInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
try {
String viewName = getViewName(request);
request.setAttribute("viewName", viewName);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
private String getViewName(HttpServletRequest request) throws Exception {
String contextPath = request.getContextPath();
String uri = (String) request.getAttribute("javax.servlet.include.request_uri");
if (uri == null || uri.trim().equals("")) {
uri = request.getRequestURI();
}
int begin = 0;
if (!((contextPath == null) || ("".equals(contextPath)))) {
begin = contextPath.length();
}
int end;
if (uri.indexOf(";") != -1) {
end = uri.indexOf(";");
} else if (uri.indexOf("?") != -1) {
end = uri.indexOf("?");
} else {
end = uri.length();
}
String fileName = uri.substring(begin, end);
if (fileName.indexOf(".") != -1) {
fileName = fileName.substring(0, fileName.lastIndexOf("."));
}
if (fileName.lastIndexOf("/") != -1) {
fileName = fileName.substring(fileName.lastIndexOf("/", 1), fileName.length());
}
return fileName;
}
}
그리고 인터셉트로 인해 접속된 ViewNameInterceptor에서 살펴볼 부분은 다음 메소드이다.
preHandle 메소드의 경우 ViewNameInterceptor 클래스가 상속한 HandlerInterceptorAdaptor 클래스의 메소드이다.
해당 메소드는 컨트롤러 실행 전 호출이 된다.
다음 메소드를 보면 viewName String 변수에 getgViewName 메소드를 이용하여 viewName을 저장한다.
getViewName은 아래와 같은 구조로 viewName만 저장한다.
<BoardControllerImpl.class>
아래 코드에서 볼 부분은 request.getAttribute("viewName")으로 viewName을 받아온다.
그리고 ModelANdView 클래스 mav 변수에 viewName으로 저장 후 mav.addObject로 list객체를 저장한다.
public class BoardControllerImpl implements BoardController{
private static final String ARTICLE_IMAGE_REPO = "C:\\board\\article_image";
@Autowired
BoardService boardService;
@Autowired
ArticleVO articleVO;
@Override
@RequestMapping(value= "/board/listArticles.do", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView listArticles(HttpServletRequest request, HttpServletResponse response) throws Exception {
String viewName = (String)request.getAttribute("viewName");
List articlesList = boardService.listArticles();
ModelAndView mav = new ModelAndView(viewName);
mav.addObject("articlesList", articlesList);
return mav;
}
'[책] > 자바 웹을 다루는 기술' 카테고리의 다른 글
9. 예제파일 압축 해제는 알집으로 (0) | 2020.01.16 |
---|---|
8. <mvc:resources mapping="/resources/**" location="/resources/"/>에 관하여(tiles 매핑이 잘 안될 때) (0) | 2020.01.15 |
7. pageContext.request.contextPath에 관하여 (0) | 2020.01.15 |
6. Thumnail을 사용해보자 (0) | 2020.01.14 |
5. tiles를 사용해보자 (0) | 2020.01.10 |