Java Code Examples for org.springframework.web.servlet.ModelAndView

The following are top voted examples for showing how to use org.springframework.web.servlet.ModelAndView. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Spring-Security-Third-Edition   File: ErrorController.java   View source code 7 votes vote down vote up
@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() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

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

    return mav;
}
 
Example 2
Project: y2t187test   File: UserControl.java   View source code 6 votes vote down vote up
@RequestMapping(value="/dologin.html")
public ModelAndView userLogin(@Valid User loginuser, BindingResult result){
	
	ModelAndView mv = new ModelAndView();
	
	// BindingResult����洢���DZ?��֤�Ľ��
	if(result.hasErrors() == true){ // ��֤����
		mv.setViewName("login");    // ��ת���?ҳ��
		return mv;
	}
	
	// ����Service����ʵ�ֵ�¼��֤
	User user = userService.login(loginuser.getUsercode(), 
								  loginuser.getUserpassword());
	//User user = null;
	// ���user��Ϊnull����¼�ɹ�
	if(user != null){
		mv.setViewName("frame");
	}else{
		mv.addObject("error", "用户名或密码错误 ");
		mv.setViewName("login");
	}
	return mv;
}
 
Example 3
Project: Spring-Security-Third-Edition   File: ErrorController.java   View source code 6 votes vote down vote up
@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() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

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

    return mav;
}
 
Example 4
Project: Spring-Security-Third-Edition   File: ErrorController.java   View source code 6 votes vote down vote up
@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);
    StringBuilder sb = new StringBuilder();
    sb.append("Exception during execution of Spring Security application!   ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

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

    return mav;
}
 
Example 5
Project: uckefu   File: UserController.java   View source code 6 votes vote down vote up
@RequestMapping("/center/fans")
@Menu(type = "apps" , subtype = "user" , name="fans" , access = false)
public ModelAndView centerfans(HttpServletRequest request , HttpServletResponse response, @Valid String orgi, @Valid String q) {
	ModelAndView view = request(super.createAppsTempletResponse("/apps/user/centerfans")) ;
	String userid = super.getUser(request).getId() ;
	Pageable page = new PageRequest(super.getP(request), super.getPs(request), new Sort(Direction.DESC, "createtime")) ;
	Page<Fans> fansList = fansRes.findByUser(userid, page) ;
	
	List<String> userids = new ArrayList<String>();
	for(Fans fan : fansList){
		userids.add(fan.getCreater()) ;
	}
	if(userids.size()>0){
		view.addObject("fansList",new PageImpl<User>(userRes.findAll(userids), page, fansList.getTotalElements()) ) ;
	}
	
    return view;
}
 
Example 6
Project: Spring-Security-Third-Edition   File: LoginController.java   View source code 6 votes vote down vote up
@GetMapping(value = "/login")
public ModelAndView login(
        @RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout) {

    logger.info("******login(error): {} ***************************************", error);
    logger.info("******login(logout): {} ***************************************", logout);

    ModelAndView model = new ModelAndView();
    if (error != null) {
        model.addObject("error", "Invalid username and password!");
    }

    if (logout != null) {
        model.addObject("message", "You've been logged out successfully.");
    }
    model.setViewName("login");

    return model;

}
 
Example 7
Project: airsonic   File: EditTagsController.java   View source code 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    MediaFile dir = mediaFileService.getMediaFile(id);
    List<MediaFile> files = mediaFileService.getChildrenOf(dir, true, false, true, false);

    Map<String, Object> map = new HashMap<String, Object>();
    if (!files.isEmpty()) {
        map.put("defaultArtist", files.get(0).getArtist());
        map.put("defaultAlbum", files.get(0).getAlbumName());
        map.put("defaultYear", files.get(0).getYear());
        map.put("defaultGenre", files.get(0).getGenre());
    }
    map.put("allGenres", JaudiotaggerParser.getID3V1Genres());

    List<Song> songs = new ArrayList<Song>();
    for (int i = 0; i < files.size(); i++) {
        songs.add(createSong(files.get(i), i));
    }
    map.put("id", id);
    map.put("songs", songs);

    return new ModelAndView("editTags","model",map);
}
 
Example 8
Project: REST-Web-Services   File: SearchController.java   View source code 6 votes vote down vote up
/**
 * @param type Type of data sought
 * @param q Search for a phrase
 * @param page Page number
 * @param pageSize Number of items per page
 * @param modelMap {@link ModelMap}
 * @return The ModelAndView for a list of users (or a list of movies( in the future ))
 */
@GetMapping(value = "/search")
public ModelAndView search(
        @RequestParam final String type,
        @RequestParam final String q,
        @RequestParam(defaultValue = "1") final int page,
        @RequestParam(defaultValue = "1") final int pageSize,
        final ModelMap modelMap
) {
    modelMap.addAttribute("type", type);
    modelMap.addAttribute("q", q);
    modelMap.addAttribute("page", page);
    modelMap.addAttribute("pageSize", pageSize);

    return new ModelAndView("users", modelMap);
}
 
Example 9
Project: Building-Web-Apps-with-Spring-5-and-Angular   File: UserAccountController.java   View source code 6 votes vote down vote up
@PostMapping(value="/forgotpassword/process", produces="application/json")
public ModelAndView processForgotPassword(ModelMap model, @RequestParam("emailaddress") String email) {
	
	User user = null;
	try {
		user = userService.doesUserExist(email);
	} catch (UserNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	if(user != null) {
		
	}	
	model.addAttribute("message", "An email notification is sent to the registered email address.");
	return new ModelAndView("forgotpassword", model);
}
 
Example 10
Project: spring-cloud-sample   File: ControllerExceptionHandler.java   View source code 6 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    if (ex instanceof UserApiException) {
        UserApiException apiException = (UserApiException) ex;
        UserExceptionData userExceptionData = new UserExceptionData();
        userExceptionData.setCode(apiException.getCode());
        userExceptionData.setMessage(apiException.getMessage());
        UserExceptionInfo userExceptionInfo = new UserExceptionInfo();
        userExceptionInfo.setExceptionClass(ex.getClass().getName());
        userExceptionInfo.setUserExceptionData(userExceptionData);

        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(JSON.toJSONString(userExceptionInfo));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new ModelAndView();
    }
    throw new RuntimeException(ex);
}
 
Example 11
Project: way_learning   File: MemberController.java   View source code 6 votes vote down vote up
@RequestMapping("showMyRecord")
public ModelAndView showMyRecord(HttpServletRequest request, ModelAndView mav) throws Exception {
	System.out.println("showMyRecord 컨트롤러 입성!");
	Member mvo = (Member) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	String userId = mvo.getUserId();
	System.out.println("showMyRecord 유저아이디:" + userId);
	List<String> rightList = memberService.selectRightNo(userId);
	List<String> wrongList = memberService.selectWrongNo(userId);
	AnswerResult answerResult = memberService.selectMyRecord(userId);
	int myRanking = memberService.selectMyRanking(userId);
	mav.addObject("rightList", rightList);
	mav.addObject("wrongList", wrongList);
	mav.addObject("answerResult", answerResult);
	mav.addObject("myRanking", myRanking);
	mav.setViewName("/member/showMyRecord");

	return mav;
}
 
Example 12
Project: Spring-Security-Third-Edition   File: LoginController.java   View source code 6 votes vote down vote up
@GetMapping(value = "/login")
public ModelAndView login(
        @RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout) {

    logger.info("******login(error): {} ***************************************", error);
    logger.info("******login(logout): {} ***************************************", logout);

    ModelAndView model = new ModelAndView();
    if (error != null) {
        model.addObject("error", "Invalid username and password!");
    }

    if (logout != null) {
        model.addObject("message", "You've been logged out successfully.");
    }
    model.setViewName("login");

    return model;

}
 
Example 13
Project: Spring-Security-Third-Edition   File: ErrorController.java   View source code 6 votes vote down vote up
@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() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

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

    return mav;
}
 
Example 14
Project: Spring-Security-Third-Edition   File: LoginController.java   View source code 6 votes vote down vote up
@GetMapping(value = "/login")
public ModelAndView login(
        @RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout) {

    logger.info("******login(error): {} ***************************************", error);
    logger.info("******login(logout): {} ***************************************", logout);

    ModelAndView model = new ModelAndView();
    if (error != null) {
        model.addObject("error", "Invalid username and password!");
    }

    if (logout != null) {
        model.addObject("message", "You've been logged out successfully.");
    }
    model.setViewName("login");

    return model;

}
 
Example 15
Project: cas-server-4.2.1   File: OAuth20CallbackAuthorizeControllerTests.java   View source code 6 votes vote down vote up
@Test
public void verifyOKWithState() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(
            "GET",
            CONTEXT
            + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET);
    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI);
    mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME);
    mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE);
    mockRequest.setSession(mockSession);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName());
    final Map<String, Object> map = modelAndView.getModel();
    assertEquals(SERVICE_NAME, map.get("serviceName"));
    assertEquals(REDIRECT_URI + '?' + OAuthConstants.CODE + '=' + SERVICE_TICKET + '&' + OAuthConstants.STATE + '='
            + STATE, map.get("callbackUrl"));
}
 
Example 16
Project: Spring-Security-Third-Edition   File: ErrorController.java   View source code 6 votes vote down vote up
@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() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append("\n\nroot cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

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

    return mav;
}
 
Example 17
Project: airsonic   File: PlaylistController.java   View source code 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<>();

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    User user = securityService.getCurrentUser(request);
    String username = user.getUsername();
    UserSettings userSettings = settingsService.getUserSettings(username);
    Player player = playerService.getPlayer(request, response);
    Playlist playlist = playlistService.getPlaylist(id);
    if (playlist == null) {
        return new ModelAndView(new RedirectView("notFound"));
    }

    map.put("playlist", playlist);
    map.put("user", user);
    map.put("player", player);
    map.put("editAllowed", username.equals(playlist.getUsername()) || securityService.isAdmin(username));
    map.put("partyMode", userSettings.isPartyModeEnabled());

    return new ModelAndView("playlist","model",map);
}
 
Example 18
Project: spring-boot-blog   File: BlogController.java   View source code 5 votes vote down vote up
@RequestMapping(value = "/blog/{username}", method = RequestMethod.GET)
    public ModelAndView blogForUsername(@PathVariable String username,
                                        @RequestParam("pageSize") Optional<Integer> pageSize,
                                        @RequestParam("page") Optional<Integer> page) {
        // Evaluate page size. If requested parameter is null, return initial
        // page size
        int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE);
        // Evaluate page. If requested parameter is null or less than 0 (to
        // prevent exception), return initial size. Otherwise, return value of
        // param. decreased by 1.
        int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1;

        ModelAndView modelAndView = new ModelAndView();
        User user = userService.findByUsername(username);
        if (user == null) {
            modelAndView.setViewName("404");
        } else {
            Page<Post> posts = postService.findByUserOrderedByDatePageable(user, new PageRequest(evalPage, evalPageSize));
            Pager pager = new Pager(posts.getTotalPages(), posts.getNumber(), BUTTONS_TO_SHOW);

//            modelAndView.addObject("posts", postService.findNLatestPostsForUser(10, user));
            modelAndView.addObject("posts", posts);
            modelAndView.addObject("selectedPageSize", evalPageSize);
            modelAndView.addObject("pageSizes", PAGE_SIZES);
            modelAndView.addObject("pager", pager);
            modelAndView.addObject("user", user);
            modelAndView.setViewName("posts");
        }
        return modelAndView;
    }
 
Example 19
Project: springboot-shiro-cas-mybatis   File: OAuth20AuthorizeControllerTests.java   View source code 5 votes vote down vote up
@Test
public void verifyNoRedirectUri() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(OAuthConstants.ERROR_VIEW, modelAndView.getViewName());
}
 
Example 20
Project: airsonic   File: TopController.java   View source code 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {
    Map<String, Object> map = new HashMap<>();

    User user = securityService.getCurrentUser(request);
    UserSettings userSettings = settingsService.getUserSettings(user.getUsername());

    map.put("user", user);
    map.put("showSideBar", userSettings.isShowSideBar());
    map.put("showAvatar", userSettings.getAvatarScheme() != AvatarScheme.NONE);
    return new ModelAndView("top","model", map);
}
 
Example 21
Project: xxl-api   File: CookieInterceptor.java   View source code 5 votes vote down vote up
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
	
	if (modelAndView!=null && ArrayUtils.isNotEmpty(request.getCookies())) {
		HashMap<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		for (Cookie ck : request.getCookies()) {
			cookieMap.put(ck.getName(), ck);
		}
		modelAndView.addObject("cookieMap", cookieMap);
	}
	
	super.postHandle(request, response, handler, modelAndView);
}
 
Example 22
Project: MoviesSearchPos   File: IndexController.java   View source code 5 votes vote down vote up
@GetMapping("/consulta")
public ModelAndView consulta(@RequestParam("titulo") String titulo, @RequestParam("desc") String desc, @RequestParam("ano") Integer ano) {
	ModelAndView mav = new ModelAndView("/consulta");
	mav.addObject("listaFilmes", filmes.getSearchFilmes(titulo, desc, ano));
	System.out.println("Passando por consulta");
	return mav;
}
 
Example 23
Project: bookshelf   File: AppController.java   View source code 5 votes vote down vote up
@GetMapping("report")
public ModelAndView createReport(@RequestParam("groupby") String groupBy) {
    Map<Integer, List<Book>> mapByYear = reportingService.generateMapByYear();
    Map<String, List<Book>> mapByAuthor = reportingService.generateMapByAuthor();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("booksMap", groupBy.equals("year") ? mapByYear : mapByAuthor);
    modelAndView.addObject("groupBy", groupBy);
    return modelAndView;
}
 
Example 24
Project: way_learning   File: EssayQuestionController.java   View source code 5 votes vote down vote up
@RequestMapping("/getEssayList")
public ModelAndView getEssayList(HttpServletRequest request, ModelAndView mav, HttpServletResponse response,
		@RequestParam(defaultValue = "") String keyword)
		throws SQLException {
	System.out.println("keyword:" + keyword);
	List<AlgorithmQuestion> list = questionService.getEssayList(keyword);
	System.out.println("qna  컨트롤러 에서 list:" + list);

	mav.addObject("list", list);
	mav.addObject("keyword", keyword);
	mav.setViewName("/question/essay/list");

	return mav;
}
 
Example 25
Project: microservice   File: ProcessInstanceController.java   View source code 5 votes vote down vote up
@RequestMapping(value = "running")
    public ModelAndView running(Model model, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/workflow/running-manage");
//        Page<ProcessInstance> page = new Page<ProcessInstance>(PageUtil.PAGE_SIZE);
//        int[] pageParams = PageUtil.init(page, request);

        ProcessInstanceQuery processInstanceQuery = runtimeService.createProcessInstanceQuery();
        List<ProcessInstance> list = processInstanceQuery.listPage(1, 10);
//        page.setResult(list);
//        page.setTotalCount(processInstanceQuery.count());
        mav.addObject("page", list);
        return mav;
    }
 
Example 26
Project: dubbo-mock   File: MockOperDefineController.java   View source code 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/selectMockOperDefine")
public ModelAndView selectMockService(HttpServletRequest arg0, Boolean selectFlag) throws Exception {
    Map<String, String> paraMap = assembleRequestParamForMap(arg0, null);
    MockServiceDefine mockService = assembleRequestParamForBean(paraMap, MockServiceDefine.class);
    MockOperDefine mockOperDefine = mockOperDefineServiceImpl.selectMockOperDefine(mockService);
    mockOperDefine.setMockRuleNames(mockServiceServiceImpl.selectMockRoleNames(mockService.getId()));
    ModelAndView view = new ModelAndView("jsp/selectMockOperDefine");
    view.addObject("mockOperDefine", mockOperDefine);
    return view;
}
 
Example 27
Project: way_learning   File: TechBoardController.java   View source code 5 votes vote down vote up
@RequestMapping("updateView")
public ModelAndView updateView(String boardNo, ModelAndView mav)
		throws Exception{
	TechBoard bvo=techBoardService.showContent(boardNo);

	List tagList= techBoardService.getTag(bvo.getBoardNo()+"");
	mav.setViewName("board/tech/update");
	mav.addObject("tagList", tagList);
	mav.addObject("bvo",bvo);
	System.out.println("컨트롤러 bvo:"+bvo);

	return mav;
}
 
Example 28
Project: Gather-Platform   File: CommonsSpiderPanel.java   View source code 5 votes vote down vote up
@RequestMapping(value = "listSpiderInfo", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView listSpiderInfo(String domain, @RequestParam(defaultValue = "1", required = false) int page) {
    ModelAndView modelAndView = new ModelAndView("panel/commons/listSpiderInfo");
    if (StringUtils.isBlank(domain)) {
        modelAndView.addObject("spiderInfoList", spiderInfoService.listAll(10, page).getResultList());
    } else {
        modelAndView.addObject("spiderInfoList", spiderInfoService.getByDomain(domain, 10, page).getResultList());
    }
    modelAndView.addObject("page", page);
    modelAndView.addObject("domain", domain);
    return modelAndView;
}
 
Example 29
Project: PowerApi   File: UnauthorizedExceptionHandler.java   View source code 5 votes vote down vote up
@ExceptionHandler({UnauthorizedException.class})
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
    ModelAndView mv = new ModelAndView();
    mv.addObject("exception", e.getMessage());
    mv.setViewName("/common/error");
    return mv;
}
 
Example 30
Project: cas4.0.x-server-wechat   File: ServiceValidateControllerTests.java   View source code 5 votes vote down vote up
@Test
public void testValidServiceTicketWithValidPgtAndProxyHandling() throws Exception {
    final String tId = getCentralAuthenticationService()
            .createTicketGrantingTicket(TestUtils.getCredentialsWithSameUsernameAndPassword());
    final String sId = getCentralAuthenticationService().grantServiceTicket(tId, TestUtils.getService());

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", TestUtils.getService().getId());
    request.addParameter("ticket", sId);
    request.addParameter("pgtUrl", "https://www.github.com");

    final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse());
    assertEquals(ServiceValidateController.DEFAULT_SERVICE_SUCCESS_VIEW_NAME, modelAndView.getViewName());
    assertNotNull(modelAndView.getModel().get("pgtIou"));
}
 
Example 31
Project: cas4.0.x-server-wechat   File: DelegatingController.java   View source code 5 votes vote down vote up
/**
 * Handles the request.
 * Ask all delegates if they can handle the current request.
 * The first to answer true is elected as the delegate that will process the request.
 * If no controller answers true, we redirect to the error page.
 * @param request the request to handle
 * @param response the response to write to
 * @return the model and view object
 * @throws Exception if an error occurs during request handling
 */
@Override
protected final ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response)
                                                throws Exception {
    for (DelegateController delegate : delegates) {
        if (delegate.canHandle(request, response)) {
            return delegate.handleRequest(request, response);
        }
    }
    return generateErrorView("INVALID_REQUEST", "INVALID_REQUEST", null);
}
 
Example 32
Project: Spring-Security-Third-Edition   File: EventsController.java   View source code 5 votes vote down vote up
@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;
}
 
Example 33
Project: OAuth-2.0-Cookbook   File: ProfileController.java   View source code 5 votes vote down vote up
@GetMapping("/form")
public ModelAndView form() {
    FacebookUser user = (FacebookUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Optional<Profile> profile = profileRepository.findByUser(user);

    ModelAndView mv = new ModelAndView("form");
    if (profile.isPresent()) {
        mv.addObject("profile", profile.get());
    } else {
        mv.addObject("profile", new Profile());
    }

    return mv;
}
 
Example 34
Project: cas-5.1.0   File: ManageRegisteredServicesMultiActionController.java   View source code 5 votes vote down vote up
/**
 * Method to show the RegisteredServices.
 *
 * @param response the response
 * @return the Model and View to go to after the services are loaded.
 */
@GetMapping(value = "/manage.html")
public ModelAndView manage(final HttpServletResponse response) {
    ensureDefaultServiceExists();
    final Map<String, Object> model = new HashMap<>();
    model.put("defaultServiceUrl", this.defaultService.getId());
    model.put(STATUS, HttpServletResponse.SC_OK);
    return new ModelAndView("manage", model);
}
 
Example 35
Project: spring_mvc_demo   File: PDFController.java   View source code 5 votes vote down vote up
protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    Map<String,String> userData = new HashMap<String,String>();
    userData.put("100", "Xiao.Lu");
    userData.put("102", "User 102");
    userData.put("301", "User 301");
    userData.put("400", "User 400");
    return new ModelAndView("UserSummary","userData",userData);
}
 
Example 36
Project: sdoc   File: DocumentScanner.java   View source code 5 votes vote down vote up
public boolean isIgnoreResponseClass(Class<?> clazz) {
    if (clazz == ModelAndView.class || clazz == Map.class || clazz == Object.class) {
        return true;
    } else {
        return false;
    }
}
 
Example 37
Project: mensa-api   File: MensaWebController.java   View source code 5 votes vote down vote up
private ModelAndView renderMenu(Mensa mensa, LocalDate date, ModelAndView modelAndView) {
    modelAndView.addObject("mensa", mensa);
    modelAndView.addObject("date", DateTimeFormatter.ofPattern("EEEE, dd.MM.yyyy", Locale.ENGLISH).format(date));
    List<Dish> dishesFromRepo = dishRepo.findByDateAndMensaIdOrderByIdAsc(date, mensa.getId());
    List<String> categories = dishesFromRepo.stream().map(Dish::getCategory).distinct().collect(Collectors.toList());
    modelAndView.addObject("categories", categories);
    List<DishWebDTO> dishes = dishesFromRepo.stream().map(dishDtoFactory::create).collect(Collectors.toList());
    Map<String,List<DishWebDTO>> dishesMap = dishes.stream().collect(Collectors.groupingBy(DishWebDTO::getCategory, Collectors.toList()));
    modelAndView.addObject("dishesMap", dishesMap);
    modelAndView.addObject("next", timeUtils.nextOpeningDay(date.plusDays(1), mensa));
    modelAndView.addObject("previous", timeUtils.lastOpeningDay(date.minusDays(1), mensa));
    modelAndView.setViewName("menu");
    return modelAndView;
}
 
Example 38
Project: mumu   File: SysLoginController.java   View source code 5 votes vote down vote up
/**
 * 用户登录
 * @return
 */
@MumuLog(name = "用户登录",operater = "POST")
@RequestMapping(value = "/login",method = {RequestMethod.POST})
public ModelAndView logining(HttpServletRequest request){
    String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
    String error = null;
    if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
        error = "用户名/密码错误";
    } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
        error = "用户名/密码错误";
    } else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)){
        error = "输入错误次数太过,请稍后重试";
    } else if(DisabledAccountException.class.getName().equals(exceptionClassName)){
        error="账户被锁定,请联系管理员";
    }else if(AccountUnActiveException.class.getName().equals(exceptionClassName)){
        error="账户未激活,请登录邮箱激活账号!";
    }else if (exceptionClassName != null) {
        error = "错误提示:" + exceptionClassName;
    }
    Map<String,String> map=new HashMap<String,String>();
    if(error!=null){
        request.setAttribute("shiroLoginFailure", error);
        map.put("code","500");
        map.put("msg","failure");
        map.put("data",error);
        return new ModelAndView("login",map);
    }
    map.put("code","200");
    map.put("msg","success");
    map.put("data","登录成功");

    return new ModelAndView("redirect:/system/index",map);
}
 
Example 39
Project: uis   File: GlobalExceptionHandler.java   View source code 5 votes vote down vote up
@ExceptionHandler(DataAccessException.class)
@ResponseStatus(value=HttpStatus.CONFLICT)
public ModelAndView handleDataAccessExceptions(HttpServletRequest request, DataAccessException ex) {
    logger.warn("DataAccessException: " + request.getRequestURL(), ex);
    ModelAndView mav = new ModelAndView();
    mav.setViewName("error");
    return mav;
}
 
Example 40
Project: java-learn   File: RequestInterceptor.java   View source code 5 votes vote down vote up
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
                       Object object, ModelAndView model)
        throws Exception {
    log.info("In postHandle request processing "
            + "completed by @RestController");

    BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String body = IOUtils.toString(reader);

    System.out.println(body);

}