Java Code Examples for org.springframework.web.servlet.mvc.support.RedirectAttributes#addFlashAttribute()

The following examples show how to use org.springframework.web.servlet.mvc.support.RedirectAttributes#addFlashAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MenuController.java    From Mario with Apache License 2.0 6 votes vote down vote up
@RequiresRoles("admin")
@RequestMapping(value = "create", method = RequestMethod.POST)
public String create(@Valid Menu menu, BindingResult result, Model model,
        RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        Menu topMenu = accountService.getTopMenu();
        menu.setParent(topMenu);

        model.addAttribute("menu", menu);
        model.addAttribute("allShows", allShows);
        model.addAttribute("action", "create");

        return "account/menuForm";
    }
    generateMenuParentIds(menu);
    accountService.saveMenu(menu);
    redirectAttributes.addFlashAttribute("message", "创建菜单成功");

    return "redirect:/account/menu";
}
 
Example 2
Source File: TaskController.java    From spring4-sandbox with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, params = "!action")
public String updateTask(@PathVariable("id") Long id, @ModelAttribute("task") @Valid TaskForm fm, BindingResult result, RedirectAttributes redirectAttrs) {
	
	log.debug("updating task @" + fm);
	if (result.hasErrors()) {
		return "edit";
	}

	Task task = taskRepository.findOne(id);

	if (task == null) {
		throw new TaskNotFoundException(id);
	}

	task.setName(fm.getName());
	task.setDescription(fm.getDescription());

	taskRepository.save(task);
	
	redirectAttrs.addFlashAttribute("flashMessage", AlertMessage.info("Task is updated sucessfully!"));

	return "redirect:/tasks";
}
 
Example 3
Source File: EventsController.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@PostMapping(value = "/new")
public String createEvent(@Valid CreateEventForm createEventForm, BindingResult result,
        RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        return "events/create";
    }
    CalendarUser attendee = calendarService.findUserByEmail(createEventForm.getAttendeeEmail());
    if (attendee == null) {
        result.rejectValue("attendeeEmail", "attendeeEmail.missing",
                "Could not find a user for the provided Attendee Email");
    }
    if (result.hasErrors()) {
        return "events/create";
    }
    Event event = new Event();
    event.setAttendee(attendee);
    event.setDescription(createEventForm.getDescription());
    event.setOwner(userContext.getCurrentUser());
    event.setSummary(createEventForm.getSummary());
    event.setWhen(createEventForm.getWhen());
    calendarService.createEvent(event);
    redirectAttributes.addFlashAttribute("message", "Successfully added the new event");
    return "redirect:/events/my";
}
 
Example 4
Source File: EventsController.java    From maven-framework-project with MIT License 6 votes vote down vote up
@RequestMapping(value = "/new", method = RequestMethod.POST)
public String createEvent(@Valid CreateEventForm createEventForm, BindingResult result,
        RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        return "events/create";
    }
    CalendarUser attendee = calendarService.findUserByEmail(createEventForm.getAttendeeEmail());
    if (attendee == null) {
        result.rejectValue("attendeeEmail", "attendeeEmail.missing",
                "Could not find a user for the provided Attendee Email");
    }
    if (result.hasErrors()) {
        return "events/create";
    }
    Event event = new Event();
    event.setAttendee(attendee);
    event.setDescription(createEventForm.getDescription());
    event.setOwner(userContext.getCurrentUser());
    event.setSummary(createEventForm.getSummary());
    event.setWhen(createEventForm.getWhen());
    calendarService.createEvent(event);
    redirectAttributes.addFlashAttribute("message", "Successfully added the new event");
    return "redirect:/events/my";
}
 
Example 5
Source File: EventsController.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@PostMapping(value = "/new")
public String createEvent(@Valid CreateEventForm createEventForm, BindingResult result,
        RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        return "events/create";
    }
    CalendarUser attendee = calendarService.findUserByEmail(createEventForm.getAttendeeEmail());
    if (attendee == null) {
        result.rejectValue("attendeeEmail", "attendeeEmail.missing",
                "Could not find a user for the provided Attendee Email");
    }
    if (result.hasErrors()) {
        return "events/create";
    }
    Event event = new Event();
    event.setAttendee(attendee);
    event.setDescription(createEventForm.getDescription());
    event.setOwner(userContext.getCurrentUser());
    event.setSummary(createEventForm.getSummary());
    event.setWhen(createEventForm.getWhen());
    calendarService.createEvent(event);
    redirectAttributes.addFlashAttribute("message",
            "Successfully added the new event");
    return "redirect:/events/my";
}
 
Example 6
Source File: IdentityController.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
/**
 * 保存Group
 *
 * @return
 */
@RequestMapping(value = "group/save", method = RequestMethod.POST)
public String saveGroup(@RequestParam("groupId") String groupId,
                        @RequestParam("groupName") String groupName,
                        @RequestParam("type") String type,
                        RedirectAttributes redirectAttributes) {
    Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
    if (group == null) {
        group = identityService.newGroup(groupId);
    }
    group.setName(groupName);
    group.setType(type);
    identityService.saveGroup(group);
    redirectAttributes.addFlashAttribute("message", "成功添加组[" + groupName + "]");
    return "redirect:/chapter14/identity/group/list";
}
 
Example 7
Source File: StaffHtmlController.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * 削除処理
 *
 * @param staffId
 * @param attributes
 * @return
 */
@PostMapping("/remove/{staffId}")
public String removeStaff(@PathVariable Long staffId, RedirectAttributes attributes) {
    // 論理削除する
    staffService.delete(staffId);

    // 削除成功メッセージ
    attributes.addFlashAttribute(GLOBAL_MESSAGE, getMessage(MESSAGE_DELETED));

    return "redirect:/system/staffs/find";
}
 
Example 8
Source File: BaseController.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 添加Flash消息
 */
protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
	StringBuilder sb = new StringBuilder();
	for (String message : messages){
		sb.append(message).append(messages.length>1?"<br/>":"");
	}
	redirectAttributes.addFlashAttribute("message", sb.toString());
}
 
Example 9
Source File: UserController.java    From es with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "changePassword")
public String changePassword(
        HttpServletRequest request,
        @RequestParam("ids") Long[] ids, @RequestParam("newPassword") String newPassword,
        @CurrentUser User opUser,
        RedirectAttributes redirectAttributes) {

    getUserService().changePassword(opUser, ids, newPassword);

    redirectAttributes.addFlashAttribute(Constants.MESSAGE, "改密成功!");

    return redirectToUrl((String) request.getAttribute(Constants.BACK_URL));
}
 
Example 10
Source File: FlashAttributeAssertionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@RequestMapping(value="/persons", method=RequestMethod.POST)
public String save(RedirectAttributes redirectAttrs) throws Exception {
	redirectAttrs.addFlashAttribute("one", "1");
	redirectAttrs.addFlashAttribute("two", 2.222);
	redirectAttrs.addFlashAttribute("three", new URL("http://example.com"));
	return "redirect:/person/1";
}
 
Example 11
Source File: NotificationManagementController.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
@GetMapping("/{notification}/delete")
public String deleteNotification(@RequestParam(required = false) Integer page, @PathVariable Notification notification, RedirectAttributes redirectAttributes) {
    ErrorUtils.requireNonNullNotification(notification);
    int currentPage = NotificationUtils.normalizePage(page);

    notificationManagementService.deleteNotification(notification);
    redirectAttributes.addFlashAttribute("notification_success", "Notification Deleted");
    return "redirect:/management/notifications?page=" + currentPage;
}
 
Example 12
Source File: GoogleAnalyticsUpdateController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public String update(
		@PathVariable String language,
		@Validated @ModelAttribute(FORM_MODEL_KEY) GoogleAnalyticsUpdateForm form,
		BindingResult errors,
		@AuthenticationPrincipal AuthorizedUser authorizedUser,
		RedirectAttributes redirectAttributes) {
	redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
	redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

	if (errors.hasErrors()) {
		return "redirect:/_admin/{language}/analytics/edit?step.edit";
	}

	GoogleAnalyticsUpdateRequest request = new GoogleAnalyticsUpdateRequest();
	request.setBlogId(Blog.DEFAULT_ID);
	request.setTrackingId(form.getTrackingId());
	request.setProfileId(form.getProfileId());
	request.setCustomDimensionIndex(form.getCustomDimensionIndex());
	request.setServiceAccountId(form.getServiceAccountId());
	request.setServiceAccountP12File(form.getServiceAccountP12File());

	GoogleAnalytics updatedGoogleAnalytics;
	try {
		updatedGoogleAnalytics = blogService.updateGoogleAnalytics(request);
	} catch (GoogleAnalyticsException e) {
		errors.reject("GoogleAnalytics");
		return "redirect:/_admin/{language}/analytics/edit?step.edit";
	}

	redirectAttributes.getFlashAttributes().clear();
	redirectAttributes.addFlashAttribute("updatedGoogleAnalytics", updatedGoogleAnalytics);
	return "redirect:/_admin/{language}/analytics";
}
 
Example 13
Source File: SignupController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@PostMapping(value="/signup/new")
public String signup(@Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) {
    if(result.hasErrors()) {
        return "signup/form";
    }

    String email = signupForm.getEmail();
    if(calendarService.findUserByEmail(email) != null) {
        result.rejectValue("email", "errors.signup.email", "Email address is already in use.");
        return "signup/form";
    }

    CalendarUser user = new CalendarUser();
    user.setEmail(email);
    user.setFirstName(signupForm.getFirstName());
    user.setLastName(signupForm.getLastName());
    user.setPassword(signupForm.getPassword());

    logger.info("CalendarUser: {}", user);

    int id = calendarService.createUser(user);
    user.setId(id);
    userContext.setCurrentUser(user);

    redirectAttributes.addFlashAttribute("message", "You have successfully signed up and logged in.");
    return "redirect:/";
}
 
Example 14
Source File: MessageController.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@PostMapping
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
    if (result.hasErrors()) {
        return new ModelAndView("messages/form", "formErrors", result.getAllErrors());
    }
    message = this.messageRepository.save(message);
    redirect.addFlashAttribute("globalMessage", "view.success");
    return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
}
 
Example 15
Source File: AdminRoleController.java    From SA47 with The Unlicense 5 votes vote down vote up
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public ModelAndView editRole(@ModelAttribute @Valid Role role, BindingResult result, @PathVariable String id,
		final RedirectAttributes redirectAttributes) throws RoleNotFound {

	if (result.hasErrors())
		return new ModelAndView("role-edit");

	ModelAndView mav = new ModelAndView("redirect:/admin/role/list");
	String message = "Role was successfully updated.";

	rService.changeRole(role);

	redirectAttributes.addFlashAttribute("message", message);
	return mav;
}
 
Example 16
Source File: SignupController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping(value="/signup/new",method=RequestMethod.POST)
public String signup(@Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) {
    if(result.hasErrors()) {
        return "signup/form";
    }

    String email = signupForm.getEmail();
    if(calendarService.findUserByEmail(email) != null) {
        result.rejectValue("email", "errors.signup.email", "Email address is already in use.");
        return "signup/form";
    }

    CalendarUser user = new CalendarUser();
    user.setEmail(email);
    user.setFirstName(signupForm.getFirstName());
    user.setLastName(signupForm.getLastName());
    user.setPassword(signupForm.getPassword());

    logger.info("CalendarUser: {}", user);

    int id = calendarService.createUser(user);
    user.setId(id);
    userContext.setCurrentUser(user);

    redirectAttributes.addFlashAttribute("message", "You have successfully signed up and logged in.");
    return "redirect:/";
}
 
Example 17
Source File: CredentialsManagementController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@PutMapping
protected String updateCreds(Principal user,
        @ModelAttribute("command") @Validated(value = { Default.class, CredentialUpdateChecks.class }) CredentialsManagementCommand cmc,
        BindingResult br, RedirectAttributes redirectAttributes) {
    if (br.hasErrors()) {
        return "credentialsSettings";
    }

    List<Boolean> failures = new ArrayList<>();
    List<UserCredential> creds = securityService.getCredentials(user.getName(), App.values());

    cmc.getCredentials().forEach(c -> {
        creds.parallelStream().filter(sc -> StringUtils.equals(String.valueOf(sc.hashCode()), c.getHash()))
                .findAny().ifPresent(dbCreds -> {
                    if (c.getMarkedForDeletion()) {
                        if (!securityService.deleteCredential(dbCreds)) {
                            LOG.warn("Could not delete creds for user {}", dbCreds.getUsername());
                            failures.add(true);
                        }
                    } else {
                        UserCredential newCreds = new UserCredential(dbCreds);
                        newCreds.setEncoder(c.getEncoder());
                        newCreds.setExpiration(c.getExpirationInstant());

                        if (!securityService.updateCredentials(dbCreds, newCreds, "User updated", false)) {
                            LOG.warn("Could not update creds for user {}", dbCreds.getUsername());
                            failures.add(true);
                        }
                    }
                });
    });

    redirectAttributes.addFlashAttribute("settings_toast", failures.isEmpty());

    return "redirect:credentialsSettings.view";
}
 
Example 18
Source File: FilterConfigController.java    From kafka-webview with MIT License 5 votes vote down vote up
/**
 * POST deletes the selected filter.
 */
@RequestMapping(path = "/delete/{id}", method = RequestMethod.POST)
public String delete(@PathVariable final Long id, final RedirectAttributes redirectAttributes) {
    // Retrieve it
    final Optional<Filter> filterOptional = filterRepository.findById(id);
    if (!filterOptional.isPresent()) {
        // Set flash message & redirect
        redirectAttributes.addFlashAttribute("FlashMessage", FlashMessage.newWarning("Unable to remove filter!"));
    } else {
        final Filter filter = filterOptional.get();
        try {
            // Delete any children
            final List<ViewToFilterEnforced> enforcedList = viewToFilterEnforcedRepository.findByFilterId(id);
            final List<ViewToFilterOptional> optionalList = viewToFilterOptionalRepository.findByFilterId(id);

            viewToFilterEnforcedRepository.deleteAll(enforcedList);
            viewToFilterOptionalRepository.deleteAll(optionalList);

            // Delete entity
            filterRepository.deleteById(id);

            // Delete jar from disk
            Files.delete(recordFilterPluginFactory.getPathForJar(filter.getJar()));
            redirectAttributes.addFlashAttribute("FlashMessage", FlashMessage.newSuccess("Deleted filter!"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // redirect to cluster index
    return "redirect:/configuration/filter";
}
 
Example 19
Source File: AccountingEventsPaymentManagerController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
@RequestMapping(value = "{person}/multiplePayments/register", method = RequestMethod.POST)
public String registerMultiplePayments(@PathVariable Person person, HttpSession httpSession, Model model, User loggedUser,
        @RequestParam String identifier, RedirectAttributes redirectAttributes) {

    accessControlService.isPaymentManager(loggedUser);

    final String attribute = MULTIPLE_PAYMENTS_ATTRIBUTE + identifier;

    PaymentsManagementDTO paymentsManagementDTO = (PaymentsManagementDTO) httpSession.getAttribute(
            attribute);

    CreatePaymentsForEvents.run(loggedUser, paymentsManagementDTO.getSelectedEntries(), paymentsManagementDTO
            .getPaymentMethod(), paymentsManagementDTO.getPaymentReference(), new DateTime());

    httpSession.removeAttribute(attribute);
    redirectAttributes.addFlashAttribute(paymentsManagementDTO);

    return "redirect:" + REQUEST_MAPPING + "/" + person.getExternalId() + "/multiplePayments/conclude";
}
 
Example 20
Source File: WebMessageUtil.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
private void addMessage(RedirectAttributes redirect, String cssClass, String text) {
    redirect.addFlashAttribute(MSG_ATTRIBUTE_NAME, new WebMessage(cssClass, text));
}