简体   繁体   English

Spring控制器的工作方式与GET和POST方法类似

[英]Spring controller to work similarly to both GET and POST methods

I have a method like below in my Spring application 我的Spring应用程序中有一种如下所示的方法

@RequestMapping(value = "/search-result-doctors", method = RequestMethod.POST)
public String getDoctorSearchResults(String LastName, String Hospital, String Specialty, String date1, ModelMap model) {
    //some logics

     return "doctorchannelling/search-result-doctors";
}

after going in to the page "search-result-doctors" when I press the just Enter in the URL it has to remain in the same page. 进入“搜索结果医生”页面后,当我按URL中的Enter键时,它必须保留在同一页面中。 Since it is a GET request I have written the same method again with a method value RequestMethod.GET. 由于这是一个GET请求,因此我再次使用方法值RequestMethod.GET编写了相同的方法。

@RequestMapping(value = "/search-result-doctors", method = RequestMethod.GET)
public String getDoctorSearchResults(String LastName, String Hospital, String Specialty, String date1, ModelMap model) {
    //some logics

    return "doctorchannelling/search-result-doctors";
}

due to the unavailability of parameter values String LastName, String Hospital, String Specialty, String date1 in the GET request i'm getting a Exception 由于GET请求中的参数值String LastName,String Hospital,String Specialty,String date1不可用,我得到了异常

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

How can I resolve this problem 我该如何解决这个问题

Thanks in advance 提前致谢

Actually you can define just one method to process both GET and POST 实际上,您只能定义一种方法来处理GET和POST

@RequestMapping(value = "/search-result-doctors", method = { RequestMethod.POST, RequestMethod.GET })

If you get NPE somewhere in your some logic just check which parameters are empty. 如果您在某些逻辑中获得了NPE,只需检查哪些参数为空。

In addition to what @StanislavL is saying, you should annotate your parameters with @RequestParam(required=false) , so 除了@StanislavL所说的以外,您还应该使用@RequestParam(required=false)注释参数。

public String getDoctorSearchResults(@RequestParam(required=false) String LastName,@RequestParam(required=false) String Hospital, @RequestParam(required=false) String Specialty, @RequestParam(required=false) String date1, ModelMap model) {

combined with the method annotation and NullPointer checkes as given by @StanislavL, should give you what you want 结合方法注释和@StanislavL给定的NullPointer校验,应该给您您想要的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM