java - Spring Controller 将输出返回到 View 时出现错误

标签 java spring spring-mvc

在我的 Spring 应用程序中 Controller 的某些方法中,我有一些方法将 String 值返回到 View ,如下例所示:

@RequestMapping(value="cadastra_campo", method=RequestMethod.GET)
public String cadastra_campo(@ModelAttribute("username") String username, @RequestParam("nome") String campo) {
    if(key.temAutorizacao(key.getUsuarioByUsername(username).getId())) {
        if(key.cadastra(campo))
            return "yes";
        else
            return "not";
    }
    else {
        return "no_permit";
    }
}

但是,通过浏览器的控制台监视 View 接收到的值,我意识到所有这些 View 都在尝试访问/jst/yes.jsp 等页面。

此输出由 jquery 函数在 View 中读取,如下所示:

$("#incluir_campo").on("click", function () {
    $.ajax({
        type: "GET",
        url: "<c:out value="${pageContext.request.contextPath}/key/cadastra_campo"/>",
        data: {nome: $("input[name=nome_campo]").val() }
    }).done(function(data){
        if(data=="yes") {
            var newRow = $("<tr>");

            cols = 'td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>';
            cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">Excluir</button> </td>';

            newRow.append(cols);
            $("table.campos").append(newRow);
            $("input[name=nome_campo]").reset();
        }
        else {
            alert("erro ao incluir campo");
        }
    }).fail(function(){
        alert("falha ao incluir campo");
    });
});

我通过此类使用 java 配置来替换文件 web.xml 和 spring-servlet.xml:

WebAppInitializer.java

@Order(value=1)
public class WebAppInitializer implements WebApplicationInitializer {

    @SuppressWarnings("resource")
    @Override
    public void onStartup(ServletContext container) {
      // Create the 'root' Spring application context
      AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
      rootContext.register(WebAppConfig.class);

      // Manage the lifecycle of the root application context
      //container.addListener(new ContextLoaderListener(rootContext));

      // Create the dispatcher servlet's Spring application context
      AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
      dispatcherContext.register(DispatcherConfig.class);

      // Register and map the dispatcher servlet
      ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/");
    }

}

WebAppConfig.java

@EnableWebMvc
@EnableTransactionManagement(mode=AdviceMode.PROXY, proxyTargetClass=true)
@ComponentScan(value="com.horariolivre")
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/bootstrap/**").addResourceLocations("/bootstrap/").setCachePeriod(31556926);
        registry.addResourceHandler("/extras/**").addResourceLocations("/extras/").setCachePeriod(31556926);
        registry.addResourceHandler("/jquery/**").addResourceLocations("/jquery/").setCachePeriod(31556926);
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

有人知道如何让我的 View 正确接收字符串值,而不是尝试访问 jsp 页面?

最佳答案

如果您没有在上下文配置中提供可用于 DispatcherServletViewResolver,它将使用默认值。默认值是一个 InternalResourceViewResolver

当您的@RequestMapping处理程序方法返回String时,Spring使用ViewNameMethodReturnValueHandler来处理它。它将返回的 String 值设置为请求的 View 名称。接下来,Spring 的 DispatcherServlet 将使用 InternalResourceViewResolver 根据提供的名称解析 View 。这将是一个 JSP。然后它将转发到该 JSP。

如果您希望将处理程序方法的 String 返回值作为 HTTP 响应的正文返回,请使用 @ResponseBody 注释该方法。 Spring 将使用 RequestResponseBodyMethodProcessor 将值写入 HttpServletResponse OutputStream

关于java - Spring Controller 将输出返回到 View 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22889632/

相关文章:

java - 外键也是主键的实体的Spring Data Repository

java - 实现此处预期的错误

java - Spring-MVC:调用 validator ,而不是从 Controller 内部

java - 如何在 Spring Boot 中发送请求范围 bean 作为响应

java - Spring Boot 通过请求作用域 bean 在单例服务/ Controller 中 Autowiring 字段

java - Spring Boot 与 Thymeleaf - 空上下文

java - Robot.mouseMove 没有正确移动到指定位置

spring - 如何在 Spring 实体类中保留 ArrayList?

spring - 使用 Apache Knox 网关自定义基于 spring 的 rest API

java - POST 时不清除表单内容