2012-07-02 4 views
1

나는 모든 웹을 검색하여 답을 찾고 있지만 그럴 수 없었다. 나는 누군가가 같은 문제를 다루기를 희망한다.Spring MVC를 사용하여 Freemarker 템플릿의 RequestParameters를 읽음

Spring MVC (3.1) 및 Freemarker (2.3.16)를 기반으로 응용 프로그램을 개발 중입니다. 내 Freemarker 설정은 다음과 같습니다.

<!-- FreeMarker parsing --> 
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> 
    <property name="templateLoaderPath" value="/WEB-INF" /> 

    <property name="freemarkerSettings"> 
     <props> 
      <prop key="default_encoding">UTF-8</prop> 
      <prop key="output_encoding">UTF-8</prop> 
     </props> 
    </property> 

</bean> 


<bean id="viewResolver" 
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> 
     <property name="cache" value="true" /> 
     <property name="prefix" value="/views/" /> 
     <property name="suffix" value=".ftl" /> 

     <property name="requestContextAttribute" value="rc"></property> 

     <!-- if you want to use the Spring FreeMarker macros, set this property to true --> 
     <property name="exposeSpringMacroHelpers" value="true" /> 

     <property name="contentType" value="text/html;charset=UTF-8"></property> 

     <property name="exposeRequestAttributes" value="true" /> 
      <property name="exposeSessionAttributes" value="true" /> 

</bean> 

매우 간단합니다. 레이아웃/뷰 렌더링에 문제가 없습니다. 문제는 Spring Controller와 Request Parameters를보기에 쓰는 것입니다. 가능한 가장 간단한 컨트롤러 동작은 다음과 같습니다.

@RequestMapping(value={"/simplest/action","/simplest"}, method=RequestMethod.GET) 
@Transactional 
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

    ModelAndView mv = new ModelAndView("/simplest/action");   
    mv.addObject("myCustomIdFromView", "66666"); 
    return mv; 
    } 

보기가 성공적으로 렌더링됩니다. 이보기에서 나는 그런 건축을 사용한다 :

그러나 그런 건축 Freemarker에는 아무 가치도 없다. 입력 내용을 다음으로 변경하면

<input type="hidden" name="myCustomIdFromView" id="myCustomIdFromView" value="${myCustomIdFromView!'default'}" /> 

'default'가 올바르게 렌더링됩니다. 그래서 RequestParameters로 전환했습니다. 그리고 또 다른 이상한 일. 구성 :

{$RequestParameters.myCustomIdFromView} 
{$RequestParameters['myCustomIdFromView']} 

Freemarker 'undefined'의 값이 비어 있습니다.

마침내 그러한 해결책을 찾았습니다.

<#assign myCustomIdFromView = '' /> 
<#list RequestParameters?keys as key> 
<#if key == 'myCustomIdFromView'> 
    <#assign myCustomIdFromView = RequestParameters[key] /> 
    ${myCustomIdFromView} 
</#if> 
</#list> 

IT 작업 중! 누구나 ModelAndView에 인수를 전달하고 템플릿에서 렌더링하는 것과 같은 간단한 문제에 왜 문제가 있는지 말해 줄 수 있습니까? 값은 (모델에서 볼 수 있듯이) 모델/요청 매개 변수이지만 문제를 일으키는 Freemarker입니까? 어떤 도움을 주셔서 감사합니다.

건배, Chlebik

+0

'$ {myCustomIdFromView! 'default'}'는'default'를 출력합니다. 그러나'$ {myCustomIdFromView} '는 예외를 발생시키지 않습니까? 너무 틀렸어.스프링 MVC가 FreeMarker를 그렇게 구성하지 않기를 바란다. 또한,'RequestParameters'는 요청 - 객체 속성이 아닌 HTTP 요청 쿼리 문자열과 양식 매개 변수를 참조합니다 ('Request.theAttributeName'라고 생각합니다). "나는 정의되지 않은 Freemarker의 빈 값을받습니다." 어쨌든? – ddekany

+0

매우 명확하게 작성하지 않았습니다. 표준 메시지를 받았습니다. 'freemarker.core.InvalidReferenceException : Expression myCustomIdFromView가 정의되지 않았습니다.' – Chlebik

+0

마지막 예제는 여전히 의미가 없습니다. 6666을 인쇄합니까? 이상하게 들릴 것이다. (myCustomIdFromView라는 쿼리 매개 변수 나 폼 필드가 없다면). 그럼에도 불구하고 예제는'$ {RequestParameters.myCustomIdFromView! ''}'로 단순화 될 수 있습니다. – ddekany

답변

1

내가 잘못 알아 냈다. 나는 Spring MVC를 사용하고있다. 따라서 모든 -servlet.xml 구성 파일이 기본적으로로드된다는 기본 규칙이 있습니다.

frontcontroller-servlet.xml에는 applicationContext.xml이 포함 된 수입 문이 입니다. 이 파일에는 config 파일의 조각 모음을 지원하기 위해 DB, 컨트롤러 등의 구성을 사용하는 다른 3 가지 가져 오기 기능이 있습니다.

는하지만 워싱턴은 또한 web.xml에에서 제공하는이었다

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 
<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:applicationContext*</param-value> 
</context-param> 

그리고 결합이 두 가지의 결과는 표준 스프링 빈의 이중 창조했다. 갑자기 내 애플리케이션을 배포 할 수 없었던 Spring Security와의 통합을 시작했을 때 예외가 있었고 기존의 이중 빈 (double bean)에 대한 지적이있었습니다 (@Autowire 주석이 미쳐 버렸습니다).

그래서 스프링 내부 (또는 스프링 자체)의 클래스 내부에 무언가가 발생했으며 두 개 모델 (요청 매개 변수 포함)이 존재한다고 가정합니다. 지금 당장 - 질문에서 코드를 사용할 때 모든 것이 올바르게 렌더링됩니다.

관련 문제