2012-07-02 2 views
0

Я создал образец пружинного MVC приложение с использованием Maven архетипаSpring MVC карта параметр .jsp вместо @RequestMapping

mvn archetype:generate -D groupId=test.tool -D artifactId=test-D version=0.1-SNAPSHOT -D archetypeArtifactId=spring-mvc-jpa-archetype -D archetypeGroupId=org.fluttercode.knappsack 

Я пытался читать некоторые параметры из URL:

package test.tool.controller; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 


@Controller 
@RequestMapping(value = "/testReadRest", method = RequestMethod.GET) 
public class TestReadRestController { 

private static final Logger logger = LoggerFactory 
     .getLogger(TestReadRestController.class); 


// No Params 
@RequestMapping(method = RequestMethod.GET) 
public void getMainModel(Model model) { 
    model.addAttribute("varFromClient","[NOT SET]"); 
    model.addAttribute("tokenFromClient","[NOT SET]"); 
    return; 
} 

// http://localhost:8080/test/testReadRest/varPost 
// read "varPost" 
@RequestMapping(value = "/{varPost}", method = RequestMethod.GET) 
public void getVarFromURI(@PathVariable("varPost") String theVar, Model model) { 
    model.addAttribute("varFromClient",theVar); 
    model.addAttribute("tokenFromClient","[NOT SET]"); 
    return; 
    } 
} 

но параметр не считывается при попытке http://localhost:8080/test/testReadRest/varPost

вместо, я получаю сообщение об ошибке:

Problem accessing /soctoolset/WEB-INF/views/testReadRest/varPost.jsp. Reason: NOT_FOUND 

Любые предложения?

[EDIT]

Вот бобы

<?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" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.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> 

    <!-- Imports user-defined @Controller beans that process client requests --> 
    <beans:import resource="controllers.xml" /> 

</beans:beans> 

и controller.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 

    <!-- Scans within the base package of the application for @Components to 
     configure as beans --> 
    <context:component-scan base-package="test.tool" /> 

    <tx:annotation-driven /> 
    <mvc:annotation-driven /> 

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

    <bean id="validator" 
     class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> 

</beans> 
+0

Действительно ли запрос действительно находится в вашем методе обработчика? Я думаю, что конфигурация уровня уровня предотвращает обработку запросов, кроме «/ testReadRest». Попробуйте установить его на '@RequestMapping (value ="/testReadRest/** ")', если это настоящая проблема. Просто игнорируйте меня, если ваше отображение работает. – Wolfram

ответ

4

Я создал новый проект с архетипом, который вы использовали.

Вы возвращаетесь void от метода @Controller, так это section from the docs относится:

void if the method handles the response itself (by writing the response content directly, declaring an argument of type ServletResponse/HttpServletResponse for that purpose) or if the view name is supposed to be implicitly determined through a RequestToViewNameTranslator (not declaring a response argument in the handler method signature).

Таким образом, the view is resolved based on the path, в вашем случае «varPost» или что вы положили в конце пути. Расширение «.jsp» добавляется за счет конфигурации по умолчанию:

<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> 

Вы можете добавить отсутствующий файл, но я предполагаю, что это не то, что вы хотите сделать. Вместо этого, вы можете изменить сигнатуру метода-обработчика и установить вид в явном виде, как это:

@RequestMapping(value = "/{varPost}", method = RequestMethod.GET) 
public String getVarFromURI(@PathVariable("varPost") String theVar, 
     Model model) { 
    model.addAttribute("varFromClient", theVar); 
    model.addAttribute("tokenFromClient", "[NOT SET]"); 
    return "someview"; 
} 

Это приводит к следующей разумной ошибки:

The requested resource (/testapp/WEB-INF/views/someview.jsp) is not available.

Теперь вам просто нужно создать эту точку зрения. Затем вы можете использовать переменную пути, не вмешиваясь в разрешение представления.

Если вы не хотите отображать JSP, вы можете начать с чтения документации относительно "Supported method return types". Если вы хотите полностью отреагировать на ответ, вы можете снова вернуть void и add the request and response as arguments.

+0

Огромное вам спасибо за 4 проблемы с моей проблемой. Ваши ссылки наиболее полезны для весны newbe, как я. ТЫ действительно очень! –

+0

И просто протестировал его. Работает как рай. Чувствуя себя так счастливым :-D –

Смежные вопросы