0

In some methods from the controllers in my spring application, I have methods which return a String value to the view, like this example:

@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";
    }
}

But, monitoring the value received by the views, through the browser's console, I realize that all of them are trying reach out pages like /jst/yes.jsp.

this output is read in the view by jquery functions like that:

$("#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");
    });
});

I am using a java configuration in replacement to files web.xml and spring-servlet.xml, through this classes:

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();
    }

}

Someone knows how to do for my views receive correctly a String value, instead of try reach a jsp page?

1
  • 1
    Annotate your methods with @ResponseBody. Commented Apr 6, 2014 at 3:26

1 Answer 1

2

If you don't provide a ViewResolver in your context configuration available to the DispatcherServlet, it will use a default. That default is an InternalResourceViewResolver.

When your @RequestMapping handler method returns a String, Spring uses ViewNameMethodReturnValueHandler to handle it. It will set the returned String value as the request's view name. Down the line, Spring's DispatcherServlet will use the InternalResourceViewResolver to resolve a view based on the provided name. This will be a JSP. It will then forward to that JSP.

If you want to return the handler method's String return value as the body of the HTTP response, annotate the method with @ResponseBody. Spring will use RequestResponseBodyMethodProcessor to write the value to the HttpServletResponse OutputStream.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.