<참조> https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/mvc.html

Spring WEB MVC 프레임워크 (4)

 

작업중... 

9. 테마 사용

9.1 테마 개요

 

9.2 테마 정의

 

styleSheet=/themes/cool/style.css
background=/themes/cool/img/coolBg.jpg

 

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
   <head>
      <link rel="stylesheet" href="<spring:theme code='styleSheet'/>" type="text/css"/>
   </head>
   <body style="background=<spring:theme code='background'/>">
      ...
   </body>
</html>

 

9.3 테마 리졸버

 

표 5. ThemeResolver 구현

FixedThemeResolver defaultThemeName속성 을 사용하여 설정한 고정 테마를 선택합니다 .
SessionThemeResolver 테마는 사용자의 HTTP 세션에서 유지됩니다. 각 세션에 대해 한 번만 설정하면 되지만 세션 간에 지속되지는 않습니다.
CookieThemeResolver 선택한 테마는 클라이언트의 쿠키에 저장됩니다.

 

10. Spring의 멀티파트(파일 업로드) 지원

10.1 소개

 

10.2 Commons FileUploadMultipartResolver 와 함께 사용하기

 

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

 

10.3 Servlet 3.0MultipartResolver 과 함께 사용하기

 

<bean id="multipartResolver"
    class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
</bean>

10.4 양식에서 파일 업로드 처리

 

<html>
    <head>
        <title>Upload a file please</title>
    </head>
    <body>
        <h1>Please upload a file</h1>
        <form method="post" action="/form" enctype="multipart/form-data">
            <input type="text" name="name"/>
            <input type="file" name="file"/>
            <input type="submit"/>
        </form>
    </body>
</html>

 

@Controller
public class FileUploadController {
    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();
            // store the bytes somewhere
           return "redirect:uploadSuccess";
       } else {
           return "redirect:uploadFailure";
       }
    }
}

 

@Controller
public class FileUploadController {
    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam("name") String name,
        @RequestParam("file") Part file) {
        InputStream inputStream = file.getInputStream();
        // store bytes from uploaded file somewhere
        return "redirect:uploadSuccess";
    }
}

10.5 프로그래밍 방식 클라이언트의 파일 업로드 요청 처리

 

POST /someUrl
Content-Type: multipart/mixed
--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
Content-Disposition: form-data; name="meta-data"
Content-Type: application/json; charset=UTF-8
Content-Transfer-Encoding: 8bit
{
  "name": "value"
}
--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
Content-Disposition: form-data; name="file-data"; filename="file.properties"
Content-Type: text/xml
Content-Transfer-Encoding: 8bit
... File Data ...

 

@RequestMapping(value="/someUrl", method = RequestMethod.POST)
public String onSubmit(@RequestPart("meta-data") MetaData metadata,
                       @RequestPart("file-data") MultipartFile file) {
    // ...
}

 

11. 예외 처리

11.1 HandlerExceptionResolver

 

 

11.2 @ExceptionHandler

 

@Controller
public class SimpleController {
  // @RequestMapping methods omitted ...
  @ExceptionHandler(IOException.class)
  public ResponseEntity<String> handleIOException(IOException ex) {
    // prepare responseEntity
    return responseEntity;
  }
}

 

11.3 표준 스프링 MVC 예외 처리

 

 
예외 HTTP 상태 코드
BindException 400 잘못된 요청)
ConversionNotSupportedException 500 내부 서버 오류)
HttpMediaTypeNotAcceptableException 406(허용되지 않음)
HttpMediaTypeNotSupportedException 415(지원되지 않는 미디어 유형)
HttpMessageNotReadableException 400 잘못된 요청)
HttpMessageNotWritableException 500 내부 서버 오류)
HttpRequestMethodNotSupportedException 405(허용되지 않는 메서드)
MethodArgumentNotValidException 400 잘못된 요청)
MissingServletRequestParameterException 400 잘못된 요청)
MissingServletRequestPartException 400 잘못된 요청)
NoSuchRequestHandlingMethodException 404 찾을 수 없음)
TypeMismatchException 400 잘못된 요청)

 

11.4 비즈니스 예외에 주석 달기@ResponseStatus

 

11.5 기본 서블릿 컨테이너 오류 페이지 사용자 지정

 

<error-page>
    <location>/error</location>
</error-page>

 

@Controller
public class ErrorController {
    @RequestMapping(value="/error", produces="application/json")
    @ResponseBody
    public Map<String, Object> handle(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", request.getAttribute("javax.servlet.error.status_code"));
        map.put("reason", request.getAttribute("javax.servlet.error.message"));
        return map;
    }
}

또는 JSP에서:

<%@ page contentType="application/json" pageEncoding="UTF-8"%>
{
   status:<%=request.getAttribute("javax.servlet.error.status_code") %>,
   reason:<%=request.getAttribute("javax.servlet.error.message") %>
}

 

12. 구성 지원에 대한 협약

 

12.1 컨트롤러 ControllerClassNameHandlerMapping

.

public class ViewShoppingCartController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        // the implementation is not hugely important for this example...
    }
}

 

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="viewShoppingCart" class="x.y.z.ViewShoppingCartController">
    <!-- inject dependencies as required... -->
</bean>

 

12.2 모델 ModelMap ( ModelAndView)

이 클래스는 기본적 으로 표시될(또는 위에) 개체를 추가 하여 공통 명명 규칙을 준수하도록 할 수 ModelMap있는 영광 입니다. 다음 구현을 고려하십시오. 연결된 이름이 지정되지 않은 상태 에서 개체가 에 추가 됩니다.MapViewControllerModelAndView

public class DisplayShoppingCartController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        List cartItems = // get a List of CartItem objects
        User user = // get the User doing the shopping
        ModelAndView mav = new ModelAndView("displayShoppingCart"); <-- the logical view name
        mav.addObject(cartItems); <-- look ma, no name, just the object
        mav.addObject(user); <-- and again ma!
        return mav;
    }
}
  •  

뭐, 자동 복수화 안되나요?

  •  

12.3 뷰 - RequestToViewNameTranslator

 

public class RegistrationController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        // process the request...
        ModelAndView mav = new ModelAndView();
        // add data as necessary to the model...
        return mav;
        // notice that no View or logical view name has been set
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- this bean with the well known name generates view names for us -->
    <bean id="viewNameTranslator"
        class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator"/>
    <bean class="x.y.RegistrationController">
        <!-- inject dependencies as necessary -->
    </bean>
    <!-- maps request URLs to Controller names -->
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

 

 

 

반응형

+ Recent posts