下面列出了org.springframework.web.servlet.ModelAndView#setView ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Nullable
private ModelAndView getModelAndView(ModelAndViewContainer mavContainer,
ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception {
modelFactory.updateModel(webRequest, mavContainer);
if (mavContainer.isRequestHandled()) {
return null;
}
ModelMap model = mavContainer.getModel();
ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, mavContainer.getStatus());
if (!mavContainer.isViewReference()) {
mav.setView((View) mavContainer.getView());
}
if (model instanceof RedirectAttributes) {
Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
if (request != null) {
RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
}
}
return mav;
}
/**
* 菜单跳转
*
* @return
*/
@RequestMapping(params = "left")
public ModelAndView left(HttpServletRequest request) {
TSUser user = ResourceUtil.getSessionUser();
HttpSession session = ContextHolderUtils.getSession();
ModelAndView modelAndView = new ModelAndView();
// 登陆者的权限
if (user.getId() == null) {
session.removeAttribute(Globals.USER_SESSION);
modelAndView.setView(new RedirectView("loginController.do?login"));
}else{
modelAndView.setViewName("main/left");
request.setAttribute("menuMap", userService.getFunctionMap(user.getId()));
}
return modelAndView;
}
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ModelAndView mav = super.doResolveException(request, response, handler, ex);
if (ex instanceof NoPermissionException) {
response.setStatus(HttpStatus.FORBIDDEN.value());
logger.info(String.valueOf(response.getStatus()));
} else if (ex instanceof BadRequestException) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
} else if (ex instanceof NoLoginException) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
} else if (ex instanceof ResourceNotFoundException || ex instanceof InvitationTokenExpiredException
|| ex instanceof InvitationTokenInvalidException || ex instanceof RegisterTokenInvalidException
|| ex instanceof ResetPasswordTokenInvalidException) {
response.setStatus(HttpStatus.NOT_FOUND.value());
} else {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
mav.setView(new MappingJacksonJsonView());
mav.addObject("exception", ex);
logger.debug("view name = {}", mav.getViewName());
return mav;
}
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object o, Exception e) {
LOGGER.error("rest error:", e);
ModelAndView modelAndView = new ModelAndView();
try {
ResultInfo resultInfo = new ResultInfo().setStatus(ResultStatus.ERROR.getCode())
.setMsg(ResultInfo.MSG_ERROR);
Map<String, Object> attr = JSON.parseObject(JSON.toJSONString(resultInfo), Map.class);
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setAttributesMap(attr);
modelAndView.setView(view);
} catch (Exception e1) {
e1.printStackTrace();
}
return modelAndView;
}
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ModelAndView mv = new ModelAndView();
MappingJackson2JsonView view = new MappingJackson2JsonView();
Map<String, Object> attributes = new HashMap();
if (ex instanceof MaxUploadSizeExceededException) {
attributes.put("code", ResultCode.C403.code);
attributes.put("msg", "Maximum upload size of " + ((MaxUploadSizeExceededException) ex).getMaxUploadSize() + " bytes exceeded");
logger.warn(ex.getMessage());
} else {
attributes.put("code", ResultCode.C500.code);
attributes.put("msg", ResultCode.C500.desc);
logger.error("Internal server error", ex);
}
view.setAttributesMap(attributes);
mv.setView(view);
return mv;
}
private ModelAndView getModelAndView(ModelAndViewContainer mavContainer,
ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception {
modelFactory.updateModel(webRequest, mavContainer);
if (mavContainer.isRequestHandled()) {
return null;
}
ModelMap model = mavContainer.getModel();
ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, mavContainer.getStatus());
if (!mavContainer.isViewReference()) {
mav.setView((View) mavContainer.getView());
}
if (model instanceof RedirectAttributes) {
Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
}
return mav;
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if(!(returnValue instanceof MultiView)){
processor.handleReturnValue(new Result<>(true,returnValue),returnType,mavContainer,webRequest);
return;
}
MultiView view = (MultiView) returnValue;
//如果是ajax请求,则返回json
if("XMLHttpRequest".equals(webRequest.getHeader("X-Requested-With"))){
processor.handleReturnValue(new Result<>(true,view.getModelMap()),returnType,mavContainer,webRequest);
return;
}
ModelAndView temp = new ModelAndView(view.getViewName());
if(view.getView() != null) {
temp.setView(view.getView());
}
temp.setStatus(view.getStatus());
temp.addAllObjects(view.getModelMap());
super.handleReturnValue(temp, returnType, mavContainer, webRequest);
}
private ModelAndView getModelAndView(ModelAndViewContainer mavContainer,
ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception {
modelFactory.updateModel(webRequest, mavContainer);
if (mavContainer.isRequestHandled()) {
return null;
}
ModelMap model = mavContainer.getModel();
ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model);
if (!mavContainer.isViewReference()) {
mav.setView((View) mavContainer.getView());
}
if (model instanceof RedirectAttributes) {
Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
}
return mav;
}
/**
* 获取其它异常。包括500
*
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request,
HttpServletResponse response,
Exception e, Model model) throws IOException {
e.printStackTrace();
if (isAjax(request)) {
ModelAndView mav = new ModelAndView();
MappingJackson2JsonView view = new MappingJackson2JsonView();
Map<String, Object> attributes = new HashMap<String, Object>();
if (e instanceof UnauthorizedException) {
attributes.put("msg", "没有权限");
} else {
attributes.put("msg", e.getMessage());
}
attributes.put("code", "0");
view.setAttributesMap(attributes);
mav.setView(view);
return mav;
}
if (e instanceof UnauthorizedException) {
//请登录
log.error("无权访问", e);
return new ModelAndView("common/error/403");
}
//其他异常
String message = e.getMessage();
model.addAttribute("code", 500);
model.addAttribute("message", message);
return new ModelAndView("common/error/500");
}
/**
* Return a ModelAndView object with the specified view name.
* <p>The content of the {@link RequestContextUtils#getInputFlashMap
* "input" FlashMap} is also added to the model.
* @see #getViewName()
*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String viewName = getViewName();
if (getStatusCode() != null) {
if (getStatusCode().is3xxRedirection()) {
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, getStatusCode());
}
else {
response.setStatus(getStatusCode().value());
if (getStatusCode().equals(HttpStatus.NO_CONTENT) && viewName == null) {
return null;
}
}
}
if (isStatusOnly()) {
return null;
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addAllObjects(RequestContextUtils.getInputFlashMap(request));
if (viewName != null) {
modelAndView.setViewName(viewName);
}
else {
modelAndView.setView(getView());
}
return modelAndView;
}
@RequestMapping("/hot.rss")
public Object rssFeed() {
ModelAndView modelAndView = new ModelAndView().addObject("articles",
articleService.listRssTopArticlesWithCache());
modelAndView.setView(new HotArticleRssContentView());
return modelAndView;
}
/**
* Return a ModelAndView object with the specified view name.
* <p>The content of the {@link RequestContextUtils#getInputFlashMap
* "input" FlashMap} is also added to the model.
* @see #getViewName()
*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String viewName = getViewName();
if (getStatusCode() != null) {
if (getStatusCode().is3xxRedirection()) {
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, getStatusCode());
viewName = (viewName != null && !viewName.startsWith("redirect:") ? "redirect:" + viewName : viewName);
}
else {
response.setStatus(getStatusCode().value());
if (isStatusOnly() || (getStatusCode().equals(HttpStatus.NO_CONTENT) && getViewName() == null)) {
return null;
}
}
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addAllObjects(RequestContextUtils.getInputFlashMap(request));
if (getViewName() != null) {
modelAndView.setViewName(viewName);
}
else {
modelAndView.setView(getView());
}
return (isStatusOnly() ? null : modelAndView);
}
/**
* Return a ModelAndView object with the specified view name.
* <p>The content of the {@link RequestContextUtils#getInputFlashMap
* "input" FlashMap} is also added to the model.
* @see #getViewName()
*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String viewName = getViewName();
if (getStatusCode() != null) {
if (getStatusCode().is3xxRedirection()) {
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, getStatusCode());
viewName = (viewName != null && !viewName.startsWith("redirect:") ? "redirect:" + viewName : viewName);
}
else {
response.setStatus(getStatusCode().value());
if (isStatusOnly() || (getStatusCode().equals(HttpStatus.NO_CONTENT) && getViewName() == null)) {
return null;
}
}
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addAllObjects(RequestContextUtils.getInputFlashMap(request));
if (getViewName() != null) {
modelAndView.setViewName(viewName);
}
else {
modelAndView.setView(getView());
}
return (isStatusOnly() ? null : modelAndView);
}
/**
* 处理登出ki4so服务器的请求。
* 1.清除用户登录的状态信息,即用户登录了那些应用。
* 2.清除sso服务端的cookie。
* 3.统一登出用户登出过的所有应用。
* @param request 请求对象。
* @param response 响应对象。
* 如果参数servcie有合法的值,则跳转到该地址。否则返回到默认的登出成功页面。
* @throws IOException
*/
@RequestMapping("/logout")
public ModelAndView logout(HttpServletRequest request,
HttpServletResponse response,HttpSession session) throws IOException {
ModelAndView modelAndView = new ModelAndView();
//获得service.
String service = request.getParameter(WebConstants.SERVICE_PARAM_NAME);
LOGGER.info("the service of logout is "+service);
//解析用户凭据。
KnightCredential credential = credentialResolver.resolveCredential(request);
//调用servie统一登出所有的应用。
this.ki4soService.logout(credential, service);
//清除cookie值。
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0){
for(Cookie cookie:cookies){
if(WebConstants.KI4SO_SERVER_ENCRYPTED_CREDENTIAL_COOKIE_KEY.equals(cookie.getName())){
//设置过期时间为立即。
cookie.setMaxAge(0);
response.addCookie(cookie);
LOGGER.info("clear up the cookie "+WebConstants.KI4SO_SERVER_ENCRYPTED_CREDENTIAL_COOKIE_KEY);
}
}
}
if(!StringUtils.isEmpty(service)){
//跳转到service对应的URL地址
modelAndView.setView(new RedirectView(service));
session.setAttribute(Ki4soClientFilter.USER_STATE_IN_SESSION_KEY,null);
}
else{
//返回默认的登出成功页面。
modelAndView.setViewName("logoutSucess");
}
return modelAndView;
}
/**
* Find an {@code @ExceptionHandler} method and invoke it to handle the raised exception.
*/
@Override
@Nullable
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response, @Nullable HandlerMethod handlerMethod, Exception exception) {
ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception);
if (exceptionHandlerMethod == null) {
return null;
}
if (this.argumentResolvers != null) {
exceptionHandlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
}
if (this.returnValueHandlers != null) {
exceptionHandlerMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
}
ServletWebRequest webRequest = new ServletWebRequest(request, response);
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
try {
if (logger.isDebugEnabled()) {
logger.debug("Using @ExceptionHandler " + exceptionHandlerMethod);
}
Throwable cause = exception.getCause();
if (cause != null) {
// Expose cause as provided argument as well
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, cause, handlerMethod);
}
else {
// Otherwise, just the given exception as-is
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, handlerMethod);
}
}
catch (Throwable invocationEx) {
// Any other than the original exception is unintended here,
// probably an accident (e.g. failed assertion or the like).
if (invocationEx != exception && logger.isWarnEnabled()) {
logger.warn("Failure in @ExceptionHandler " + exceptionHandlerMethod, invocationEx);
}
// Continue with default processing of the original exception...
return null;
}
if (mavContainer.isRequestHandled()) {
return new ModelAndView();
}
else {
ModelMap model = mavContainer.getModel();
HttpStatus status = mavContainer.getStatus();
ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, status);
mav.setViewName(mavContainer.getViewName());
if (!mavContainer.isViewReference()) {
mav.setView((View) mavContainer.getView());
}
if (model instanceof RedirectAttributes) {
Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
}
return mav;
}
}
/**
* Find an {@code @ExceptionHandler} method and invoke it to handle the raised exception.
*/
@Override
@Nullable
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response, @Nullable HandlerMethod handlerMethod, Exception exception) {
ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception);
if (exceptionHandlerMethod == null) {
return null;
}
if (this.argumentResolvers != null) {
exceptionHandlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
}
if (this.returnValueHandlers != null) {
exceptionHandlerMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
}
ServletWebRequest webRequest = new ServletWebRequest(request, response);
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
try {
if (logger.isDebugEnabled()) {
logger.debug("Using @ExceptionHandler " + exceptionHandlerMethod);
}
Throwable cause = exception.getCause();
if (cause != null) {
// Expose cause as provided argument as well
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, cause, handlerMethod);
}
else {
// Otherwise, just the given exception as-is
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, handlerMethod);
}
}
catch (Throwable invocationEx) {
// Any other than the original exception is unintended here,
// probably an accident (e.g. failed assertion or the like).
if (invocationEx != exception && logger.isWarnEnabled()) {
logger.warn("Failure in @ExceptionHandler " + exceptionHandlerMethod, invocationEx);
}
// Continue with default processing of the original exception...
return null;
}
if (mavContainer.isRequestHandled()) {
return new ModelAndView();
}
else {
ModelMap model = mavContainer.getModel();
HttpStatus status = mavContainer.getStatus();
ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, status);
mav.setViewName(mavContainer.getViewName());
if (!mavContainer.isViewReference()) {
mav.setView((View) mavContainer.getView());
}
if (model instanceof RedirectAttributes) {
Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
}
return mav;
}
}
public ModelAndView get(String url, Exception exception) {
String ticket = ticket();
String message = printStackTrace ? exception.toString() : exception.toString();
log.error("[TICKET:URL] {}:{} {}", ticket, url, message);
System.err.printf("[TICKET:URL] %s:%s %s%n", ticket, url, message);
if (printStackTrace && !skip(message)) {
exception.printStackTrace();
}
Map<String, Object> info = getDetails(ticket, url, exception);
tickets.put(ticket, info);
ModelAndView result = new ModelAndView();
result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
copy("ticketNumber", info, result);
if (!debug.isWorking()) {
result.addObject("message", getMessage());
if (url.contains("/rest/")) {
shouldJsonResult(result);
} else {
shouldErrorPage(result);
}
return result;
}
copy("message", info, result);
copy("url", info, result);
copy("exception", info, result);
if (url.contains("/rest/")) {
copy("stackTrace", info, result);
result.setView(new MappingJackson2JsonView(){{
setPrettyPrint(true);
}});
return result;
}
result.addObject("stackTrace", prepareStackTrace(exception));
shouldErrorPage(result);
return result;
}
/**
* Find an {@code @ExceptionHandler} method and invoke it to handle the raised exception.
*/
@Override
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception);
if (exceptionHandlerMethod == null) {
return null;
}
exceptionHandlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
exceptionHandlerMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
ServletWebRequest webRequest = new ServletWebRequest(request, response);
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
try {
if (logger.isDebugEnabled()) {
logger.debug("Invoking @ExceptionHandler method: " + exceptionHandlerMethod);
}
Throwable cause = exception.getCause();
if (cause != null) {
// Expose cause as provided argument as well
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, cause, handlerMethod);
}
else {
// Otherwise, just the given exception as-is
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, handlerMethod);
}
}
catch (Throwable invocationEx) {
// Any other than the original exception is unintended here,
// probably an accident (e.g. failed assertion or the like).
if (invocationEx != exception && logger.isWarnEnabled()) {
logger.warn("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
}
// Continue with default processing of the original exception...
return null;
}
if (mavContainer.isRequestHandled()) {
return new ModelAndView();
}
else {
ModelMap model = mavContainer.getModel();
HttpStatus status = mavContainer.getStatus();
ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, status);
mav.setViewName(mavContainer.getViewName());
if (!mavContainer.isViewReference()) {
mav.setView((View) mavContainer.getView());
}
if (model instanceof RedirectAttributes) {
Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
request = webRequest.getNativeRequest(HttpServletRequest.class);
RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
}
return mav;
}
}
/**
* Find an {@code @ExceptionHandler} method and invoke it to handle the raised exception.
*/
@Override
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception);
if (exceptionHandlerMethod == null) {
return null;
}
exceptionHandlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
exceptionHandlerMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
ServletWebRequest webRequest = new ServletWebRequest(request, response);
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
try {
if (logger.isDebugEnabled()) {
logger.debug("Invoking @ExceptionHandler method: " + exceptionHandlerMethod);
}
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, handlerMethod);
}
catch (Exception invocationEx) {
if (logger.isErrorEnabled()) {
logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
}
return null;
}
if (mavContainer.isRequestHandled()) {
return new ModelAndView();
}
else {
ModelAndView mav = new ModelAndView().addAllObjects(mavContainer.getModel());
mav.setViewName(mavContainer.getViewName());
if (!mavContainer.isViewReference()) {
mav.setView((View) mavContainer.getView());
}
return mav;
}
}
public ModelAndView get(String url, Exception exception) {
String ticket = ticket();
String message = printStackTrace ? exception.toString() : exception.toString();
log.error("[TICKET:URL] {}:{} {}", ticket, url, message);
System.err.printf("[TICKET:URL] %s:%s %s%n", ticket, url, message);
if (printStackTrace && !skip(message)) {
exception.printStackTrace();
}
Map<String, Object> info = getDetails(ticket, url, exception);
tickets.put(ticket, info);
ModelAndView result = new ModelAndView();
result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
copy("ticketNumber", info, result);
if (!debug.isWorking()) {
result.addObject("message", ERROR_MESSAGE);
if (url.contains("/rest/")) {
shouldJsonResult(result);
} else {
shouldErrorPage(result);
}
return result;
}
copy("message", info, result);
copy("url", info, result);
copy("exception", info, result);
if (url.contains("/rest/")) {
copy("stackTrace", info, result);
result.setView(new MappingJackson2JsonView(){{
setPrettyPrint(true);
}});
return result;
}
result.addObject("stackTrace", prepareStackTrace(exception));
shouldErrorPage(result);
return result;
}