Java Spring MVC 缺少 URI 模板变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19803117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:19:25  来源:igfitidea点击:

Spring MVC Missing URI template variable

javaspringspring-mvcmodel-view-controller

提问by devdar

I have a Controllerclass with a function that saves a record to the Database. I am passing several parameters to the Controllerfunction however i think i may be writing the @RequestMappingincorrectly. Under is the code

我有一个Controller带有将记录保存到数据库的函数的类。我正在向Controller函数传递几个参数,但是我认为我可能写错了@RequestMapping。下面是代码

Controller

控制器

 @RequestMapping(value="createRoadBlock.htm", method = RequestMethod.POST)
 public @ResponseBody Integer createRoadBlock(@RequestParam String purpose, @RequestParam String userName,
                                              @RequestParam  int status, @RequestParam double latAdd,
                                              @RequestParam double longAdd, HttpServletRequest request,  
                                              HttpServletResponse response) {

         int roadBlockId = 0;
        try{

            roadBlockId = roadBlockManager.saveRoadBlock(purpose, userName, status,latAdd,longAdd);
            logger.info("Create Road Block Successful roadBlockId "+ roadBlockId);

            return roadBlockId;

        }catch(Exception e){
            logger.error("Exception Occured In Road Block Controller "+e.getMessage());
            return roadBlockId;

        } 

     }

Ajax Request

Ajax 请求

$.ajax({
    type:'POST',
    url:'createRoadBlock.htm',
    contentType:"application/json",
    async:false,
    cache:false,
        data:{purpose:f_purpose, userName:f_userName,status: f_status,latAdd: f_latAdd, longAdd:f_lngAdd},
    dataType:'json'

    }).success(function(recordId){ 
                console.log('Road Block created with id ' + recordId);
    });

Error Log

错误日志

Controller [com.crimetrack.web.RoadBlockController]
Method [public java.lang.Integer com.crimetrack.web.RoadBlockController.createRoadBlock(java.lang.String,java.lang.String,int,double,double,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]

org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'purpose' is not present
    at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:201)
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:90)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)

采纳答案by Jason

@PathVariableis used to tell Spring that part of the URI path is a value you want passed to your method. Is this what you want, or are the variables supposed to be form data posted to the URI?

@PathVariable用于告诉 Spring URI 路径的一部分是您要传递给方法的值。这是您想要的,还是变量应该是发布到 URI 的表单数据?

If you want form data, use @RequestParaminstead of @PathVariable.

如果您需要表单数据,请使用@RequestParam代替@PathVariable

If you want @PathVariable, you need to specify placeholders in the @RequestMappingentry to tell Spring where the path variables fit in the URI. For example, if you want to extract a path variable called contentId, you would use:

如果需要@PathVariable,您需要在@RequestMapping条目中指定占位符以告诉 Spring 路径变量适合 URI 的位置。例如,如果您想提取一个名为 的路径变量contentId,您可以使用:

@RequestMapping(value = "/whatever/{contentId}", method = RequestMethod.POST)

@RequestMapping(value = "/whatever/{contentId}", method = RequestMethod.POST)

Edit: Additionally, if your path variable could contain a '.' and you want that part of the data, then you will need to tell Spring to grab everything, not just the stuff before the '.':

编辑:此外,如果您的路径变量可能包含“。” 并且您想要那部分数据,那么您需要告诉 Spring 获取所有内容,而不仅仅是 '.' 之前的内容:

@RequestMapping(value = "/whatever/{contentId:.*}", method = RequestMethod.POST)

@RequestMapping(value = "/whatever/{contentId:.*}", method = RequestMethod.POST)

This is because the default behaviour of Spring is to treat that part of the URL as if it is a file extension, and excludes it from variable extraction.

这是因为 Spring 的默认行为是将 URL 的那部分视为文件扩展名,并将其从变量提取中排除。

回答by Hany Sakr

I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping

我因为一个愚蠢的错误而得到这个错误,@PathVariable 中的变量名与 @RequestMapping 中的变量名不匹配

For example

例如

@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}

It may help others

它可能会帮助他人