2010-05-10 195 views
0

這是我的問題,我需要用spring來映射AJAX請求。現在,我知道我需要這兩個傢伙:用spring處理ajax請求

HttpServletRequest,獲取客戶端發送給我的消息,並將其從JSON(最有可能)解析爲Map和HttpServletResponse以將消息發送到客戶端。 什麼我不知道的是正確的(簡單,簡潔)的方式來做到這一點...

下面是從springframework的網站代碼示例:

/** 
* Normal comments here 
* 
* @@org.springframework.web.servlet.handler.metadata.PathMap("/foo.cgi") 
* @@org.springframework.web.servlet.handler.metadata.PathMap("/baz.cgi") 
*/ 
public class FooController extends AbstractController { 

    private Cruncher cruncher; 

    public FooController(Cruncher cruncher) { 
     this.cruncher = cruncher; 
    } 

    protected ModelAndView handleRequestInternal (
      HttpServletRequest request, HttpServletResponse response) throws Exception { 
     return new ModelAndView("test"); 
    } 
} 

這是很好的。除此之外,據我所看到的,我不能映射每個方法的URL在類中我會用這種同步請求做:

@Controller 
@RequestMapping("/test") 
public class ControllerTest { 
    @RequestMapping(value = "/test.htm", method = RequestMethod.GET) 
    public void showSearchView(Model model) {...} 
    ... 
} 

我可以做一些簡單的AJAX請求?

回答

1

不確定你在SpringSource上找到第一個例子!這是做壞事的方式。我很確定AbstractController在Spring 3中甚至被標記爲廢棄。

第二種方法對於映射AJAX請求正常工作。如果你真的想自己解析它,HttpServletRequest和HttpServletResponse是該處理程序方法的合法參數。然而,春天會很樂意爲你做它:http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

(如果你被困在舊版本的春天也有添加JSON映射處理第三方庫)

0

這是我的答案找到。我修改了我的帖子中顯示的方法,並向方法參數添加了一個HttpServletRequest。

public void showSearchView(Model model, HttpServletRequest req, HttpServletRequest resp) { 
     if(req==null||resp==null)throw new RuntimeException("OLOLOLOLOL xD"); 
} 

就是這樣。如果有人有更好的答案或評論,我會很高興聽到。