Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > Spring MVC и robots.txt


Автор: m0zg 27.11.2011, 18:02
Как при такой конфигурации сделать так, чтобы robots.txt открывался?

web.xml

Код

...
<servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
</servlet-mapping>
...


spring-servlet.xml
Код

...
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="xml" value="application/xml"/>
                <entry key="html" value="text/html"/>
                <entry key="json" value="application/json"/>
                <entry key="txt" value="application/txt" />
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                    <property name="prefix" value="/WEB-INF/jsp/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
            </list>
        </property>
</bean>

<mvc:annotation-driven/>

<mvc:resources mapping="/resources/**" location="/resources/" />
...


И куда robots.txt при такой структуре положить?

Автор: Stolzen 27.11.2011, 18:47
Примерно так:
Код

@Controller
public class RobotsController {
    @RequestMapping(value = "/robots.txt", method = RequestMethod.GET) 
    public String robots() {
        return "robots";
    }
}


Где robots - это /WEB-INF/jsp/robots.jsp с нужными txt данными.

Автор: m0zg 27.11.2011, 19:23
Как ни странно:

Код

javax.servlet.ServletException: Could not resolve view with name 'robots' in servlet with name 'spring'
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1029)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)


robots.jsp в /WEB-INF/jsp/ с текстовыми данными. В контроллере:

Код

@RequestMapping(value = "/robots.txt", method = RequestMethod.GET) 
    public String robots() {
        return "robots";
    }


Странно.

Автор: m0zg 27.11.2011, 20:47
Вот так возвращает правильно:

Код

@RequestMapping(value = "/robots", method = RequestMethod.GET) 
public String robots() {
        return "robots";
}


но это не то, что нужно, как вы понимаете smile

Автор: Stolzen 27.11.2011, 23:46
Что-то мне подсказывает, что дело в http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.html

Цитата
Implementation of ViewResolver that resolves a view based on the request file name or Accept header. 


Вот немного информации об нем - http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-multiple-representations

Цитата
In the above configuration, if a request is made with an .html extension, the view resolver looks for a view that matches the text/html media type. The InternalResourceViewResolver provides the matching view for text/html. If the request is made with the file extension .atom, the view resolver looks for a view that matches the application/atom+xml media type. This view is provided by the BeanNameViewResolver that maps to the SampleContentAtomView if the view name returned is content. If the request is made with the file extension .json, the MappingJacksonJsonView instance from the DefaultViews list will be selected regardless of the view name. Alternatively, client requests can be made without a file extension but with the Accept header set to the preferred media-type, and the same resolution of request to views would occur.


Значит нужно каким-то образом добавить в него резолвер для txt.

При таком маппинге
Цитата(m0zg @  27.11.2011,  21:47 Найти цитируемый пост)
@RequestMapping(value = "/robots", method = RequestMethod.GET) 
public String robots() {
        return "robots";
}


По запросу /robots.txt что-нибудь возвращается? Или 404?

Автор: m0zg 27.11.2011, 23:52
Цитата(Stolzen @  27.11.2011,  23:46 Найти цитируемый пост)
По запросу /robots.txt что-нибудь возвращается? Или 404?



ошибка 500, стэк-трэйс я выше писал

Автор: m0zg 28.11.2011, 13:24
Если конфиг поменять на:

Код

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


то всё работает правильно. Как бы чего не сломалось. Надо подумать над резолвером для txt-файлов

Автор: jk1 29.11.2011, 17:00
А зачем статику резолвить вообще? Отдавайте как есть
Код

 <mvc:resources mapping="/robots.txt" location="/robots.txt" />

Автор: m0zg 30.11.2011, 14:37
Цитата(jk1 @  29.11.2011,  17:00 Найти цитируемый пост)
А зачем статику резолвить вообще? Отдавайте как есть
Разметка XML
1:
 <mvc:resources mapping="/robots.txt" location="/robots.txt" />





мать перемать  smile 


Спасибо smile

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)