Trigger 404 na wiosnę-kontroler MVC?

Jak uzyskać Kontroler Spring 3.0 do uruchomienia 404?

Mam kontroler z @RequestMapping(value = "/**", method = RequestMethod.GET) i dla niektórych adresów URL uzyskujących dostęp do kontrolera, chcę, aby kontener miał numer 404.

Author: Peter Mortensen, 2010-01-14

12 answers

Od wiosny 3.0 można również wyrzucić wyjątek zadeklarowany przez @ResponseStatus adnotacja:

@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(); 
        }
    }
}
 279
Author: axtavt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-08 18:35:36

Przepisz sygnaturę metody tak, aby akceptowała ona HttpServletResponse jako parametr, abyś mógł na niej wywołać setStatus(int).

Http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments

 33
Author: matt b,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-14 19:39:03

Chciałbym wspomnieć, że domyślnie jest wyjątek (nie tylko) dla 404 dostarczany przez Spring. Zobacz Dokumentacja Sprężyny Po szczegóły. Więc jeśli nie potrzebujesz własnego wyjątku, możesz po prostu to zrobić:

 @RequestMapping(value = "/**", method = RequestMethod.GET)
 public ModelAndView show() throws NoSuchRequestHandlingMethodException {
    if(something == null)
         throw new NoSuchRequestHandlingMethodException("show", YourClass.class);

    ...

  }
 24
Author: michal.kreuzman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-04 22:32:09

Od wiosny 3.0.2 można zwrócić odpowiedź w wyniku metody kontrolera:

@RequestMapping.....
public ResponseEntity<Object> handleCall() {
    if (isFound()) {
        // do what you want
        return new ResponseEntity<>(HttpStatus.OK);
    }
    else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

(ODPOWIEDŹ jest bardziej elastyczna niż adnotacja @ResponseBody - zobacz kolejne pytanie )

 18
Author: Lu55,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:32

Możesz użyć @Controlleravice do obsługi wyjątków , Domyślne zachowanie klasy adnotowanej @ Controlleravice pomoże wszystkim znanym kontrolerom.

Więc zostanie wywołany, gdy dowolny kontroler wyrzuci błąd 404 .

Jak poniżej:

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.NOT_FOUND)  // 404
    @ExceptionHandler(Exception.class)
    public void handleNoTFound() {
        // Nothing to do
    }
}

I zmapuj ten błąd odpowiedzi 404 w swojej sieci.xml, jak poniżej:

<error-page>
        <error-code>404</error-code>
        <location>/Error404.html</location>
</error-page>
Mam nadzieję, że to pomoże .
 13
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-05 10:41:26

Jeśli twoja metoda kontrolera służy do obsługi plików, to ResponseEntity jest bardzo przydatna:

@Controller
public class SomeController {
    @RequestMapping.....
    public ResponseEntity handleCall() {
        if (isFound()) {
            return new ResponseEntity(...);
        }
        else {
            return new ResponseEntity(404);
        }
    }
}
 9
Author: Ralph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-20 16:17:52

Polecam rzucanie HttpClientErrorException , w ten sposób

@RequestMapping(value = "/sample/")
public void sample() {
    if (somethingIsWrong()) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
    }
}

Należy pamiętać, że można to zrobić tylko zanim cokolwiek zostanie zapisane do strumienia wyjściowego servleta.

 5
Author: mmatczuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-16 09:01:05

Chociaż zaznaczona odpowiedź jest poprawna, istnieje sposób na osiągnięcie tego bez wyjątków. Usługa zwraca Optional<T> wyszukiwanego obiektu i jest mapowana do HttpStatus.OK jeśli zostanie znaleziona i do 404 jeśli jest pusta.

@Controller
public class SomeController {

    @RequestMapping.....
    public ResponseEntity<Object> handleCall() {
        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); 
    }

}
 5
Author: user1121883,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-22 08:02:55

Również jeśli chcesz zwrócić status 404 ze swojego kontrolera, wystarczy to zrobić

@RequestMapping(value = "/somthing", method = RequestMethod.POST)
@ResponseBody
public HttpStatus doSomthing(@RequestBody String employeeId) {
    try{
  return HttpStatus.OK;
    } 
    catch(Exception ex){ 
  return HttpStatus.NOT_FOUND;
    }
}

W ten sposób otrzymasz błąd 404 w przypadku, gdy chcesz zwrócić 404 z kontrolera.

 1
Author: AbdusSalam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-04 02:37:43

To trochę za późno, ale jeśli używasz Spring Data REST to jest już org.springframework.data.rest.webmvc.ResourceNotFoundException Używa również adnotacji @ResponseStatus. Nie ma już potrzeby tworzenia niestandardowego wyjątku runtime.

 1
Author: pilot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-16 13:48:06

Po prostu możesz użyć web.xml, aby dodać kod błędu i stronę błędu 404. Ale upewnij się, że strona błędu 404 nie może znajdować się w WEB-INF.

<error-page>
    <error-code>404</error-code>
    <location>/404.html</location>
</error-page>
Jest to najprostszy sposób, ale ma pewne ograniczenia. Załóżmy, że chcesz dodać ten sam styl dla tej strony, który dodałeś do innych stron. W ten sposób nie możesz tego zrobić. Musisz użyć @ResponseStatus(value = HttpStatus.NOT_FOUND)
 0
Author: Rajith Delantha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-06 14:58:29

Konfiguracja www.xml z ustawieniem

<error-page>
    <error-code>500</error-code>
    <location>/error/500</location>
</error-page>

<error-page>
    <error-code>404</error-code>
    <location>/error/404</location>
</error-page>

Utwórz nowy kontroler

   /**
     * Error Controller. handles the calls for 404, 500 and 401 HTTP Status codes.
     */
    @Controller
    @RequestMapping(value = ErrorController.ERROR_URL, produces = MediaType.APPLICATION_XHTML_XML_VALUE)
    public class ErrorController {


        /**
         * The constant ERROR_URL.
         */
        public static final String ERROR_URL = "/error";


        /**
         * The constant TILE_ERROR.
         */
        public static final String TILE_ERROR = "error.page";


        /**
         * Page Not Found.
         *
         * @return Home Page
         */
        @RequestMapping(value = "/404", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
        public ModelAndView notFound() {

            ModelAndView model = new ModelAndView(TILE_ERROR);
            model.addObject("message", "The page you requested could not be found. This location may not be current.");

            return model;
        }

        /**
         * Error page.
         *
         * @return the model and view
         */
        @RequestMapping(value = "/500", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
        public ModelAndView errorPage() {
            ModelAndView model = new ModelAndView(TILE_ERROR);
            model.addObject("message", "The page you requested could not be found. This location may not be current, due to the recent site redesign.");

            return model;
        }
}
 0
Author: Atish Narlawar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-28 21:30:50