Skip to content

Instantly share code, notes, and snippets.

@dodangquan
Created January 18, 2016 01:00
Show Gist options
  • Save dodangquan/96f62f733b533e397075 to your computer and use it in GitHub Desktop.
Save dodangquan/96f62f733b533e397075 to your computer and use it in GitHub Desktop.
Tùy chỉnh ngoại lệ không tìm thấy tài nguyên khi duyệt web
@Controller
public class BookController {
private static final Logger logger = LoggerFactory.getLogger(BookController.class);
@Autowired
@Qualifier("bookService")
private BookService bookService;
@Autowired
@Qualifier("cartBean")
private Cart cartBean;
@ExceptionHandler(ResourceNotFoundException.class)
public String handleResourceNotFoundException(HttpServletRequest request) {
HttpSession session = request.getSession(true);
session.setAttribute("cartBean", cartBean);
return "404page";
}
@RequestMapping(value = "/book/detail/{bookId}")
@SuppressWarnings("unchecked")
public String details(@PathVariable("bookId") long bookId, Model model, HttpServletRequest request) {
logger.info("Show Book Detail Page");
HttpSession session = request.getSession(false);
Book book = null;
if (session != null && session.getAttribute("books") != null) {
List<Book> books = (List<Book>) session.getAttribute("books");
for (Book b : books) {
if (b.getId() == bookId) {
book = b;
model.addAttribute("book", b);
break;
}
}
if (book == null) {
throw new ResourceNotFoundException();
}
} else {
book = bookService.findBook(bookId);
if (book == null) {
throw new ResourceNotFoundException();
}
model.addAttribute("book", book);
}
return "book-detail";
}
}
@Controller
@SessionAttributes(names = "cartBean")
public class ResourceNotFoundController {
@Controller
@SessionAttributes(names = "cartBean")
public class ResourceNotFoundController {
@Autowired
@Qualifier("cartBean")
private Cart cartBean;
@RequestMapping("/404")
public String handleResourceNotFound(Model model, HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
model.addAttribute("cartBean", cartBean);
}
return "404page";
}
}
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = -3329819391367130855L;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment