org.springframework.web.bind.annotation.ExceptionHandler#org.springframework.web.servlet.ModelAndView源码实例Demo

下面列出了org.springframework.web.bind.annotation.ExceptionHandler#org.springframework.web.servlet.ModelAndView 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: MOOC   文件: UserController.java
@RequestMapping(value = "regist")
// 注册
public ModelAndView regist(ModelAndView mav, String varcode, User user, HttpSession session, HttpServletRequest req) {
	String id = DateUtil.getId();
	String username = user.getUsername();
	mav.setViewName("redirect:course");
	if (varcode == null) {
		return mav;
	}
	if (userBiz.selectUser(username) == 1 || !CaptchaUtil.ver(varcode, req)) {
		return mav;
	}
	user.setId(id);
	user.setMission(null);
	user.setBuycase(null);
	user.setMycase(null);
	user.setVip(null);
	userBiz.insertSelective(user);
	setlog(user, req.getRemoteAddr(), "普通注册");
	return mav;
}
 
/**
 * Resolve the exception by iterating over the list of configured exception resolvers.
 * <p>The first one to return a {@link ModelAndView} wins. Otherwise {@code null} is returned.
 */
@Override
@Nullable
public ModelAndView resolveException(
		HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {

	if (this.resolvers != null) {
		for (HandlerExceptionResolver handlerExceptionResolver : this.resolvers) {
			ModelAndView mav = handlerExceptionResolver.resolveException(request, response, handler, ex);
			if (mav != null) {
				return mav;
			}
		}
	}
	return null;
}
 
源代码3 项目: EasyEE   文件: MyErrorViewResolver.java
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
	// Use the request or status to optionally return a ModelAndView
	// System.out.println(status.value());
	// System.out.println(status.is5xxServerError());
	// System.out.println(model);
	if(logger.isErrorEnabled()){
		logger.error("View error! ["+status.value()+", "+status.getReasonPhrase()+"]");
	}
	ModelAndView mav = new ModelAndView();
	if(status.is4xxClientError()){
		mav.setViewName("error/notFound");
	}else{
		mav.setViewName("error/serverError");
	}
	
	return mav;
}
 
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!  ");
    sb.append((throwable != null ? throwable.getMessage() : "Unknown error"));
    sb.append(", root cause: ").append((throwable != null ? throwable.getCause() : "Unknown cause"));
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
源代码5 项目: subsonic   文件: M3UController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("audio/x-mpegurl");
    response.setCharacterEncoding(StringUtil.ENCODING_UTF8);

    Player player = playerService.getPlayer(request, response);

    String url = request.getRequestURL().toString();
    url = url.replaceFirst("play.m3u.*", "stream?");

    // Rewrite URLs in case we're behind a proxy.
    if (settingsService.isRewriteUrlEnabled()) {
        String referer = request.getHeader("referer");
        url = StringUtil.rewriteUrl(url, referer);
    }

    url = settingsService.rewriteRemoteUrl(url);

    if (player.isExternalWithPlaylist()) {
        createClientSidePlaylist(response.getWriter(), player, url);
    } else {
        createServerSidePlaylist(response.getWriter(), player, url);
    }
    return null;
}
 
源代码6 项目: youkefu   文件: MetadataController.java
@SuppressWarnings({ "rawtypes"})
@RequestMapping("/synctodb")
   @Menu(type = "admin" , subtype = "metadata" , admin = true)
   public ModelAndView synctodb(ModelMap map , HttpServletRequest request,@Valid String id) throws SQLException, BeansException, ClassNotFoundException {
   	if(!StringUtils.isBlank(id)) {
   		MetadataTable table = metadataRes.findById(id) ;
   		if(table.isFromdb() && !StringUtils.isBlank(table.getListblocktemplet())) {
   			SysDic dic = UKeFuDic.getInstance().getDicItem(table.getListblocktemplet()) ;
   			
   			if(dic!=null) {
    			Object bean = UKDataContext.getContext().getBean(Class.forName(dic.getCode())) ;
    			if(bean instanceof ElasticsearchRepository) {
    				ElasticsearchRepository jpa = (ElasticsearchRepository)bean ;
    				if(!StringUtils.isBlank(table.getPreviewtemplet())) {
    					Iterable dataList = jpa.findAll();
    					for(Object object : dataList) {
    						service.delete(object);
    						service.save(object);
    					}
    				}
    			}
   			}
   		}
   	}
   	return request(super.createRequestPageTempletResponse("redirect:/admin/metadata/index.html"));
   }
 
源代码7 项目: tddl5   文件: Alert.java
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
                                                                                                      throws Exception {
    int reason = 0;
    String result = null;
    try {
        reason = Integer.parseInt(request.getParameter("reason").trim());
    } catch (NullPointerException e) {
        reason = 0;
    }
    result = typeMap.get(reason);
    if (null == result) {
        result = typeMap.get(UNKNOW);
    }
    return new ModelAndView("failure", "reason", result);
}
 
源代码8 项目: youkefu   文件: IMAgentController.java
@RequestMapping("/tag")
@Menu(type = "setting" , subtype = "tag" , admin= false)
public ModelAndView tag(ModelMap map , HttpServletRequest request , @Valid String code) {
	SysDic tagType = null ;
	List<SysDic> tagList = UKeFuDic.getInstance().getDic("com.dic.tag.type") ;
	if(tagList.size() > 0){
		
		if(!StringUtils.isBlank(code)){
			for(SysDic dic : tagList){
				if(code.equals(dic.getCode())){
					tagType = dic ;
				}
			}
		}else{
			tagType = tagList.get(0) ;
		}
		map.put("tagType", tagType) ;
	}
	if(tagType!=null){
		map.put("tagList", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , tagType.getCode() , new PageRequest(super.getP(request), super.getPs(request)))) ;
	}
	map.put("tagTypeList", tagList) ;
	return request(super.createAppsTempletResponse("/apps/setting/agent/tag"));
}
 
源代码9 项目: rice   文件: DocumentControllerServiceImpl.java
/**
 * {@inheritDoc}
 */
@Override
public ModelAndView superUserDisapprove(DocumentFormBase form) {
    Document document = form.getDocument();

    if (StringUtils.isBlank(document.getSuperUserAnnotation())) {
        GlobalVariables.getMessageMap().putErrorForSectionId(
                "Uif-SuperUserAnnotation", RiceKeyConstants.ERROR_SUPER_USER_DISAPPROVE_MISSING);
    }

    Set<String> selectedCollectionLines = form.getSelectedCollectionLines().get(UifPropertyPaths.ACTION_REQUESTS);

    if (!CollectionUtils.isEmpty(selectedCollectionLines)) {
        GlobalVariables.getMessageMap().putErrorForSectionId(
                "Uif-SuperUserActionRequests", RiceKeyConstants.ERROR_SUPER_USER_DISAPPROVE_ACTIONS_CHECKED);
    }

    if (GlobalVariables.getMessageMap().hasErrors()) {
        return getModelAndViewService().getModelAndView(form);
    }

    performSuperUserWorkflowAction(form, UifConstants.SuperUserWorkflowAction.DISAPPROVE);

    return getModelAndViewService().getModelAndView(form);
}
 
@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;
}
 
源代码11 项目: teaching   文件: SysUserController.java
/**
   * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(SysUser sysUser,HttpServletRequest request) {
      // Step.1 组装查询条件
      QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, request.getParameterMap());
      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      //update-begin--Author:kangxiaolin  Date:20180825 for:[03]用户导出,如果选择数据则只导出相关数据--------------------
      String selections = request.getParameter("selections");
     if(!oConvertUtils.isEmpty(selections)){
         queryWrapper.in("id",selections.split(","));
     }
      //update-end--Author:kangxiaolin  Date:20180825 for:[03]用户导出,如果选择数据则只导出相关数据----------------------
      List<SysUser> pageList = sysUserService.list(queryWrapper);

      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "用户列表");
      mv.addObject(NormalExcelConstants.CLASS, SysUser.class);
LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户列表数据", "导出人:"+user.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }
 
源代码12 项目: web-sso   文件: LogoutActionTest.java
@Test
public void testLogoutWithCredentialButNoService() throws IOException {
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	HttpSession session = request.getSession();
	CredentialResolver credentialResolver = Mockito.mock(CredentialResolver.class);
	logoutAction.setCredentialResolver(credentialResolver);
	Ki4soService ki4soService = Mockito.mock(Ki4soService.class);
	logoutAction.setKi4soService(ki4soService);
	
	//测试存在cookie,登出后要清除cookie值,但是service参数的值是null的情况。
	request.setCookies(new Cookie(WebConstants.KI4SO_SERVER_ENCRYPTED_CREDENTIAL_COOKIE_KEY, "dddsd"));
	ModelAndView mv = logoutAction.logout(request, response,session);
	Assert.assertEquals(1, response.getCookies().length);
	Assert.assertEquals(0, response.getCookies()[0].getMaxAge());
	Assert.assertEquals("logoutSucess", mv.getViewName());
}
 
源代码13 项目: gocd   文件: JobControllerIntegrationTest.java
@Test
public void jobDetailModel_shouldNotHaveElasticPluginIdAndElasticAgentIdForACompletedJob() throws Exception {
    Pipeline pipeline = fixture.createdPipelineWithAllStagesPassed();
    Stage stage = pipeline.getFirstStage();
    JobInstance job = stage.getFirstJob();

    final Agent agent = new Agent(job.getAgentUuid(), "localhost", "127.0.0.1", uuidGenerator.randomUuid());
    agent.setElasticAgentId("elastic_agent_id");
    agent.setElasticPluginId("plugin_id");
    agentService.saveOrUpdate(agent);

    ModelAndView modelAndView = controller.jobDetail(pipeline.getName(), String.valueOf(pipeline.getCounter()),
            stage.getName(), String.valueOf(stage.getCounter()), job.getName());

    assertNull(modelAndView.getModel().get("elasticAgentPluginId"));
    assertNull(modelAndView.getModel().get("elasticAgentId"));
}
 
源代码14 项目: jpetstore-kubernetes   文件: SignonInterceptor.java
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
	UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
	if (userSession == null) {
		String url = request.getServletPath();
		String query = request.getQueryString();
		ModelAndView modelAndView = new ModelAndView("SignonForm");
		if (query != null) {
			modelAndView.addObject("signonForwardAction", url+"?"+query);
		}
		else {
			modelAndView.addObject("signonForwardAction", url);
		}
		throw new ModelAndViewDefiningException(modelAndView);
	}
	else {
		return true;
	}
}
 
源代码15 项目: activiti-in-action-codes   文件: TaskController.java
/**
 * 读取用户任务的表单字段
 */
@RequestMapping(value = "task/getform/{taskId}")
public ModelAndView readTaskForm(@PathVariable("taskId") String taskId) throws Exception {
    String viewName = "chapter6/task-form";
    ModelAndView mav = new ModelAndView(viewName);
    TaskFormData taskFormData = formService.getTaskFormData(taskId);
    if (taskFormData.getFormKey() != null) {
        Object renderedTaskForm = formService.getRenderedTaskForm(taskId);
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        mav.addObject("task", task);
        mav.addObject("taskFormData", renderedTaskForm);
        mav.addObject("hasFormKey", true);
    } else {
        mav.addObject("taskFormData", taskFormData);
    }
    return mav;
}
 
源代码16 项目: rice   文件: EncryptionController.java
/**
 * Decrypt the text of the input field.
 *
 * <p>
 * The encryptedText and decryptedText filds are populated when decryption is successful.  An error message
 * is displayed otherwise.
 * </p>
 */
@RequestMapping(params = "methodToCall=decrypt")
public ModelAndView decrypt(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
        HttpServletRequest request, HttpServletResponse response) {
    EncryptionForm encryptionForm = (EncryptionForm) form;

    try {
        encryptionForm.setEncryptedText(encryptionForm.getInput());
        encryptionForm.setDecryptedText(getEncryptionService().decrypt(
                encryptionForm.getInput()));
    }
    catch (GeneralSecurityException gse) {
        GlobalVariables.getMessageMap().putError(INPUT_FIELD, ENCRYPTION_ERROR, gse.toString());
    }

    return getModelAndView(form);
}
 
源代码17 项目: youkefu   文件: CustomerController.java
@RequestMapping("/impsave")
@Menu(type = "customer" , subtype = "customer")
public ModelAndView impsave(ModelMap map , HttpServletRequest request , @RequestParam(value = "cusfile", required = false) MultipartFile cusfile,@Valid String ekind) throws IOException {
	String msg = "upload_success";
	if(!cusfile.isEmpty()) {
		if(cusfile.getOriginalFilename().endsWith("xlsx") || cusfile.getOriginalFilename().endsWith("xls")) {
			DSDataEvent event = new DSDataEvent();
	    	String fileName = "customer/"+UKTools.getUUID()+cusfile.getOriginalFilename().substring(cusfile.getOriginalFilename().lastIndexOf(".")) ;
	    	File excelFile = new File(path , fileName) ;
	    	if(!excelFile.getParentFile().exists()){
	    		excelFile.getParentFile().mkdirs() ;
	    	}
	    	MetadataTable table = metadataRes.findByTablename("uk_entcustomer") ;
	    	if(table!=null){
		    	FileUtils.writeByteArrayToFile(new File(path , fileName), cusfile.getBytes());
		    	event.setDSData(new DSData(table,excelFile , cusfile.getContentType(), super.getUser(request)));
		    	event.getDSData().setClazz(EntCustomer.class);
		    	event.getDSData().setProcess(new EntCustomerProcess(entCustomerRes));
		    	event.setOrgi(super.getOrgi(request));
		    	/*if(!StringUtils.isBlank(ekind)){
		    		event.getValues().put("ekind", ekind) ;
		    	}*/
		    	event.getValues().put("creater", super.getUser(request).getId()) ;
		    	reporterRes.save(event.getDSData().getReport()) ;
		    	new ExcelImportProecess(event).process() ;		//启动导入任务
	    	}
		}else {
			msg = "upload_format_faild";
		}
	}else {
		msg = "upload_nochoose_faild";
	}
	
	
	
	return request(super.createRequestPageTempletResponse("redirect:/apps/customer/index.html?msg="+msg));
}
 
源代码18 项目: MultimediaDesktop   文件: LoginController.java
@RequestMapping(value = "/user/findPassword", method = RequestMethod.POST)
public ModelAndView findPassword(String email, String captcha,
		HttpSession session, ModelAndView model) {

	try {
		model.setViewName("onlineStatus");
		if (StringUtils.isBlank(captcha)) {
			throw new VerificationException("验证码不允许为空");
		}
		String code = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(captcha)) {
			throw new VerificationException("验证码错误");
		}

		if (!StringUtils.checkEmail(email)) {
			throw new VerificationException("邮箱错误");
		}

		CommonResponseDto response = userService.findPassword(email);

		if (response.getResult() == UserConstant.SUCCESS) {
			model.addObject(Constant.USER_STATUS_KEY,
					Constant.USER_FIND_PASSWORD_SUCCESS);
		} else {
			throw new VerificationException(response.getErrorMessage());
		}

	} catch (VerificationException e) {
		// 注册失败异常
		model.addObject(
				FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
				e.getMessage());
		model.addObject(Constant.USER_STATUS_KEY,
				Constant.USER_FIND_PASSWORD_FAIL);
	}
	return model;
}
 
@Test
public void invokesCorrectMethodOnDelegate() throws Exception {
	MultiActionController mac = new MultiActionController();
	TestDelegate d = new TestDelegate();
	mac.setDelegate(d);
	HttpServletRequest request = new MockHttpServletRequest("GET", "/test.html");
	HttpServletResponse response = new MockHttpServletResponse();
	ModelAndView mv = mac.handleRequest(request, response);
	assertTrue("view name is test", mv.getViewName().equals("test"));
	assertTrue("Delegate was invoked", d.invoked);
}
 
源代码20 项目: OAuth-2.0-Cookbook   文件: ApplicationController.java
@GetMapping("/dashboard")
public ModelAndView dashboard() {
    DefaultOidcUser user = (DefaultOidcUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    ModelAndView mv = new ModelAndView("dashboard");
    mv.addObject("profile", user.getUserInfo().getClaims());
    return mv;
}
 
@RequestMapping("/processes")
public ModelAndView processes() {
    ModelAndView mav = new ModelAndView("processes");
    List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();
    mav.addObject("processes", list);
    return mav;
}
 
@Override
protected ModelAndView writeToInternal(HttpServletRequest servletRequest,
		HttpServletResponse servletResponse, Context context) {

	AsyncContext asyncContext = servletRequest.startAsync(servletRequest,
			new NoContentLengthResponseWrapper(servletResponse));
	entity().subscribe(new ProducingSubscriber(asyncContext, context));
	return null;
}
 
源代码23 项目: TinyMooc   文件: TeamController.java
@RequestMapping("addApplyUser.htm")
public ModelAndView addApplyUser(HttpServletRequest req, HttpServletResponse res) {
    String userTeamId = ServletRequestUtils.getStringParameter(req, "userTeamId", "");
    UserTeam userTeam = teamService.findById(UserTeam.class, userTeamId);
    String teamId = userTeam.getTeam().getTeamId();
    userTeam.setUserState("批准");
    userTeam.setApproveDate(new Date());
    userTeam.setContribution(0);
    userTeam.setUserPosition("组员");
    teamService.update(userTeam);
    return new ModelAndView("redirect:membersAdminPage.htm?teamId=" + teamId);
}
 
@GetMapping("/my")
public ModelAndView myEvents() {
    CalendarUser currentUser = userContext.getCurrentUser();
    Integer currentUserId = currentUser.getId();
    ModelAndView result = new ModelAndView("events/my", "events", calendarService.findForUser(currentUserId));
    result.addObject("currentUser", currentUser);
    return result;
}
 
源代码25 项目: kafka-eagle   文件: AlarmController.java
/** Modify alarmer viewer. */
@RequiresPermissions("/alarm/modify")
@RequestMapping(value = "/alarm/modify", method = RequestMethod.GET)
public ModelAndView modifyView(HttpSession session) {
	ModelAndView mav = new ModelAndView();
	mav.setViewName("/alarm/modify");
	return mav;
}
 
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	ModelAndView mav = (ModelAndView) returnValue;
	if (mav.isReference()) {
		String viewName = mav.getViewName();
		mavContainer.setViewName(viewName);
		if (viewName != null && isRedirectViewName(viewName)) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	else {
		View view = mav.getView();
		mavContainer.setView(view);
		if (view instanceof SmartView) {
			if (((SmartView) view).isRedirectView()) {
				mavContainer.setRedirectModelScenario(true);
			}
		}
	}
	mavContainer.addAllAttributes(mav.getModel());
}
 
源代码27 项目: SA47   文件: AdminEmployeeController.java
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView employeeListPage() {
	ModelAndView mav = new ModelAndView("employee-list");
	List<Employee> employeeList = eService.findAllEmployees();
	mav.addObject("employeeList", employeeList);
	return mav;
}
 
源代码28 项目: tutorials   文件: SessionTimerInterceptor.java
/**
 * Executed before after handler is executed
 **/
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView model) throws Exception {
    log.info("Post handle method - check execution time of handling");
    long startTime = (Long) request.getAttribute("executionTime");
    log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime);
}
 
源代码29 项目: cachecloud   文件: AppController.java
/**
 * 执行应用命令
 *
 * @param appId
 * @return
 */
@RequestMapping("/commandExecute")
public ModelAndView commandExecute(HttpServletRequest request, HttpServletResponse response, Model model, Long appId) {
    if (appId != null && appId > 0) {
        model.addAttribute("appId", appId);
        String command = request.getParameter("command");
        String result = appStatsCenter.executeCommand(appId, command);
        model.addAttribute("result", result);
    } else {
        model.addAttribute("result", "error");
    }
    return new ModelAndView("app/commandExecute");
}
 
源代码30 项目: cachecloud   文件: InstanceController.java
@RequestMapping("/command")
public ModelAndView command(HttpServletRequest request, HttpServletResponse response, Model model, Integer admin, Long instanceId, Long appId) {
    if (instanceId != null && instanceId > 0) {
        model.addAttribute("instanceId", instanceId);
    }
    return new ModelAndView("instance/instanceCommand");
}