Spring MVC但没有视图解析器?

jon*_*ney 10 spring

是否可以在不使用视图解析器的情况下使用Spring 3.1 MVC?

我问的原因是因为我只是想构建和创建一个Web服务,而不是一个网站,所以我根本不需要渲染任何JSP或html页面.我想使用Spring 3.1构建一个RESTful Web服务.

这可能吗?

这是我的servlett从教程中看起来的样子:

这是我的mvc-config.xml这是我的Web.xml
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
        <servlet-name>FreedomSpring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>FreedomSpring</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>

        </param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>

    <welcome-file-list>
        <welcome-file>
      index.jsp
    </welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

</web-app>
Run Code Online (Sandbox Code Playgroud)

这是我的控制器java类,只想从特定的http REST请求而不是"ModelAndView"对象返回一个String,可以这么说

  package com.jr.freedom.controllers;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;

    @Controller
    public class Hello {

        @RequestMapping(value = "/hello", method = RequestMethod.GET)
        public String helloWorldInJson() {

            return "hello";
        }
    }
Run Code Online (Sandbox Code Playgroud)

另外,我如何捕获客户端可能发送给我的请求参数?使用弹簧注释可能吗?我知道我可以在之前的Spring 2.x中使用HttpServletRequest和HttpServletResponse来获取从客户端发送的任何参数,并将对象也返回给用户,例如JSON对象.

我只是在寻找一个这样做的简单例子:

  1. 从我的控制器类上的客户端请求获取参数和可能的HTTP头并将它们映射到某个Java对象"例如,客户端向我发送注册到我的后端服务的新用户对象的详细信息(用户名,密码等),我想要能够将此映射到我的Java类Called User"

  2. 将任何类型的对象(如String,json或xml数据)的响应返回给客户端.

我对Spring 3.0很新.我很久以前就在Spring 2.0上做了一些工作,但注释似乎是现在的方式,不知道如何通过注释来做到这一点.

谢谢

另外,要执行helloWorldInJson()的上述控制器方法,我只需调用http:// localhost/FreedomSpring/hello吗?

ska*_*man 21

你通常用@ResponseBody它.

请参见16.3.3.5使用@ResponseBody注释映射响应正文.

这完全绕过了视图解析器的东西.