如何让Spring 3.0控制器触发404?
我有一个控制器@RequestMapping(值= "/**",方法= RequestMethod.GET)和一些访问控制器的url,我希望容器提出一个404。
如何让Spring 3.0控制器触发404?
我有一个控制器@RequestMapping(值= "/**",方法= RequestMethod.GET)和一些访问控制器的url,我希望容器提出一个404。
当前回答
从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();
}
}
}
其他回答
如果你想从控制器返回404状态,你只需要这样做
@RequestMapping(value = "/something", method = RequestMethod.POST)
@ResponseBody
public HttpStatus doSomething(@RequestBody String employeeId) {
try {
return HttpStatus.OK;
}
catch (Exception ex) {
return HttpStatus.NOT_FOUND;
}
}
通过这样做,当您想从控制器返回404时,您将收到一个404错误。
虽然标记的答案是正确的,但有一种方法可以做到这一点,没有例外。服务返回搜索对象的Optional<T>,这被映射到HttpStatus。如果找到OK,如果为空则返回404。
@Controller
public class SomeController {
@RequestMapping.....
public ResponseEntity<Object> handleCall(@PathVariable String param) {
return service.find(param)
.map(result -> new ResponseEntity<>(result, HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
}
@Service
public class Service{
public Optional<Object> find(String param){
if(!found()){
return Optional.empty();
}
...
return Optional.of(data);
}
}
因为做同一件事至少有十种方法总是好的:
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);
}
}
简单地说,您可以使用web.xml添加错误代码和404错误页面。但是要确保404错误页面不能位于WEB-INF下面。
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
这是最简单的方法,但也有局限性。假设您希望为该页添加与其他页相同的样式。这样你就不能那样做了。你必须使用@ResponseStatus(value = HttpStatus.NOT_FOUND)
重写你的方法签名,使它接受HttpServletResponse作为参数,这样你就可以对它调用setStatus(int)。
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments