如何让Spring 3.0控制器触发404?
我有一个控制器@RequestMapping(值= "/**",方法= RequestMethod.GET)和一些访问控制器的url,我希望容器提出一个404。
如何让Spring 3.0控制器触发404?
我有一个控制器@RequestMapping(值= "/**",方法= RequestMethod.GET)和一些访问控制器的url,我希望容器提出一个404。
当前回答
如果你的控制器方法是用于文件处理,那么ResponseEntity是非常方便的:
@Controller
public class SomeController {
@RequestMapping.....
public ResponseEntity handleCall() {
if (isFound()) {
return new ResponseEntity(...);
}
else {
return new ResponseEntity(404);
}
}
}
其他回答
这有点晚了,但如果你正在使用Spring Data REST,那么已经有org.springframework.data.rest.webmvc.ResourceNotFoundException 它还使用@ResponseStatus注释。不再需要创建自定义运行时异常。
简单地说,您可以使用web.xml添加错误代码和404错误页面。但是要确保404错误页面不能位于WEB-INF下面。
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
这是最简单的方法,但也有局限性。假设您希望为该页添加与其他页相同的样式。这样你就不能那样做了。你必须使用@ResponseStatus(value = HttpStatus.NOT_FOUND)
因为做同一件事至少有十种方法总是好的:
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class Something {
@RequestMapping("/path")
public ModelAndView somethingPath() {
return new ModelAndView("/", HttpStatus.NOT_FOUND);
}
}
从Spring 3.0开始,你还可以抛出一个用@ResponseStatus注释声明的Exception:
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
...
}
@Controller
public class SomeController {
@RequestMapping.....
public void handleCall() {
if (isFound()) {
// whatever
}
else {
throw new ResourceNotFoundException();
}
}
}
我建议抛出HttpClientErrorException,就像这样
@RequestMapping(value = "/sample/")
public void sample() {
if (somethingIsWrong()) {
throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
}
}
您必须记住,这只能在将任何内容写入servlet输出流之前进行。