Java Examples for org.springframework.web.servlet.mvc.support.RedirectAttributes
The following java examples will help you to understand the usage of org.springframework.web.servlet.mvc.support.RedirectAttributes. These source code samples are taken from different open source projects.
Example 1
| Project: cmop-master File: ResourcesExtensionController.java View source code |
/**
* �更实例Compute
*/
@RequestMapping(value = "/compute", method = RequestMethod.POST)
public String updateCompute(@RequestParam(value = "id") Integer id, @RequestParam(value = "osType") Integer osType, @RequestParam(value = "osBit") Integer osBit, @RequestParam(value = "serverType") Integer serverType, @RequestParam(value = "esgIds", required = false) String[] esgIds, @RequestParam(value = "remark") String remark, @RequestParam(value = "applicationName") String[] applicationNames, @RequestParam(value = "applicationVersion") String[] applicationVersions, @RequestParam(value = "applicationDeployPath") String[] applicationDeployPaths, @RequestParam(value = "serviceTagId") Integer serviceTagId, @RequestParam(value = "changeDescription") String changeDescription, RedirectAttributes redirectAttributes) {
Resources resources = comm.resourcesService.getResources(id);
comm.computeService.saveResourcesByCompute(resources, serviceTagId, osType, osBit, serverType, esgIds, remark, applicationNames, applicationVersions, applicationDeployPaths, changeDescription);
redirectAttributes.addFlashAttribute("message", SUCCESS_MESSAGE_TEXT);
return REDIRECT_SUCCESS_URL;
}Example 2
| Project: ldrbrd-master File: SignupController.java View source code |
@RequestMapping(value = "signup", method = RequestMethod.POST)
public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors, RedirectAttributes ra) {
if (errors.hasErrors()) {
return SIGNUP_VIEW_NAME;
}
Account account = accountRepository.save(signupForm.createAccount());
userService.signin(account);
// see /WEB-INF/i18n/messages.properties and /WEB-INF/views/homeSignedIn.html
MessageHelper.addSuccessAttribute(ra, "signup.success");
return "redirect:/";
}Example 3
| Project: lemon-master File: TaskOperationController.java View source code |
/**
* 显示任务表�.
*/
@RequestMapping("task-operation-viewTaskForm")
public String viewTaskForm(@RequestParam("humanTaskId") String humanTaskId, Model model, RedirectAttributes redirectAttributes) throws Exception {
HumanTaskDTO humanTaskDto = humanTaskConnector.findHumanTask(humanTaskId);
if (humanTaskDto == null) {
messageHelper.addFlashMessage(redirectAttributes, "任务ä¸?å˜åœ¨");
return "redirect:/humantask/workspace-listPersonalTasks.do";
}
// 处�转�抄�任务,设置为已读
if (HumanTaskConstants.CATALOG_COPY.equals(humanTaskDto.getCatalog())) {
humanTaskDto.setStatus("complete");
humanTaskDto.setAction("read");
humanTaskConnector.saveHumanTask(humanTaskDto);
}
// 表�
FormDTO formDto = this.findTaskForm(humanTaskDto);
if (formDto.isRedirect()) {
String redirectUrl = formDto.getUrl() + "?humanTaskId=" + formDto.getTaskId();
return "redirect:" + redirectUrl;
}
model.addAttribute("formDto", formDto);
model.addAttribute("humanTaskId", humanTaskId);
model.addAttribute("humanTask", humanTaskDto);
if (humanTaskDto.getParentId() != null) {
model.addAttribute("parentHumanTask", humanTaskConnector.findHumanTask(humanTaskDto.getParentId()));
}
// 表�和数�
if ((humanTaskId != null) && (!"".equals(humanTaskId))) {
// 如果是任务�稿,直接通过processInstanceId获得record,更新数�
// TODO: 分支肯定有问题
String processInstanceId = humanTaskDto.getProcessInstanceId();
String json = this.findTaskFormData(processInstanceId);
if (json != null) {
model.addAttribute("json", json);
}
Record record = keyValueConnector.findByRef(processInstanceId);
Xform xform = new XformBuilder().setStoreConnector(storeConnector).setUserConnector(userConnector).setContent(formDto.getContent()).setRecord(record).build();
model.addAttribute("xform", xform);
}
// �作
List<ButtonDTO> buttons = new ArrayList<ButtonDTO>();
for (String button : formDto.getButtons()) {
buttons.add(buttonHelper.findButton(button.trim()));
}
if (buttons.isEmpty()) {
buttons.add(buttonHelper.findButton("saveDraft"));
buttons.add(buttonHelper.findButton("completeTask"));
}
model.addAttribute("buttons", buttons);
// 沟通
List<HumanTaskDTO> children = humanTaskConnector.findSubTasks(humanTaskId);
model.addAttribute("children", children);
// 审批记录
List<HumanTaskDTO> logHumanTaskDtos = humanTaskConnector.findHumanTasksByProcessInstanceId(humanTaskDto.getProcessInstanceId());
model.addAttribute("logHumanTaskDtos", logHumanTaskDtos);
return "operation/task-operation-viewTaskForm";
}Example 4
| Project: mateo-master File: EntradaController.java View source code |
@Transactional
@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Entrada entrada, BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
for (String nombre : request.getParameterMap().keySet()) {
log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
}
if (bindingResult.hasErrors()) {
log.debug("Hubo algun error en la forma, regresando");
return "inventario/entrada/nueva";
}
if (entrada.getProveedor() == null || entrada.getProveedor().getId() == null) {
log.warn("No introdujo un proveedor correcto, regresando");
errors.rejectValue("proveedor", "entrada.no.eligio.proveedor.message", null, null);
return "inventario/entrada/nueva";
}
try {
Usuario usuario = ambiente.obtieneUsuario();
if (request.getParameter("proveedor.id") == null) {
log.warn("No se puede crear la entrada si no ha seleccionado un proveedor");
errors.rejectValue("proveedor", "entrada.sin.proveedor.message");
return "inventario/entrada/nueva";
}
Proveedor proveedor = proveedorDao.obtiene(new Long(request.getParameter("proveedor.id")));
entrada.setProveedor(proveedor);
entrada = entradaDao.crea(entrada, usuario);
} catch (ConstraintViolationException e) {
log.error("No se pudo crear la entrada", e);
errors.rejectValue("factura", "campo.duplicado.message", new String[] { "factura" }, null);
return "inventario/entrada/nueva";
}
redirectAttributes.addFlashAttribute("message", "entrada.creada.message");
redirectAttributes.addFlashAttribute("messageAttrs", new String[] { entrada.getFolio() });
return "redirect:/inventario/entrada/ver/" + entrada.getId();
}Example 5
| Project: Punisher-master File: SignupController.java View source code |
@RequestMapping(value = "signup", method = RequestMethod.POST)
public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors, RedirectAttributes ra) {
if (errors.hasErrors()) {
return SIGNUP_VIEW_NAME;
}
Account account = accountRepository.save(signupForm.createAccount());
userService.signin(account);
// see /WEB-INF/i18n/messages.properties and /WEB-INF/views/homeSignedIn.html
MessageHelper.addSuccessAttribute(ra, "signup.success");
return "redirect:/";
}Example 6
| Project: The-Punisher-master File: SignupController.java View source code |
@RequestMapping(value = "signup", method = RequestMethod.POST)
public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors, RedirectAttributes ra) {
if (errors.hasErrors()) {
return SIGNUP_VIEW_NAME;
}
Account account = accountRepository.save(signupForm.createAccount());
userService.signin(account);
// see /WEB-INF/i18n/messages.properties and /WEB-INF/views/homeSignedIn.html
MessageHelper.addSuccessAttribute(ra, "signup.success");
return "redirect:/";
}Example 7
| Project: Estudo-Spring-master File: UsuarioController.java View source code |
@RequestMapping(value = "/", method = RequestMethod.POST)
public String salvar(Usuario usuario, BindingResult erros, Model model, RedirectAttributes redirect) {
String password = usuario.getPassword();
String encodePassword = usuario.getEncodePassword(password);
usuario.setPassword(encodePassword);
usuario.addPermissao(getPermissao());
redirect.addFlashAttribute("mensagem", "Usuário criado com sucesso");
usuarioRepository.save(usuario);
return "redirect:/login";
}Example 8
| Project: git-java-practice-master File: CheckoutController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public String doCheckout(@Valid @ModelAttribute("customerInfo") CustomerInfo customer, BindingResult result, RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
// show the checkout form again
return "/checkout";
}
LOG.debug("No errors, continue with processing for Customer {}:", customer.getName());
OrderDetails order = basket.createOrderDetailsWithCustomerInfo(customer);
OrderCreatedEvent event = orderService.createOrder(new CreateOrderEvent(order));
UUID key = event.getNewOrderKey();
redirectAttrs.addFlashAttribute("message", "Your order has been accepted!");
basket.clear();
LOG.debug("Basket now has {} items", basket.getSize());
return "redirect:/order/" + key.toString();
}Example 9
| Project: glados-wiki-master File: FlashAlerts.java View source code |
public void add(RedirectAttributes redirectAttributes, FlashAlert flashAlert) {
if (!redirectAttributes.containsAttribute(FLASHMAP_KEY)) {
redirectAttributes.addFlashAttribute(FLASHMAP_KEY, new ArrayList<FlashAlert>());
}
//
List<FlashAlert> flashAlerts = (List<FlashAlert>) redirectAttributes.getFlashAttributes().get(FLASHMAP_KEY);
flashAlerts.add(flashAlert);
redirectAttributes.addFlashAttribute(FLASHMAP_KEY, flashAlerts);
}Example 10
| Project: jgt-master File: TaskController.java View source code |
@RequiresPermissions(value = { "task:create", "mytask:create" }, logical = Logical.OR)
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(Task task, @RequestParam("type") String type, RedirectAttributes redirectAttributes) {
if ("2".equals(type)) {
task.setUserId(Functions.getCurrentUserId());
}
taskService.createTask(task);
redirectAttributes.addFlashAttribute("msg", "新增�功");
if ("2".equals(type)) {
return "redirect:/task/my";
} else {
return "redirect:/task";
}
}Example 11
| Project: jspxcms304-master File: WebFileController.java View source code |
@RequiresPermissions("core:web_file:mkdir")
@RequestMapping(value = "mkdir.do", method = RequestMethod.POST)
public String mkdir(String parentId, String dir, HttpServletRequest request, HttpServletResponse response, RedirectAttributes ra) throws IOException {
Site site = Context.getCurrentSite(request);
String base = site.getFilesBasePath("");
if (StringUtils.isBlank(parentId)) {
parentId = base;
}
File parent = new File(pathResolver.getPath(parentId));
File newDir = new File(parent, dir);
if (!hasPermission(newDir, site)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
}
boolean isSuccess = newDir.mkdir();
ra.addFlashAttribute("refreshLeft", true);
ra.addAttribute("parentId", parentId);
ra.addFlashAttribute(MESSAGE, isSuccess ? OPERATION_SUCCESS : OPERATION_FAILURE);
return "redirect:list.do";
}Example 12
| Project: LearningCommunity-master File: UserController.java View source code |
@RequestMapping(value = "/completeInfo", method = RequestMethod.POST)
public String complete(Model model, HttpSession session, String gender, MultipartFile avatar, String motto, String city, RedirectAttributes redirectAttributes) {
User user = (User) session.getAttribute("loginUser");
String avatarPath = "/opt/LearningCommunity/avatar";
String avatarUrl = MultipartFileUtils.saveFile(avatar, avatarPath);
userDao.update(user.getUserId(), gender, avatarUrl, motto, city);
redirectAttributes.addFlashAttribute("userMsg", "信�完善�功");
return "redirect:/course/courses";
}Example 13
| Project: okmakeover-master File: SampleController.java View source code |
/**
* Sample 등� By Form Submit
* @param categoryId
* @param sample
* @param authentication
* @return
*/
@Secured("ROLE_USER")
@RequestMapping(value = "/{categoryId}", method = RequestMethod.POST)
public String createByForm(@PathVariable int categoryId, Sample sample, Authentication authentication, Model model, RedirectAttributes redirectAttributes) {
Result result = this.create(categoryId, sample, authentication);
if (result.isSuccess()) {
redirectAttributes.addFlashAttribute("result", result);
return "redirect:/sample/" + categoryId;
} else {
model.addAttribute("result", result);
return "sample/sample_create";
}
}Example 14
| Project: quadriga-master File: ArchiveWSController.java View source code |
/**
* This calls the workspace manager to archive the workspace
* It takes workspaceId and projectId as parameters
* @param workspaceId
* @param principal
* @param redirectAttributes
* @param model
* @return view
* @throws QuadrigaStorageException
* @throws QuadrigaAccessException
*/
@AccessPolicies({ @ElementAccessPolicy(type = CheckedElementType.PROJECT, paramIndex = 2, userRole = { RoleNames.ROLE_COLLABORATOR_OWNER, RoleNames.ROLE_PROJ_COLLABORATOR_ADMIN, RoleNames.ROLE_PROJ_COLLABORATOR_CONTRIBUTOR }), @ElementAccessPolicy(type = CheckedElementType.WORKSPACE, paramIndex = 0, userRole = {}) })
@RequestMapping(value = "auth/workbench/{projectId}/archiveworkspace/{workspaceId}", method = RequestMethod.GET)
public String archiveWorkspace(@PathVariable("workspaceId") String workspaceId, @PathVariable("projectId") String projectId, Principal principal, RedirectAttributes redirectAttributes) throws QuadrigaStorageException, QuadrigaAccessException {
// archive the workspace
archiveWSManager.archiveWorkspace(workspaceId, principal.getName());
// add redirect attributes
redirectAttributes.addFlashAttribute("show_success_alert", true);
redirectAttributes.addFlashAttribute("success_alert_msg", "The workspace has been successfully archived.");
return "redirect:/auth/workbench/workspace/" + workspaceId;
}Example 15
| Project: shopb2b-master File: OrderController.java View source code |
@RequestMapping(value = { "/confirm" }, method = RequestMethod.POST)
public String confirm(Long id, RedirectAttributes redirectAttributes) {
Order order = (Order) this.orderService.find(id);
Admin operator = this.adminService.getCurrent();
if ((order != null) && (!order.isExpired()) && (order.getOrderStatus() == Order.OrderStatus.unconfirmed) && (!order.isLocked(operator))) {
this.orderService.confirm(order, operator);
addMessage(redirectAttributes, ADMIN_SUCCESS);
} else {
addMessage(redirectAttributes, Message.warn("admin.common.invalid", new Object[0]));
}
return "redirect:view.jhtml?id=" + id;
}Example 16
| Project: spring-mvc-showcase-master File: FormController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@Valid FormBean formBean, BindingResult result, @ModelAttribute("ajaxRequest") boolean ajaxRequest, Model model, RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
return null;
}
// Typically you would save to a db and clear the "form" attribute from the session
// via SessionStatus.setCompleted(). For the demo we leave it in the session.
String message = "Form submitted successfully. Bound " + formBean;
// Success response handling
if (ajaxRequest) {
// prepare model for rendering success message in this request
model.addAttribute("message", message);
return null;
} else {
// store a success message for rendering on the next request after redirect
// redirect back to the form to render the success message along with newly bound values
redirectAttrs.addFlashAttribute("message", message);
return "redirect:/form";
}
}Example 17
| Project: spring-security-javaconfig-master File: MessageController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
if (result.hasErrors()) {
return new ModelAndView("messages/compose");
}
message = messageRepository.save(message);
redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
}Example 18
| Project: SpringBlog-master File: UserController.java View source code |
@RequestMapping(value = "{userId:[0-9]+}", method = POST)
public String update(@PathVariable Long userId, @Valid UserForm userForm, Errors errors, RedirectAttributes ra) {
User user = userRepository.findOne(userId);
Assert.notNull(user);
if (errors.hasErrors()) {
return "admin/users/profile";
}
if (!userForm.getNewPassword().isEmpty()) {
if (!userService.changePassword(user, userForm.getPassword(), userForm.getNewPassword()))
MessageHelper.addErrorAttribute(ra, "Change password failed.");
else
MessageHelper.addSuccessAttribute(ra, "Change password successfully.");
}
return "redirect:profile";
}Example 19
| Project: thymeleafexamples-layouts-master File: SignupController.java View source code |
@PostMapping("signup")
public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors, RedirectAttributes ra) {
if (errors.hasErrors()) {
return SIGNUP_VIEW_NAME;
}
Account account = accountService.save(signupForm.createAccount());
accountService.signin(account);
// see /WEB-INF/i18n/messages.properties and /WEB-INF/views/homeSignedIn.html
MessageHelper.addSuccessAttribute(ra, "signup.success");
return "redirect:/";
}Example 20
| Project: urlaubsverwaltung-master File: ApplicationForLeaveDetailsController.java View source code |
/**
* Allow a not yet allowed application for leave (Privileged user only!).
*/
@PreAuthorize(SecurityRules.IS_BOSS_OR_DEPARTMENT_HEAD_OR_SECOND_STAGE_AUTHORITY)
@RequestMapping(value = "/{applicationId}/allow", method = RequestMethod.POST)
public String allowApplication(@PathVariable("applicationId") Integer applicationId, @ModelAttribute("comment") ApplicationCommentForm comment, @RequestParam(value = "redirect", required = false) String redirectUrl, Errors errors, RedirectAttributes redirectAttributes) throws UnknownApplicationForLeaveException, AccessDeniedException {
Application application = applicationService.getApplicationById(applicationId).orElseThrow(() -> new UnknownApplicationForLeaveException(applicationId));
Person signedInUser = sessionService.getSignedInUser();
Person person = application.getPerson();
boolean isBoss = signedInUser.hasRole(Role.BOSS);
boolean isDepartmentHead = signedInUser.hasRole(Role.DEPARTMENT_HEAD) && departmentService.isDepartmentHeadOfPerson(signedInUser, person);
boolean isSecondStageAuthority = signedInUser.hasRole(Role.SECOND_STAGE_AUTHORITY) && departmentService.isSecondStageAuthorityOfPerson(signedInUser, person);
if (!isBoss && !isDepartmentHead && !isSecondStageAuthority) {
throw new AccessDeniedException(String.format("User '%s' has not the correct permissions to allow application for leave of user '%s'", signedInUser.getLoginName(), person.getLoginName()));
}
comment.setMandatory(false);
commentValidator.validate(comment, errors);
if (errors.hasErrors()) {
redirectAttributes.addFlashAttribute(ControllerConstants.ERRORS_ATTRIBUTE, errors);
return "redirect:/web/application/" + applicationId + "?action=allow";
}
Application allowedApplicationForLeave = applicationInteractionService.allow(application, signedInUser, Optional.ofNullable(comment.getText()));
if (allowedApplicationForLeave.hasStatus(ApplicationStatus.ALLOWED)) {
redirectAttributes.addFlashAttribute("allowSuccess", true);
} else if (allowedApplicationForLeave.hasStatus(ApplicationStatus.TEMPORARY_ALLOWED)) {
redirectAttributes.addFlashAttribute("temporaryAllowSuccess", true);
}
if (redirectUrl != null) {
return "redirect:" + redirectUrl;
}
return "redirect:/web/application/" + applicationId;
}Example 21
| Project: YummyNoodleBar-master File: CheckoutController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public String doCheckout(@Valid @ModelAttribute("customerInfo") CustomerInfo customer, BindingResult result, RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
// show the checkout form again
return "/checkout";
}
LOG.debug("No errors, continue with processing for Customer {}:", customer.getName());
OrderDetails order = basket.createOrderDetailsWithCustomerInfo(customer);
OrderCreatedEvent event = orderService.createOrder(new CreateOrderEvent(order));
UUID key = event.getNewOrderKey();
redirectAttrs.addFlashAttribute("message", "Your order has been accepted!");
basket.clear();
LOG.debug("Basket now has {} items", basket.getSize());
return "redirect:/order/" + key.toString();
}Example 22
| Project: alf.io-master File: ReservationController.java View source code |
@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}", method = RequestMethod.POST)
public String handleReservation(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, PaymentForm paymentForm, BindingResult bindingResult, Model model, HttpServletRequest request, Locale locale, RedirectAttributes redirectAttributes) {
Optional<Event> eventOptional = eventRepository.findOptionalByShortName(eventName);
if (!eventOptional.isPresent()) {
return "redirect:/";
}
Event event = eventOptional.get();
Optional<TicketReservation> ticketReservation = ticketReservationManager.findById(reservationId);
if (!ticketReservation.isPresent()) {
return redirectReservation(ticketReservation, eventName, reservationId);
}
if (paymentForm.shouldCancelReservation()) {
ticketReservationManager.cancelPendingReservation(reservationId, false);
SessionUtil.removeSpecialPriceData(request);
return "redirect:/event/" + eventName + "/";
}
if (!ticketReservation.get().getValidity().after(new Date())) {
bindingResult.reject(ErrorsCode.STEP_2_ORDER_EXPIRED);
}
final TotalPrice reservationCost = ticketReservationManager.totalReservationCostWithVAT(reservationId);
if (!paymentForm.isPostponeAssignment() && !ticketRepository.checkTicketUUIDs(reservationId, paymentForm.getTickets().keySet())) {
bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA);
}
paymentForm.validate(bindingResult, reservationCost, event, ticketFieldRepository.findAdditionalFieldsForEvent(event.getId()));
if (bindingResult.hasErrors()) {
SessionUtil.addToFlash(bindingResult, redirectAttributes);
return redirectReservation(ticketReservation, eventName, reservationId);
}
CustomerName customerName = new CustomerName(paymentForm.getFullName(), paymentForm.getFirstName(), paymentForm.getLastName(), event);
//handle paypal redirect!
if (paymentForm.getPaymentMethod() == PaymentProxy.PAYPAL && !paymentForm.hasPaypalTokens()) {
OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, event, locale);
try {
String checkoutUrl = paymentManager.createPaypalCheckoutRequest(event, reservationId, orderSummary, customerName, paymentForm.getEmail(), paymentForm.getBillingAddress(), locale, paymentForm.isPostponeAssignment());
assignTickets(eventName, reservationId, paymentForm, bindingResult, request, true);
return "redirect:" + checkoutUrl;
} catch (Exception e) {
bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_REQUEST_CREATION);
SessionUtil.addToFlash(bindingResult, redirectAttributes);
return redirectReservation(ticketReservation, eventName, reservationId);
}
}
//
final PaymentResult status = ticketReservationManager.confirm(paymentForm.getToken(), paymentForm.getPaypalPayerID(), event, reservationId, paymentForm.getEmail(), customerName, locale, paymentForm.getBillingAddress(), reservationCost, SessionUtil.retrieveSpecialPriceSessionId(request), Optional.ofNullable(paymentForm.getPaymentMethod()));
if (!status.isSuccessful()) {
String errorMessageCode = status.getErrorCode().get();
MessageSourceResolvable message = new DefaultMessageSourceResolvable(new String[] { errorMessageCode, StripeManager.STRIPE_UNEXPECTED });
bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_PROCESSING_ERROR, new Object[] { messageSource.getMessage(message, locale) }, null);
SessionUtil.addToFlash(bindingResult, redirectAttributes);
return redirectReservation(ticketReservation, eventName, reservationId);
}
//
TicketReservation reservation = ticketReservationManager.findById(reservationId).orElseThrow(IllegalStateException::new);
sendReservationCompleteEmail(request, event, reservation);
sendReservationCompleteEmailToOrganizer(request, event, reservation);
if (paymentForm.getPaymentMethod() != PaymentProxy.PAYPAL) {
assignTickets(eventName, reservationId, paymentForm, bindingResult, request, paymentForm.getPaymentMethod() == PaymentProxy.OFFLINE);
}
return "redirect:/event/" + eventName + "/reservation/" + reservationId + "/success";
}Example 23
| Project: Broadleaf-eCommerce-master File: AdminBasicEntityController.java View source code |
/**
* Builds JSON that looks like this:
*
* {"errors":
* [{"message":"This field is Required",
* "code": "requiredValidationFailure"
* "field":"defaultSku--name",
* "errorType", "field",
* "tab": "General"
* },
* {"message":"This field is Required",
* "code": "requiredValidationFailure"
* "field":"defaultSku--name",
* "errorType", "field",
* "tab": "General"
* }]
* }
*
*/
@RequestMapping(value = "/{id}", method = RequestMethod.POST, produces = "application/json")
public String saveEntityJson(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable Map<String, String> pathVars, @PathVariable(value = "id") String id, @ModelAttribute(value = "entityForm") EntityForm entityForm, BindingResult result, RedirectAttributes ra) throws Exception {
saveEntity(request, response, model, pathVars, id, entityForm, result, ra);
JsonResponse json = new JsonResponse(response);
if (result.hasErrors()) {
populateJsonValidationErrors(entityForm, result, json);
}
List<String> dirtyList = buildDirtyList(pathVars, request, id);
if (CollectionUtils.isNotEmpty(dirtyList)) {
json.with("dirty", dirtyList);
}
return json.done();
}Example 24
| Project: BroadleafCommerce-master File: AdminBasicEntityController.java View source code |
/**
* Builds JSON that looks like this:
*
* {"errors":
* [{"message":"This field is Required",
* "code": "requiredValidationFailure"
* "field":"defaultSku--name",
* "errorType", "field",
* "tab": "General"
* },
* {"message":"This field is Required",
* "code": "requiredValidationFailure"
* "field":"defaultSku--name",
* "errorType", "field",
* "tab": "General"
* }]
* }
*
*/
@RequestMapping(value = "/{id}", method = RequestMethod.POST, produces = "application/json")
public String saveEntityJson(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable Map<String, String> pathVars, @PathVariable(value = "id") String id, @ModelAttribute(value = "entityForm") EntityForm entityForm, BindingResult result, RedirectAttributes ra) throws Exception {
saveEntity(request, response, model, pathVars, id, entityForm, result, ra);
JsonResponse json = new JsonResponse(response);
if (result.hasErrors()) {
populateJsonValidationErrors(entityForm, result, json);
}
List<String> dirtyList = buildDirtyList(pathVars, request, id);
if (CollectionUtils.isNotEmpty(dirtyList)) {
json.with("dirty", dirtyList);
}
return json.done();
}Example 25
| Project: commerce-master File: AdminBasicEntityController.java View source code |
/**
* Builds JSON that looks like this:
*
* {"errors":
* [{"message":"This field is Required",
* "code": "requiredValidationFailure"
* "field":"defaultSku--name",
* "errorType", "field",
* "tab": "General"
* },
* {"message":"This field is Required",
* "code": "requiredValidationFailure"
* "field":"defaultSku--name",
* "errorType", "field",
* "tab": "General"
* }]
* }
*
*/
@RequestMapping(value = "/{id}", method = RequestMethod.POST, produces = "application/json")
public String saveEntityJson(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable Map<String, String> pathVars, @PathVariable(value = "id") String id, @ModelAttribute(value = "entityForm") EntityForm entityForm, BindingResult result, RedirectAttributes ra) throws Exception {
saveEntity(request, response, model, pathVars, id, entityForm, result, ra);
JsonResponse json = new JsonResponse(response);
if (result.hasErrors()) {
populateJsonValidationErrors(entityForm, result, json);
}
List<String> dirtyList = buildDirtyList(pathVars, request, id);
if (CollectionUtils.isNotEmpty(dirtyList)) {
json.with("dirty", dirtyList);
}
return json.done();
}Example 26
| Project: comsat-master File: FiberRequestMappingHandlerAdapter.java View source code |
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;
}Example 27
| Project: eGov-master File: UpdateConnectionController.java View source code |
@RequestMapping(value = "/update/{applicationNumber}", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute WaterConnectionDetails waterConnectionDetails, final BindingResult resultBinder, final RedirectAttributes redirectAttributes, final HttpServletRequest request, final Model model, @RequestParam("files") final MultipartFile[] files) {
String mode = "";
String workFlowAction = "";
String sourceChannel = request.getParameter("Source");
if (request.getParameter("mode") != null)
mode = request.getParameter("mode");
if (request.getParameter("workFlowAction") != null)
workFlowAction = request.getParameter("workFlowAction");
request.getSession().setAttribute(WaterTaxConstants.WORKFLOW_ACTION, workFlowAction);
// For Submit Button
if (waterConnectionDetails.getStatus().getCode().equalsIgnoreCase(WaterTaxConstants.APPLICATION_STATUS_CREATED) && mode.equalsIgnoreCase("fieldInspection"))
if (workFlowAction.equalsIgnoreCase(WaterTaxConstants.SUBMITWORKFLOWACTION)) {
final ConnectionCategory connectionCategory = connectionCategoryService.findOne(waterConnectionDetails.getCategory().getId());
if (connectionCategory != null && !connectionCategory.getCode().equalsIgnoreCase(WaterTaxConstants.CATEGORY_BPL) && waterConnectionDetails.getBplCardHolderName() != null)
waterConnectionDetails.setBplCardHolderName(null);
populateEstimationDetails(waterConnectionDetails);
WaterDemandConnection waterDemandConnection = waterTaxUtils.getCurrentDemand(waterConnectionDetails);
waterDemandConnection.setDemand(connectionDemandService.createDemand(waterConnectionDetails));
waterDemandConnection.setWaterConnectionDetails(waterConnectionDetails);
waterConnectionDetails.addWaterDemandConnection(waterDemandConnection);
waterDemandConnectionService.createWaterDemandConnection(waterDemandConnection);
waterConnectionDetailsService.save(waterConnectionDetails);
waterConnectionDetailsService.getCurrentSession().flush();
// Attach any other file during field inspection and estimation
final Set<FileStoreMapper> fileStoreSet = addToFileStore(files);
Iterator<FileStoreMapper> fsIterator = null;
if (fileStoreSet != null && !fileStoreSet.isEmpty())
fsIterator = fileStoreSet.iterator();
if (fsIterator != null && fsIterator.hasNext())
waterConnectionDetails.setFileStore(fsIterator.next());
} else if (workFlowAction.equalsIgnoreCase(WaterTaxConstants.WFLOW_ACTION_STEP_REJECT)) {
waterConnectionDetailsService.getCurrentSession().evict(waterConnectionDetails);
waterConnectionDetails = waterConnectionDetailsService.findBy(waterConnectionDetails.getId());
}
Long approvalPosition = 0l;
String approvalComent = "";
if (request.getParameter("approvalComent") != null)
approvalComent = request.getParameter("approvalComent");
if (workFlowAction != null && workFlowAction.equals(WaterTaxConstants.APPROVEWORKFLOWACTION) && waterConnectionDetails.getStatus() != null && waterConnectionDetails.getStatus().getCode() != null && waterConnectionDetails.getStatus().getCode().equals(WaterTaxConstants.APPLICATION_STATUS_FEEPAID))
validateSanctionDetails(waterConnectionDetails, resultBinder);
if (request.getParameter("approvalPosition") != null && !request.getParameter("approvalPosition").isEmpty())
approvalPosition = Long.valueOf(request.getParameter("approvalPosition"));
// For Get Configured ApprovalPosition from workflow history
if (approvalPosition == null || approvalPosition.equals(Long.valueOf(0)))
if (waterConnectionDetails.getCloseConnectionType() != null)
approvalPosition = waterConnectionDetailsService.getApprovalPositionByMatrixDesignation(waterConnectionDetails, approvalPosition, request.getParameter("additionalRule"), mode, workFlowAction);
else
approvalPosition = waterConnectionDetailsService.getApprovalPositionByMatrixDesignation(waterConnectionDetails, approvalPosition, waterConnectionDetails.getApplicationType().getCode(), mode, workFlowAction);
// to get modes to hide and show details in every user inbox
request.getSession().setAttribute("APPROVAL_POSITION", approvalPosition);
appendModeBasedOnApplicationCreator(model, request, waterConnectionDetails);
if ((approvalPosition == null || approvalPosition.equals(Long.valueOf(0))) && request.getParameter("approvalPosition") != null && !request.getParameter("approvalPosition").isEmpty())
approvalPosition = Long.valueOf(request.getParameter("approvalPosition"));
if (!resultBinder.hasErrors()) {
try {
// For Closure Connection
if (waterConnectionDetails.getCloseConnectionType() != null)
if (waterConnectionDetails.getCloseConnectionType().equals(WaterTaxConstants.PERMENENTCLOSECODE))
waterConnectionDetails.setCloseConnectionType(ClosureType.Permanent.getName());
else
waterConnectionDetails.setCloseConnectionType(ClosureType.Temporary.getName());
if (null != workFlowAction)
if (workFlowAction.equalsIgnoreCase(WaterTaxConstants.PREVIEWWORKFLOWACTION) && (waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.NEWCONNECTION) || waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.ADDNLCONNECTION) || waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.CHANGEOFUSE)))
return "redirect:/application/workorder?pathVar=" + waterConnectionDetails.getApplicationNumber();
else if (workFlowAction.equalsIgnoreCase(WaterTaxConstants.PREVIEWWORKFLOWACTION) && waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.CLOSINGCONNECTION))
return "redirect:/application/acknowlgementNotice?pathVar=" + waterConnectionDetails.getApplicationNumber();
else if (workFlowAction.equalsIgnoreCase(WaterTaxConstants.PREVIEWWORKFLOWACTION) && waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.RECONNECTIONCONNECTION))
return "redirect:/application/ReconnacknowlgementNotice?pathVar=" + waterConnectionDetails.getApplicationNumber();
else if (workFlowAction.equals(WaterTaxConstants.SIGNWORKFLOWACTION)) {
// Sign
WaterConnectionDetails upadtedWaterConnectionDetails = null;
WorkOrderNumberGenerator workOrderGen = beanResolver.getAutoNumberServiceFor(WorkOrderNumberGenerator.class);
if (waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.NEWCONNECTION) || waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.ADDNLCONNECTION) || waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.CHANGEOFUSE)) {
waterConnectionDetails.setWorkOrderDate(new Date());
waterConnectionDetails.setWorkOrderNumber(workOrderGen.generateWorkOrderNumber());
}
final String cityMunicipalityName = (String) request.getSession().getAttribute("citymunicipalityname");
final String districtName = (String) request.getSession().getAttribute("districtName");
ReportOutput reportOutput = null;
reportOutput = getReportOutputObject(waterConnectionDetails, workFlowAction, cityMunicipalityName, districtName);
// the document
if (reportOutput != null) {
String fileName = "";
if (waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.CLOSINGCONNECTION)) {
fileName = WaterTaxConstants.SIGNED_DOCUMENT_PREFIX + waterConnectionDetails.getApplicationNumber() + ".pdf";
} else if (waterConnectionDetails.getApplicationType().getCode().equals(WaterTaxConstants.RECONNECTIONCONNECTION)) {
fileName = WaterTaxConstants.SIGNED_DOCUMENT_PREFIX + waterConnectionDetails.getApplicationNumber() + ".pdf";
} else {
fileName = WaterTaxConstants.SIGNED_DOCUMENT_PREFIX + waterConnectionDetails.getWorkOrderNumber() + ".pdf";
}
final InputStream fileStream = new ByteArrayInputStream(reportOutput.getReportOutputData());
final FileStoreMapper fileStore = fileStoreService.store(fileStream, fileName, "application/pdf", WaterTaxConstants.FILESTORE_MODULECODE);
waterConnectionDetails.setFileStore(fileStore);
upadtedWaterConnectionDetails = waterConnectionDetailsService.updateWaterConnectionDetailsWithFileStore(waterConnectionDetails);
}
model.addAttribute("fileStoreIds", upadtedWaterConnectionDetails.getFileStore().getFileStoreId());
model.addAttribute("ulbCode", ApplicationThreadLocals.getCityCode());
final HttpSession session = request.getSession();
session.setAttribute(WaterTaxConstants.MODE, mode);
session.setAttribute(WaterTaxConstants.APPROVAL_POSITION, approvalPosition);
session.setAttribute(WaterTaxConstants.APPROVAL_COMMENT, approvalComent);
session.setAttribute(WaterTaxConstants.APPLICATION_NUMBER, upadtedWaterConnectionDetails.getApplicationNumber());
final Map<String, String> fileStoreIdsApplicationNoMap = new HashMap<String, String>();
fileStoreIdsApplicationNoMap.put(upadtedWaterConnectionDetails.getFileStore().getFileStoreId(), upadtedWaterConnectionDetails.getApplicationNumber());
session.setAttribute(WaterTaxConstants.FILE_STORE_ID_APPLICATION_NUMBER, fileStoreIdsApplicationNoMap);
model.addAttribute("isDigitalSignatureEnabled", waterTaxUtils.isDigitalSignatureEnabled());
return "newConnection-digitalSignatureRedirection";
} else
waterConnectionDetailsService.updateWaterConnection(waterConnectionDetails, approvalPosition, approvalComent, waterConnectionDetails.getApplicationType().getCode(), workFlowAction, mode, null, sourceChannel);
} catch (final ValidationException e) {
throw new ValidationException(e.getMessage());
}
if (workFlowAction != null && !workFlowAction.isEmpty() && // Generate
workFlowAction.equalsIgnoreCase(WaterTaxConstants.WF_ESTIMATION_NOTICE_BUTTON))
// Button
return "redirect:/application/estimationNotice?pathVar=" + waterConnectionDetails.getApplicationNumber();
if (null != workFlowAction && !workFlowAction.isEmpty() && // For
workFlowAction.equalsIgnoreCase(WaterTaxConstants.WF_WORKORDER_BUTTON))
// WorkOrder
return "redirect:/application/workorder?pathVar=" + waterConnectionDetails.getApplicationNumber();
if (workFlowAction != null && !workFlowAction.isEmpty() && // For
workFlowAction.equalsIgnoreCase(WaterTaxConstants.WF_CLOSERACKNOWLDGEENT_BUTTON))
// Acknowlegement
return "redirect:/application/acknowlgementNotice?pathVar=" + waterConnectionDetails.getApplicationNumber();
if (workFlowAction != null && !workFlowAction.isEmpty() && // For
workFlowAction.equalsIgnoreCase(WaterTaxConstants.WF_RECONNECTIONACKNOWLDGEENT_BUTTON))
// Ack
return "redirect:/application/ReconnacknowlgementNotice?pathVar=" + waterConnectionDetails.getApplicationNumber();
// For ReConnection and Closure Connection
if ((workFlowAction.equals(WaterTaxConstants.WFLOW_ACTION_STEP_REJECT) || workFlowAction.equalsIgnoreCase(WaterTaxConstants.WF_RECONNECTIONACKNOWLDGEENT_BUTTON)) && (waterConnectionDetails.getStatus().getCode().equals(WaterTaxConstants.WORKFLOW_RECONNCTIONINITIATED) || waterConnectionDetails.getStatus().getCode().equals(WaterTaxConstants.APPLICATION_STATUS__RECONNCTIONINPROGRESS) || waterConnectionDetails.getStatus().getCode().equals(WaterTaxConstants.APPLICATION_STATUS_CLOSERINPROGRESS) || waterConnectionDetails.getStatus().getCode().equals(WaterTaxConstants.APPLICATION_STATUS_CLOSERINITIATED)))
approvalPosition = waterTaxUtils.getApproverPosition(WaterTaxConstants.ROLE_CLERKFORADONI, waterConnectionDetails);
final Assignment currentUserAssignment = assignmentService.getPrimaryAssignmentForGivenRange(securityUtils.getCurrentUser().getId(), new Date(), new Date());
String nextDesign = "";
Assignment assignObj = null;
List<Assignment> asignList = null;
if (approvalPosition != null)
assignObj = assignmentService.getPrimaryAssignmentForPositon(approvalPosition);
if (assignObj != null) {
asignList = new ArrayList<Assignment>();
asignList.add(assignObj);
} else if (assignObj == null && approvalPosition != null)
asignList = assignmentService.getAssignmentsForPosition(approvalPosition, new Date());
nextDesign = !asignList.isEmpty() ? asignList.get(0).getDesignation().getName() : "";
final String pathVars = waterConnectionDetails.getApplicationNumber() + "," + waterTaxUtils.getApproverName(approvalPosition) + "," + (currentUserAssignment != null ? currentUserAssignment.getDesignation().getName() : "") + "," + (nextDesign != null ? nextDesign : "");
return "redirect:/application/application-success?pathVars=" + pathVars;
} else {
if (waterConnectionDetails.getStatus().getCode().equalsIgnoreCase(WaterTaxConstants.APPLICATION_STATUS_WOGENERATED))
model.addAttribute("meterFocus", true);
return loadViewData(model, request, waterConnectionDetails);
}
}Example 28
| Project: enhanced-pet-clinic-master File: MessageController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
if (result.hasErrors()) {
return new ModelAndView("messages/messageForm", "formErrors", result.getAllErrors());
}
message = this.messageRepository.save(message);
redirect.addFlashAttribute("statusMessage", "Successfully created a new message");
return new ModelAndView("redirect:/messages/{message.id}", "message.id", message.getId());
}Example 29
| Project: gs-spring-security-3.2-master File: MessageController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid MessageForm messageForm, BindingResult result, RedirectAttributes redirect) {
User to = userRepository.findByEmail(messageForm.getToEmail());
if (to == null) {
result.rejectValue("toEmail", "toEmail", "User not found");
}
if (result.hasErrors()) {
return new ModelAndView("messages/compose");
}
Message message = new Message();
message.setSummary(messageForm.getSummary());
message.setText(messageForm.getText());
message.setTo(to);
message = messageRepository.save(message);
redirect.addFlashAttribute("globalMessage", "Message added successfully");
return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
}Example 30
| Project: jblog-master File: PubController.java View source code |
/**
* 找回密ç ?
* @param req
* @param rep
* @param u 用户Id
* @param key token key
* @param vcode 验è¯?ç ?
* @param password1 新密ç ?确认密ç ?
* @param password2
* @return
*/
@RequestMapping("/findpass.do")
public ModelAndView findpass(HttpServletRequest req, HttpServletResponse rep, String u, String key, String vcode, String password1, String password2, RedirectAttributes attr) {
ModelAndView mav = new ModelAndView("/admin/pub/findpass");
String msg_50X = "授æ?ƒç ?过期或者é?žæ³•æ“?作!";
try {
boolean isok = user_serv.canFindPass(u, key);
if (null == vcode || vcode.isEmpty()) {
//点邮件过�或者直接�法访问的
if (isok) {
mav.addObject("key", key);
mav.addObject("u", u);
} else {
rep.sendError(500, msg_50X);
}
} else {
//æ??交过æ?¥çš„
if (null == vcode || !vcode.equals(req.getSession().getAttribute("vcode"))) {
mav.addObject("msg", "验è¯?ç ?错误");
} else if (!isok) {
mav.addObject("msg", msg_50X);
} else if (!password1.equals(password2)) {
mav.addObject("msg", "两次密ç ?ä¸?一致!");
} else {
UserVo vo = user_serv.resetPass(password1, u);
user_serv.userLogin(vo.getUserName(), vo.getUserPsw(), false, req, rep);
rep.sendRedirect(String.format("http://%s/admin/main.do", user_serv.getHost()));
}
}
} catch (Exception e) {
e.printStackTrace();
mav.addObject("msg", "系统出错!");
log.error("找回密ç ?", e);
}
return mav;
}Example 31
| Project: libresonic-master File: UserSettingsController.java View source code |
@RequestMapping(method = RequestMethod.POST)
protected String doSubmitAction(@ModelAttribute("command") @Validated UserSettingsCommand command, BindingResult bindingResult, RedirectAttributes redirectAttributes) throws Exception {
if (!bindingResult.hasErrors()) {
if (command.isDeleteUser()) {
deleteUser(command);
} else if (command.isNewUser()) {
createUser(command);
} else {
updateUser(command);
}
redirectAttributes.addFlashAttribute("settings_reload", true);
redirectAttributes.addFlashAttribute("settings_toast", true);
} else {
redirectAttributes.addFlashAttribute("command", command);
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.command", bindingResult);
redirectAttributes.addFlashAttribute("userIndex", getUserIndex(command));
}
return "redirect:userSettings.view";
}Example 32
| Project: members_cuacfm-master File: UserPaymentsController.java View source code |
/**
* View user fee members by fee member id.
*
* @param directDebitId the direct debit id
* @param emailPayer the email payer
* @param idPayer the id payer
* @param datePay the date pay
* @param statusPay the status pay
* @param idTxn the id txn
* @param principal the principal
* @param ra the ra
* @return the string
*/
@RequestMapping(value = "userPayments/directDebitList/paypal/{directDebitId}", method = RequestMethod.POST)
public String directDebitByPayPal(@PathVariable String directDebitId, @RequestParam("payer_email") String emailPayer, @RequestParam("payer_id") String idPayer, @RequestParam("payment_date") String datePay, @RequestParam("payment_status") String statusPay, @RequestParam("txn_id") String idTxn, Principal principal, RedirectAttributes ra) {
// Validar que el pago, este realmente echo en paypal, con la informacion
// que viene en el post....
Account account = accountService.findByLogin(principal.getName());
DirectDebit directDebit = directDebitService.findById(directDebitId);
// Verified if account is equals to account of userPayAccount
if (directDebit.getAccount().getId() == account.getId()) {
try {
directDebitService.paypal(directDebit, account, idTxn, idPayer, emailPayer, statusPay, datePay);
MessageHelper.addSuccessAttribute(ra, Constants.SUCCESSPAYPAL, directDebit.getConcept());
} catch (ExistTransactionIdException e) {
logger.warn("directDebitByPayPal - ExistTransactionIdException", e);
MessageHelper.addErrorAttribute(ra, Constants.ERRORPAYPAL, directDebit.getConcept(), e.getIdTxn());
}
}
return REDIRECT_USERPAYMENTS;
}Example 33
| Project: osm-tools-master File: OauthRequestController.java View source code |
@RequestMapping("/oauthResponse")
public String oauthResponse(@SuppressWarnings("unused") @RequestParam(value = "oauth_token", defaultValue = "") String oAuthToken, @RequestParam(value = "oauth_verifier", defaultValue = "") String oAuthVerifier, RedirectAttributes attributes) {
OauthTokens oauthTokens = oauthService.retrieveAccessToken(oAuthVerifier);
UserOperations userOperations = osmOperations.userOperations(oauthTokens);
try {
attributes.addFlashAttribute("osmUser", userOperations.getForUser());
} catch (Exception e) {
e.printStackTrace();
}
attributes.addFlashAttribute("oauthTokens", oauthTokens);
return "redirect:index";
}Example 34
| Project: park_java-master File: CartController.java View source code |
/*
* The Heat Clinic does not support adding products with required product
* options from a category browse page when JavaScript is disabled. When
* this occurs, we will redirect the user to the full product details page
* for the given product so that the required options may be chosen.
*/
@RequestMapping(value = "/cart/add", produces = { "text/html", "*/*" })
public String add(HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes, @ModelAttribute("addToCartItem") AddToCartItemEx addToCartItem) throws IOException, PricingException, AddToCartException {
Boolean w_flag = (Boolean) request.getSession().getAttribute("w_flag");
addToCartItem.validateLocationId();
try {
String return_url = add0(request, response, model, addToCartItem);
if (w_flag != null && w_flag) {
return "redirect:/weixin/cart";
} else {
return return_url;
}
} catch (AddToCartException e) {
Sku sku = catalogService.findSkuById(addToCartItem.getSkuId());
if (sku == null)
return "redirect:/";
String errorMsg;
if (e.getCause() instanceof RequiredAttributeNotProvidedException) {
errorMsg = "请选择商å“?è§„æ ¼ï¼Œ";
} else if (e.getCause() instanceof ProductOptionValidationException) {
errorMsg = "请选择商å“?è§„æ ¼ï¼Œ";
} else if (e.getCause() instanceof InventoryUnavailableException || e.getCause().getCause() instanceof InventoryUnavailableException) {
errorMsg = "这个太好了,被抢光了,下次�早点�。";
} else if (e.getCause() instanceof IllegalArgumentException && e.getCause().getMessage() != null) {
if (e.getCause().getMessage().indexOf("currencies") > 0)
errorMsg = "抱æ‰ï¼Œç§¯åˆ†å•†å“?ä¸?能与普通商å“?å?Œä¹°ï¼Œ";
else
errorMsg = e.getCause().getMessage();
} else {
errorMsg = "抱æ‰ï¼ŒåŠ å…¥è´ç‰©è½¦å‡ºé”™äº†ï¼?";
}
return "redirect:" + sku.getProduct().getUrl() + "?errorMessage=" + URLEncoder.encode(errorMsg, "UTF-8");
} catch (Exception e1) {
if (e1 instanceof InventoryUnavailableException) {
Sku sku = catalogService.findSkuById(addToCartItem.getSkuId());
if (sku == null)
return "redirect:/";
return "redirect:" + sku.getProduct().getUrl() + "?errorMessage=" + URLEncoder.encode("这个太好了,被抢光了,下次�早点�。", "UTF-8");
} else
throw new RuntimeException("error add", e1);
}
}Example 35
| Project: PhenotypeArchive-master File: GenesController.java View source code |
/**
* @throws IOException
*/
@RequestMapping("/genomeBrowser/{acc}")
public String genomeBrowser(@PathVariable String acc, Model model, HttpServletRequest request, RedirectAttributes attributes) throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException, GenomicFeatureNotFoundException, IOException {
System.out.println("genome browser called");
GenomicFeature gene = genesDao.getGenomicFeatureByAccession(acc);
System.out.println("gene in browser=" + gene);
if (gene == null) {
log.warn("Gene status for " + acc + " can't be found.");
}
Datasource ensembl = datasourceDao.getDatasourceByShortName("Ensembl");
Datasource vega = datasourceDao.getDatasourceByShortName("VEGA");
Datasource ncbi = datasourceDao.getDatasourceByShortName("EntrezGene");
Datasource ccds = datasourceDao.getDatasourceByShortName("cCDS");
List<String> ensemblIds = new ArrayList<String>();
List<String> vegaIds = new ArrayList<String>();
List<String> ncbiIds = new ArrayList<String>();
List<String> ccdsIds = new ArrayList<String>();
List<Xref> xrefs = gene.getXrefs();
for (Xref xref : xrefs) {
if (xref.getXrefDatabaseId() == ensembl.getId()) {
ensemblIds.add(xref.getXrefAccession());
} else if (xref.getXrefDatabaseId() == vega.getId()) {
vegaIds.add(xref.getXrefAccession());
} else if (xref.getXrefDatabaseId() == ncbi.getId()) {
ncbiIds.add(xref.getXrefAccession());
} else if (xref.getXrefDatabaseId() == ccds.getId()) {
ccdsIds.add(xref.getXrefAccession());
}
}
model.addAttribute("ensemblIds", ensemblIds);
model.addAttribute("vegaIds", vegaIds);
model.addAttribute("ncbiIds", ncbiIds);
model.addAttribute("ccdsIds", ccdsIds);
model.addAttribute("gene", gene);
return "genomeBrowser";
}Example 36
| Project: spring-boot-master File: MessageController.java View source code |
@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", "Successfully created a new message");
return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
}Example 37
| Project: spring-data-jpa-examples-master File: PersonControllerTest.java View source code |
@Test
public void delete() throws PersonNotFoundException {
Person deleted = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME);
when(personServiceMock.delete(PERSON_ID)).thenReturn(deleted);
initMessageSourceForFeedbackMessage(PersonController.FEEDBACK_MESSAGE_KEY_PERSON_DELETED);
RedirectAttributes attributes = new RedirectAttributesModelMap();
String view = controller.delete(PERSON_ID, attributes);
verify(personServiceMock, times(1)).delete(PERSON_ID);
verifyNoMoreInteractions(personServiceMock);
assertFeedbackMessage(attributes, PersonController.FEEDBACK_MESSAGE_KEY_PERSON_DELETED);
String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST);
assertEquals(expectedView, view);
}Example 38
| Project: spring-security-master File: MessageController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
if (result.hasErrors()) {
return new ModelAndView("messages/compose");
}
message = messageRepository.save(message);
redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
}Example 39
| Project: spring-security-test-blog-master File: MessageController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
if (result.hasErrors()) {
return new ModelAndView("messages/form");
}
message = messageRepository.save(message);
redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
return new ModelAndView("redirect:/messages/{message.id}", "message.id", message.getId());
}Example 40
| Project: spring-test-htmlunit-master File: MessageController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
if (result.hasErrors()) {
return new ModelAndView("messages/form");
}
message = messageRepository.save(message);
redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
return new ModelAndView("redirect:/messages/{message.id}", "message.id", message.getId());
}Example 41
| Project: tasq-master File: TaskController.java View source code |
@Transactional
@RequestMapping(value = "task/create", method = RequestMethod.POST)
public String createTask(@Valid @ModelAttribute("taskForm") TaskForm taskForm, BindingResult errors, @RequestParam(value = "linked", required = false) String linked, RedirectAttributes ra, HttpServletRequest request, Model model) {
if (!Roles.isUser()) {
throw new TasqAuthException(msg);
}
if (Utils.containsHTMLTags(taskForm.getName())) {
errors.rejectValue(NAME, ERROR_NAME_HTML);
}
checkEstimatesValues(taskForm, errors);
int storyPoints = getStoryPoints(taskForm);
if (!StringUtils.isNumeric(taskForm.getStory_points()) || !Utils.validStoryPoint(storyPoints)) {
errors.rejectValue(STORY_POINTS, "task.storyPoints.invalid");
}
if (errors.hasErrors()) {
fillCreateTaskModel(model);
return null;
}
Project project = projectSrv.findByProjectId(taskForm.getProject());
if (project != null) {
// check if can edit
Task task;
task = taskForm.createTask();
if (!projectSrv.canEdit(project)) {
MessageHelper.addErrorAttribute(ra, msg.getMessage(ERROR_ACCES_RIGHTS, null, Utils.getCurrentLocale()));
return REDIRECT + request.getHeader(REFERER);
}
// build ID
long taskCount = project.getLastTaskNo();
taskCount++;
String taskID = project.getProjectId() + "-" + taskCount;
task.setId(taskID);
task.setProject(project);
task.setTaskOrder(taskCount);
project.getTasks().add(task);
project.setLastTaskNo(taskCount);
// assigne
setCreatedTaskAssignee(taskForm, task);
//save before adding rest
task = taskSrv.save(task);
wlSrv.addActivityLog(task, "", LogType.CREATE);
// Create log work
if (taskForm.getAddToSprint() != null) {
Sprint sprint = sprintSrv.findByProjectIdAndSprintNo(project.getId(), taskForm.getAddToSprint());
task.addSprint(sprint);
// increase scope
if (sprint.isActive()) {
if (checkIfNotEstimated(task, project)) {
errors.rejectValue("addToSprint", "agile.task2Sprint.Notestimated", new Object[] { "", sprint.getSprintNo() }, "Unable to add not estimated task to active sprint");
fillCreateTaskModel(model);
return null;
}
String message = "";
wlSrv.addActivityLog(task, message, LogType.TASKSPRINTADD);
}
}
task = taskSrv.save(task);
projectSrv.save(project);
// Save files
saveTaskFiles(taskForm.getFiles(), task);
watchSrv.startWatching(task);
if (StringUtils.isNotBlank(linked)) {
Task linkedTask = taskSrv.findById(linked);
if (linkedTask != null) {
TaskLink link = new TaskLink(linkedTask.getId(), taskID, TaskLinkType.RELATES_TO);
linkService.save(link);
wlSrv.addWorkLogNoTask(linked + " - " + taskID, project, LogType.TASK_LINK);
}
}
//everything went well , save task
taskSrv.save(task);
MessageHelper.addSuccessAttribute(ra, msg.getMessage("task.create.success", new Object[] { taskID }, Utils.getCurrentLocale()));
return REDIRECT_TASK + taskID;
}
return null;
}Example 42
| Project: Tranquil-master File: PersonController.java View source code |
@RequestMapping("/edit/savePerson/")
public String savePerson(@ModelAttribute("person") Person person, final RedirectAttributes redirectAttributes) {
System.out.println("in savePerson - id is " + person.getPersonId());
System.out.println("in savePerson - list size is " + person.getAddresses().size());
personService.savePerson(person);
redirectAttributes.addFlashAttribute("message", "changes have been saved");
return "redirect:/people/";
}Example 43
| Project: ame-master File: UserController.java View source code |
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@Valid NewUser newUser, BindingResult result, RedirectAttributes attr, ModelMap model) {
try {
if (result.hasErrors()) {
model.addAttribute("templateName", "welcome");
return "base";
}
userService.save(newUser);
User user = userService.find(newUser.getEmail());
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
// Authenticate the user
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getEmail(), null, grantedAuths);
// Save user in session
auth.setDetails(user);
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (UserExistsException e) {
attr.addFlashAttribute("error", "That user already exists.");
LOG.info("User already exists.", e);
}
return "redirect:/welcome";
}Example 44
| Project: amediamanager-master File: UserController.java View source code |
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@Valid NewUser newUser, BindingResult result, RedirectAttributes attr, ModelMap model) {
try {
if (result.hasErrors()) {
model.addAttribute("templateName", "welcome");
return "base";
}
userService.save(newUser);
User user = userService.find(newUser.getEmail());
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
// Authenticate the user
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getEmail(), null, grantedAuths);
// Save user in session
auth.setDetails(user);
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (UserExistsException e) {
attr.addFlashAttribute("error", "That user already exists.");
LOG.info("User already exists.", e);
}
return "redirect:/welcome";
}Example 45
| Project: bees-shop-clickstart-master File: ProductController.java View source code |
@RequestMapping(value = "/product/{id}/mail", method = RequestMethod.POST)
public String sendEmail(@PathVariable long id, @RequestParam("recipientEmail") String recipientEmail, HttpServletRequest request, RedirectAttributes redirectAttributes) {
Product product = productRepository.get(id);
if (product == null) {
throw new ProductNotFoundException(id);
}
try {
String productPageUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/product/" + id;
mailService.sendProductEmail(product, recipientEmail, productPageUrl);
redirectAttributes.addFlashAttribute("mailSuccessMessage", "Email sent!");
} catch (MessagingException e) {
redirectAttributes.addFlashAttribute("mailFailureMessage", "Failure sending email: " + e.getMessage());
logger.warn("Failure sending message to " + recipientEmail, e);
}
return "redirect:/product/" + product.getId();
}Example 46
| Project: demo-application-master File: AccountsController.java View source code |
@TransactionTokenCheck(value = "create")
@RequestMapping(method = RequestMethod.POST)
public String create(@Validated final AccountForm form, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return createForm(form);
}
final Account inputAccount = beanMapper.map(form, Account.class);
for (final String authority : form.getAuthorities()) {
inputAccount.addAuthority(new AccountAuthority(null, authority));
}
final Account createdAccount;
try {
createdAccount = accountService.create(inputAccount);
} catch (final DuplicateKeyException e) {
model.addAttribute(Message.ACCOUNT_ID_USED.resultMessages());
return createForm(form);
} catch (final BusinessException e) {
model.addAttribute(e.getResultMessages());
return createForm(form);
}
return redirectDetailView(createdAccount.getAccountUuid(), Message.ACCOUNT_CREATED, redirectAttributes);
}Example 47
| Project: eMonocot-master File: ResourceController.java View source code |
/**
* @param organisationId
* Set the source identifier
* @param resourceId
* Set the job identifier
* @param model
* Set the model
* @param session
* Set the session
* @param resource
* Set the job
* @param result
* Set the binding results
* @return the view name
*/
@RequestMapping(value = "/{resourceId}", method = RequestMethod.POST, produces = "text/html", params = { "!parameters" })
public String update(@PathVariable Long resourceId, Model model, @Validated({ Default.class, ReadResource.class }) Resource resource, BindingResult result, RedirectAttributes redirectAttributes) {
Resource persistedResource = getService().load(resourceId);
if (result.hasErrors()) {
for (ObjectError objectError : result.getAllErrors()) {
logger.error(objectError.getDefaultMessage());
}
populateForm(model, resource, new ResourceParameterDto());
return "resource/update";
}
persistedResource.setUri(resource.getUri());
persistedResource.setTitle(resource.getTitle());
persistedResource.setResourceType(resource.getResourceType());
persistedResource.setLastHarvested(resource.getLastHarvested());
persistedResource.setJobId(resource.getJobId());
persistedResource.setLastHarvestedJobId(resource.getLastHarvestedJobId());
persistedResource.setStatus(resource.getStatus());
persistedResource.setStartTime(resource.getStartTime());
persistedResource.setDuration(resource.getDuration());
persistedResource.setExitCode(resource.getExitCode());
persistedResource.setExitDescription(resource.getExitDescription());
persistedResource.setRecordsRead(resource.getRecordsRead());
persistedResource.setReadSkip(resource.getReadSkip());
persistedResource.setProcessSkip(resource.getProcessSkip());
persistedResource.setWriteSkip(resource.getWriteSkip());
persistedResource.setWritten(resource.getWritten());
persistedResource.setParameters(resource.getParameters());
persistedResource.setScheduled(resource.getScheduled());
persistedResource.setSchedulingPeriod(resource.getSchedulingPeriod());
persistedResource.updateNextAvailableDate();
getService().saveOrUpdate(persistedResource);
String[] codes = new String[] { "resource.was.updated" };
Object[] args = new Object[] { resource.getTitle() };
DefaultMessageSourceResolvable message = new DefaultMessageSourceResolvable(codes, args);
redirectAttributes.addFlashAttribute("info", message);
return "redirect:/resource/{resourceId}";
}Example 48
| Project: enzymeportal-master File: ControllerAdvisor.java View source code |
@RequestMapping(value = FILTER_BY_FACETS, method = RequestMethod.GET)
public String filterByFacets(@ModelAttribute("searchModel") SearchModel searchModel, @RequestParam(value = "pageNumber", required = false) Integer pageNumber, @RequestParam(value = "ec", required = true) String ec, @RequestParam(value = "ecname", required = false) String ecname, @RequestParam(value = "taxId", required = false) Long taxId, @RequestParam(value = "organismName", required = false) String organismName, Model model, HttpServletRequest request, HttpSession session, RedirectAttributes attributes) {
if (pageNumber < 1) {
pageNumber = 1;
}
if (!StringUtils.isEmpty(ec)) {
return filterByFacetsEC(searchModel, pageNumber, ec, ecname, model, request, session, attributes);
} else {
return filterByFacetsTaxonomy(searchModel, pageNumber, taxId, organismName, model, request, session, attributes);
}
}Example 49
| Project: fenixedu-academic-master File: ProfessorshipController.java View source code |
/***
* Creates a new professorship for the teacher of this {@link TeacherAuthorization}
*
* @param authorization the teacher information
* @param bean information to create the professorship
* @return {@link #showCreate(Model, TeacherAuthorization, CreateProfessorshipBean)} if there is an error, otherwise redirects
* to {@link #home(Model, SearchBean, TeacherAuthorization)}
*/
@RequestMapping(method = POST, value = "{authorization}")
public String create(Model model, @PathVariable TeacherAuthorization authorization, @ModelAttribute CreateProfessorshipBean bean, RedirectAttributes attrs) {
try {
professorshipService.create(bean);
attrs.addAttribute("period", bean.getPeriod().getExternalId());
attrs.addAttribute("degree", bean.getDegree().getExternalId());
return "redirect:/teacher/professorships/" + authorization.getExternalId();
} catch (DomainException e) {
model.addAttribute("error", e.getLocalizedMessage());
return showCreate(model, authorization, bean);
}
}Example 50
| Project: fenixedu-cms-master File: AdminSites.java View source code |
@RequestMapping(value = "{slug}/edit", method = RequestMethod.POST)
public RedirectView edit(@PathVariable(value = "slug") String slug, @RequestParam LocalizedString name, @RequestParam LocalizedString description, @RequestParam(required = false) String theme, @RequestParam(required = false) String newSlug, @RequestParam(required = false, defaultValue = "") String initialPageSlug, @RequestParam(required = false, defaultValue = "false") Boolean published, @RequestParam(required = false) String viewGroup, @RequestParam(required = false) String folder, @RequestParam(required = false) String analyticsCode, @RequestParam(required = false) String accountId, RedirectAttributes redirectAttributes) {
if (name.isEmpty()) {
redirectAttributes.addFlashAttribute("emptyName", true);
return new RedirectView("/sites/" + slug + "/edit", true);
} else {
Site s = Site.fromSlug(slug);
newSlug = Optional.ofNullable(newSlug).orElse(slug);
if (canAccess(Authenticate.getUser(), s)) {
editSite(name, description, theme, newSlug, published, s, viewGroup, folder, analyticsCode, accountId, s.pageForSlug(initialPageSlug));
}
return new RedirectView("/cms/sites/" + newSlug + "#general", true);
}
}Example 51
| Project: github-cla-integration-master File: IndividualSignatoryController.java View source code |
@Transactional
@RequestMapping(method = RequestMethod.POST, value = "/{organization}/{repository}/individual")
String createIndividual(@PathVariable String organization, @PathVariable String repository, @RequestParam String name, @RequestParam("email") String emailAddress, @RequestParam String mailingAddress, @RequestParam String country, @RequestParam String telephoneNumber, @RequestParam("contribution") String[] addresses, @RequestParam("versionId") Version version, RedirectAttributes model) {
Agreement agreement = this.linkedRepositoryRepository.findByOrganizationAndRepository(organization, repository).getAgreement();
IndividualSignatory individualSignatory = this.individualSignatoryRepository.save(new IndividualSignatory(version, name, emailAddress, mailingAddress, country, telephoneNumber));
for (String address : addresses) {
this.signedAddressRepository.save(new SignedAddress(address, agreement, individualSignatory));
}
//
model.addFlashAttribute("organization", //
organization).addFlashAttribute("repository", repository);
return "redirect:/confirmation";
}Example 52
| Project: lolibox-master File: LoginController.java View source code |
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signupSubmit(@Valid RegisterDto registerDto, BindingResult bindingResult, RedirectAttributes redirectAttrs, Model model) {
if (bindingResult.hasErrors()) {
return signup(registerDto);
}
if (adminProperties.isSignupInvitation()) {
// validate invitation code
try {
if (!invitationCodeService.verify(registerDto.getEmail(), registerDto.getInvitationCode())) {
bindingResult.rejectValue("invitationCode", "invitationCode.error");
return signup(registerDto);
}
} catch (Exception e) {
bindingResult.rejectValue("invitationCode", "invitationCode.error");
return signup(registerDto);
}
}
User registered = new User();
registered.setRole(Role.ROLE_USER);
registered.setEmail(registerDto.getEmail());
registered.setUserName(registerDto.getUserName());
registered.setPassword(passwordEncoder.encode(registerDto.getPassword()));
try {
userService.registerNewUser(registered);
} catch (UserExistsException e) {
bindingResult.rejectValue("email", e.getMessage());
return signup(registerDto);
}
redirectAttrs.addAttribute("messages", "signup.success");
return "redirect:signin";
}Example 53
| Project: telekom-workflow-engine-master File: WorkflowInstancesListController.java View source code |
@PreAuthorize("hasRole('ROLE_TWE_ADMIN')")
@RequestMapping(value = "/workflow/instances/action", method = RequestMethod.POST)
public String abortInstances(@RequestParam String action, @ModelAttribute("refNums") List<Long> refNums, RedirectAttributes model) {
switch(action) {
case "abort":
invokeAction(refNums, model, new WorkflowInstanceActionInvoker() {
@Override
void invoke(Long refNum) {
facade.abortWorkflowInstance(refNum);
}
});
break;
case "suspend":
invokeAction(refNums, model, new WorkflowInstanceActionInvoker() {
@Override
void invoke(Long refNum) {
facade.suspendWorkflowInstance(refNum);
}
});
break;
case "resume":
invokeAction(refNums, model, new WorkflowInstanceActionInvoker() {
@Override
void invoke(Long refNum) {
facade.resumeWorkflowInstance(refNum);
}
});
break;
case "retry":
invokeAction(refNums, model, new WorkflowInstanceActionInvoker() {
@Override
void invoke(Long refNum) {
facade.retryWorkflowInstance(refNum);
}
});
break;
}
return "redirect:" + configuration.getConsoleMappingPrefix() + "/console/workflow/instances";
}Example 54
| Project: xbao-master File: AdminUserController.java View source code |
@RequestMapping("delete")
public String delete(String userId, RedirectAttributes redirectAttributes) {
AdminUser adminUser = adminUserService.findAdminUserById(userId);
if (adminUser != null) {
if (adminUser.getId().equals(CurrentUserUtil.getCurrentUser().getId())) {
redirectAttributes.addFlashAttribute("error", "ç¦?æ¢åˆ 除当å‰?登录账å?·");
} else {
adminUserService.removeAdminUser(adminUser);
redirectAttributes.addFlashAttribute("info", "åˆ é™¤æˆ?功");
}
}
return "redirect:list.adm";
}Example 55
| Project: categolj2-backend-master File: AuthenticationHelper.java View source code |
void handleHttpStatusCodeException(HttpStatusCodeException e, RedirectAttributes attributes) throws IOException {
if (logger.isInfoEnabled()) {
logger.info("authentication failed (message={},X-Track={})", e.getMessage(), e.getResponseHeaders().get("X-Track"));
}
try {
OAuth2Exception oAuth2Exception = objectMapper.readValue(e.getResponseBodyAsByteArray(), OAuth2Exception.class);
attributes.addAttribute("error", oAuth2Exception.getMessage());
} catch (JsonMappingExceptionJsonParseException | ex) {
attributes.addAttribute("error", e.getMessage());
}
}Example 56
| Project: deliciousfruit-master File: FruitStoryController.java View source code |
@RequestMapping(value = "init", method = RequestMethod.POST)
public String init(@Valid FruitStory newFruitStory, RedirectAttributes redirectAttributes) {
newFruitStory.setCreateTime(new Date());
fruitStoryService.saveFruitStory(newFruitStory);
FruitStoryMenu fruitStoryMenu = new FruitStoryMenu();
fruitStoryMenu.setFruitStory(newFruitStory);
fruitStoryMenuService.saveFruitStoryMenu(fruitStoryMenu);
newFruitStory.setFruitStoryMenu(fruitStoryMenu);
fruitStoryService.saveFruitStory(newFruitStory);
redirectAttributes.addFlashAttribute("message", "创建fruitStory�功,请输入详细信�");
return "redirect:/admin/fruitStory/update/" + newFruitStory.getId();
}Example 57
| Project: escuela-master File: AlumnoController.java View source code |
@RequestMapping("/crea")
public String crea(@Valid Alumno alumno, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
log.debug("Creando al alumno {}", alumno);
if (bindingResult.hasErrors()) {
return "alumno/nuevo";
}
alumno = alumnoDao.crea(alumno);
redirectAttributes.addFlashAttribute("mensaje", "El alumno " + alumno.getMatricula() + " ha sido creado");
return "redirect:/alumno/ver/" + alumno.getMatricula();
}Example 58
| Project: exit-web-framework-master File: DictionaryCategoryController.java View source code |
/**
*
* ä¿?å˜æˆ–æ›´æ–°å—典类别,ä¿?å˜æˆ?功å?Žé‡?定å?‘到:foundation/dictionary-category/view
*
* @param entity 实体信�
* @param parentId 所对应的父类id
* @param redirectAttributes spring mvc �定�属性
*
* @return String
*/
@RequestMapping("save")
public String save(@ModelAttribute("entity") DictionaryCategory entity, String parentId, RedirectAttributes redirectAttributes) {
if (StringUtils.isEmpty(parentId)) {
entity.setParent(null);
} else {
entity.setParent(systemDictionaryManager.getDictionaryCategory(parentId));
}
systemDictionaryManager.saveDictionaryCategory(entity);
redirectAttributes.addFlashAttribute("message", "ä¿?å˜æˆ?功");
return "redirect:/foundation/dictionary-category/view";
}Example 59
| Project: fenix-ist-master File: TeacherPagesController.java View source code |
@RequestMapping(value = "copyContent", method = RequestMethod.POST)
public RedirectView copyContent(@PathVariable ExecutionCourse executionCourse, @RequestParam ExecutionCourse previousExecutionCourse, RedirectAttributes redirectAttributes) {
canCopyContent(executionCourse, previousExecutionCourse);
try {
copyContent(previousExecutionCourse.getSite(), executionCourse.getSite());
} catch (RuntimeException e) {
LoggerFactory.getLogger(TeacherPagesController.class).error("error importing site content", e);
redirectAttributes.addFlashAttribute("importError", true);
return new RedirectView(String.format("/teacher/%s/pages", executionCourse.getExternalId()), true);
}
return new RedirectView(String.format("/teacher/%s/pages", executionCourse.getExternalId()), true);
}Example 60
| Project: greenhouse-master File: ResetPasswordController.java View source code |
/**
* Process a request by a person to reset a member password.
* Calls the {@link ResetPasswordService} to send a reset password mail.
* The mail message will contain a request token that must be presented to continue the password reset operation.
*/
@RequestMapping(value = "/reset", method = RequestMethod.POST)
public String sendResetMail(@RequestParam String signin, Model model, RedirectAttributes redirectAttrs) {
try {
service.sendResetMail(signin);
redirectAttrs.addFlashAttribute(Message.info("An email has been sent to you. Follow its instructions to reset your password."));
return "redirect:/reset";
} catch (SignInNotFoundException e) {
model.addAttribute("signin", FieldModel.error("not on file", signin));
return null;
}
}Example 61
| Project: login-server-master File: ChangeEmailController.java View source code |
@RequestMapping(value = "/change_email.do", method = RequestMethod.POST)
public String changeEmail(Model model, @Valid @ModelAttribute("newEmail") ValidEmail newEmail, BindingResult result, @RequestParam("client_id") String clientId, RedirectAttributes redirectAttributes, HttpServletResponse response) {
SecurityContext securityContext = SecurityContextHolder.getContext();
if (result.hasErrors()) {
model.addAttribute("error_message_code", "invalid_email");
model.addAttribute("email", ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getEmail());
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
return "change_email";
}
String origin = ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getOrigin();
if (!origin.equals(Origin.UAA)) {
redirectAttributes.addAttribute("error_message_code", "email_change.non-uaa-origin");
return "redirect:profile";
}
String userId = ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getId();
String userEmail = ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getName();
try {
changeEmailService.beginEmailChange(userId, userEmail, newEmail.getNewEmail(), clientId);
} catch (UaaException e) {
if (e.getHttpStatus() == 409) {
model.addAttribute("error_message_code", "username_exists");
model.addAttribute("email", ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getEmail());
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
return "change_email";
}
}
return "redirect:email_sent?code=email_change";
}Example 62
| Project: loli.io-master File: UserAction.java View source code |
/**
* 用户注册POSTæ??交
*
* @param user User对象
* @param model
* @param re_password 用户é‡?å¤?输入的密ç ?, 应为md5值
* @param password_md5 客户端js自动生æˆ?的密ç ?md5值, 用以验è¯?é?žæ³•æ??交
*/
@RequestMapping(value = { "/regist" }, method = RequestMethod.POST)
public String submitReg(@ModelAttribute User user, @RequestParam(TOKEN_NAME) String token, Model model, @RequestParam(required = true, value = "password_re") String passwordRe, HttpServletRequest request, RedirectAttributes redirectAttributes) {
Map<String, String> msgMap = new HashMap<String, String>();
request.setAttribute(MSG_NAME, msgMap);
Object tokenInSession = request.getSession().getAttribute(TOKEN_NAME);
if (null != tokenInSession && null != token && !token.equals(tokenInSession)) {
msgMap.put(TOKEN_NAME, "验è¯?ç ?ä¸?æ£ç¡®");
return REG_INPUT;
} else {
request.getSession().removeAttribute(TOKEN_NAME);
}
// 没有md5åŠ å¯†
if (user.getPassword().length() != 32 || !user.getPassword().equals(passwordRe)) {
msgMap.put(EMAIL_NAME, "�法请求");
return REG_INPUT;
}
// 用户注册日期
user.setRegDate(new Date());
try {
userService.save(user);
} catch (DBException e) {
logger.info("å·²ç»?å˜åœ¨æ¤é‚®ç®±" + e);
msgMap.put(EMAIL_NAME, e.getMessage());
return REG_INPUT;
}
redirectAttributes.addFlashAttribute("info", "您已�功注册");
return "redirect:" + LOGIN_INPUT;
}Example 63
| Project: spring-greenhouse-clickstart-master File: ResetPasswordController.java View source code |
/**
* Process a request by a person to reset a member password.
* Calls the {@link ResetPasswordService} to send a reset password mail.
* The mail message will contain a request token that must be presented to continue the password reset operation.
*/
@RequestMapping(value = "/reset", method = RequestMethod.POST)
public String sendResetMail(@RequestParam String signin, Model model, RedirectAttributes redirectAttrs) {
try {
service.sendResetMail(signin);
redirectAttrs.addFlashAttribute(Message.info("An email has been sent to you. Follow its instructions to reset your password."));
return "redirect:/reset";
} catch (SignInNotFoundException e) {
model.addAttribute("signin", FieldModel.error("not on file", signin));
return null;
}
}Example 64
| Project: spring-mvc-qq-weibo-master File: UserController.java View source code |
/**
* 演示自行绑定表å?•ä¸çš„checkBox roleList到对象ä¸.
*/
@RequiresPermissions("user:edit")
@RequestMapping(value = "update", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute("user") User user, @RequestParam(value = "roleList") List<Long> checkedRoleList, RedirectAttributes redirectAttributes) {
// bind roleList
user.getRoleList().clear();
for (Long roleId : checkedRoleList) {
Role role = new Role(roleId);
user.getRoleList().add(role);
}
accountService.saveUser(user);
redirectAttributes.addFlashAttribute("message", "ä¿?å˜ç”¨æˆ·æˆ?功");
return "redirect:/account/user";
}Example 65
| Project: terasoluna-tourreservation-mybatis3-master File: ManageReservationController.java View source code |
/**
* Updates the reservation after user changes edits the reservation info on the edit reservation page
* @param form
* @return
*/
@TransactionTokenCheck(value = "update", type = TransactionTokenType.IN)
@RequestMapping(value = "{reserveNo}/update", method = RequestMethod.POST)
public String update(@PathVariable("reserveNo") String reserveNo, @Validated ManageReservationForm form, BindingResult result, Model model, RedirectAttributes redirectAttr) {
if (result.hasErrors()) {
return updateRedo(reserveNo, form, model);
}
ReservationUpdateInput input = beanMapper.map(form, ReservationUpdateInput.class);
input.setReserveNo(reserveNo);
ReservationUpdateOutput output = reserveService.update(input);
redirectAttr.addFlashAttribute("output", output);
return "redirect:/reservations/{reserveNo}/update?complete";
}Example 66
| Project: uaa-master File: ChangeEmailController.java View source code |
@RequestMapping(value = "/change_email.do", method = RequestMethod.POST)
public String changeEmail(Model model, @Valid @ModelAttribute("newEmail") ValidEmail newEmail, BindingResult result, @RequestParam(required = false, value = "client_id") String clientId, @RequestParam(required = false, value = "redirect_uri") String redirectUri, RedirectAttributes redirectAttributes, HttpServletResponse response) {
SecurityContext securityContext = SecurityContextHolder.getContext();
if (result.hasErrors()) {
model.addAttribute("error_message_code", "invalid_email");
model.addAttribute("email", ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getEmail());
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
return "change_email";
}
String origin = ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getOrigin();
if (!origin.equals(OriginKeys.UAA)) {
redirectAttributes.addAttribute("error_message_code", "email_change.non-uaa-origin");
return "redirect:profile";
}
String userId = ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getId();
String userEmail = ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getName();
try {
changeEmailService.beginEmailChange(userId, userEmail, newEmail.getNewEmail(), clientId, redirectUri);
} catch (UaaException e) {
if (e.getHttpStatus() == 409) {
model.addAttribute("error_message_code", "username_exists");
model.addAttribute("email", ((UaaPrincipal) securityContext.getAuthentication().getPrincipal()).getEmail());
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
return "change_email";
}
}
return "redirect:email_sent?code=email_change";
}Example 67
| Project: components-html5-master File: GenericCrudController.java View source code |
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public String remove(@RequestParam(value = "id", required = true) Long id, RedirectAttributes redirectAttrs) {
try {
genericCrudBusiness.delete(id);
redirectAttrs.addFlashAttribute(EnumTipoMensagem.SUCESSO.getDescricao(), genericMessages.getDeleteSuccess());
} catch (IllegalArgumentException e) {
redirectAttrs.addFlashAttribute(EnumTipoMensagem.ERRO.getDescricao(), genericMessages.getNotFound());
log.trace("Não foi encontrado:", e);
} catch (Exception e) {
redirectAttrs.addFlashAttribute(EnumTipoMensagem.ERRO.getDescricao(), e.getMessage());
log.error("Erro ao salvar:", e);
}
return getReturnToListURL();
}Example 68
| Project: Consent2Share-master File: AdminController.java View source code |
/**
* NOTE: THIS FUNCTION IS A TEMPORARY FUNCTION TO PROCESS THE ADMIN CREATE
* PATIENT ACCOUNT FORM WHEN IT IS SUBMITTED. THIS FUNCTION MUST BE MODIFIED
* BEFORE IT IS INTEGREATED WITH THE BACK-END CODE.
*
* @param basicPatientAccountDto
* the basic patient account dto
* @param result
* the result
* @param redirectAttributes
* the redirect attributes
* @param model
* the model
* @return the string
* @throws PatientExistingException
* the patient existing exception
*/
@RequestMapping(value = "adminCreatePatientAccount.html", method = RequestMethod.POST)
public String adminCreatePatientAccount(@Valid BasicPatientAccountDto basicPatientAccountDto, BindingResult result, RedirectAttributes redirectAttributes, Model model) throws PatientExistingException {
fieldValidator.validate(basicPatientAccountDto, result);
if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("basicPatientAccountDto", basicPatientAccountDto);
redirectAttributes.addFlashAttribute("notify", "createPatientFailed");
return "redirect:/Administrator/adminHome.html";
}
try {
AdminCreatePatientResponseDto response = adminService.createPatientAccount(basicPatientAccountDto);
return "redirect:/Administrator/adminPatientView.html?id=" + response.getPatientId() + "&status=" + response.getMessage();
} catch (SpiritClientNotAvailableException e) {
redirectAttributes.addFlashAttribute("basicPatientAccountDto", basicPatientAccountDto);
redirectAttributes.addFlashAttribute("notify", "createPatientFailed");
return "redirect:/Administrator/adminHome.html";
}
}Example 69
| Project: developer-bookshelf-heroku-master File: BookController.java View source code |
/**
* Create/update a book.
*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid Book book, BindingResult bindingResult, Model model, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale, @RequestParam(value = "file", required = false) MultipartFile file) {
if (bindingResult.hasErrors()) {
model.addAttribute("book", book);
return "books/create";
}
logger.info("Creating/updating book");
model.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("book_save_success", new Object[] {}, locale)));
// Process upload file
if (!file.isEmpty() && (file.getContentType().equals(MediaType.IMAGE_JPEG_VALUE) || file.getContentType().equals(MediaType.IMAGE_PNG_VALUE) || file.getContentType().equals(MediaType.IMAGE_GIF_VALUE))) {
logger.info("File name: " + file.getName());
logger.info("File size: " + file.getSize());
logger.info("File content type: " + file.getContentType());
byte[] fileContent = null;
String imageString = null;
try {
InputStream inputStream = file.getInputStream();
fileContent = IOUtils.toByteArray(inputStream);
// Convert byte[] into String image
imageString = ImageUtil.encodeToString(fileContent);
book.setPhoto(imageString);
} catch (IOException ex) {
logger.error("Error saving uploaded file");
book.setPhoto(ImageUtil.smallNoImage());
}
} else // File is improper type or no file was uploaded.
{
// If book already exists, load its image into the 'book' object.
if (book.getId() != null) {
Book savedBook = bookService.findById(book.getId());
book.setPhoto(savedBook.getPhoto());
} else // Else set to default no-image picture.
{
book.setPhoto(ImageUtil.smallNoImage());
}
}
bookService.save(book);
return "redirect:/" + UrlUtil.encodeUrlPathSegment(book.getId().toString(), httpServletRequest);
}Example 70
| Project: ORCID-Source-master File: ManageProfileController.java View source code |
@RequestMapping(value = "/admin-switch-user", method = RequestMethod.GET)
public ModelAndView adminSwitchUser(HttpServletRequest request, @RequestParam("orcid") String targetOrcid, RedirectAttributes redirectAttributes) {
// Redirect to the new way of switching user, which includes admin
// access
ModelAndView mav = null;
if (StringUtils.isNotBlank(targetOrcid))
targetOrcid = targetOrcid.trim();
if (profileEntityManager.orcidExists(targetOrcid)) {
mav = new ModelAndView("redirect:/switch-user?username=" + targetOrcid);
} else {
redirectAttributes.addFlashAttribute("invalidOrcid", true);
mav = new ModelAndView("redirect:/my-orcid");
}
return mav;
}Example 71
| Project: site-master File: IndexController.java View source code |
@RequestMapping(value = "/register/{eventId}", method = GET)
public String register(@PathVariable final Integer eventId, final Model model, final RedirectAttributes redirectAttributes) {
final EventEntity event = this.eventRepository.findOne(eventId).orElse(null);
String rv;
if (event == null) {
redirectAttributes.addFlashAttribute(ATTRIBUTE_ALERTS, Arrays.asList("invalidEvent"));
rv = "redirect:/";
} else {
model.addAttribute(ATTRIBUTE_EVENT, event);
if (!model.containsAttribute("registration")) {
model.addAttribute("registration", new Registration());
}
if (!model.containsAttribute(ATTRIBUTE_REGISTERED)) {
model.addAttribute(ATTRIBUTE_REGISTERED, false);
}
rv = "register";
}
return rv;
}Example 72
| Project: spring-boot-sample-master File: ShiroController.java View source code |
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@Valid User user, HttpSession session, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return "login";
}
session.setAttribute("test", "测试");
String username = user.getUsername();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
//获�当�的Subject
Subject currentUser = SecurityUtils.getSubject();
logger.info("从HttpSessionä¸è¯»å?–Attr : test = {}", currentUser.getSession().getAttribute("test"));
try {
//在调用了login方法�,SecurityManager会收到AuthenticationToken,并将其��给已�置的Realm执行必须的认�检查
//æ¯?个Realm都能在必è¦?时对æ??交的AuthenticationTokens作出å??应
//所以这一æ¥åœ¨è°ƒç”¨login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法ä¸,具体验è¯?æ–¹å¼?详è§?æ¤æ–¹æ³•
logger.info("对用户[" + username + "]进行登录验�..验�开始");
currentUser.login(token);
logger.info("对用户[" + username + "]进行登录验�..验�通过");
} catch (UnknownAccountException uae) {
logger.info("对用户[" + username + "]进行登录验�..验�未通过,未知账户");
redirectAttributes.addFlashAttribute("message", "未知账户");
} catch (IncorrectCredentialsException ice) {
logger.info("对用户[" + username + "]进行登录验è¯?..验è¯?未通过,错误的å‡è¯?");
redirectAttributes.addFlashAttribute("message", "密ç ?ä¸?æ£ç¡®");
} catch (LockedAccountException lae) {
logger.info("对用户[" + username + "]进行登录验�..验�未通过,账户已�定");
redirectAttributes.addFlashAttribute("message", "账户已�定");
} catch (ExcessiveAttemptsException eae) {
logger.info("对用户[" + username + "]进行登录验�..验�未通过,错误次数过多");
redirectAttributes.addFlashAttribute("message", "用户å??或密ç ?错误次数过多");
} catch (AuthenticationException ae) {
logger.info("对用户[" + username + "]进行登录验è¯?..验è¯?未通过,å †æ ˆè½¨è¿¹å¦‚ä¸‹");
ae.printStackTrace();
redirectAttributes.addFlashAttribute("message", "用户å??或密ç ?ä¸?æ£ç¡®");
}
//验�是�登录�功
if (currentUser.isAuthenticated()) {
logger.info("用户[" + username + "]登录认�通过(这里�以进行一些认�通过�的一些系统�数�始化�作)");
return "redirect:/user";
} else {
token.clear();
return "redirect:/login";
}
}Example 73
| Project: spring-framework-master File: RequestMappingHandlerAdapter.java View source code |
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;
}Example 74
| Project: spring4-sandbox-master File: TaskController.java View source code |
@RequestMapping(value = "", method = RequestMethod.POST)
public String createTask(@ModelAttribute("task") @Valid TaskForm fm, BindingResult result, RedirectAttributes redirectAttrs) {
log.debug("saving task @" + fm);
if (result.hasErrors()) {
redirectAttrs.addFlashAttribute("flashMessage", AlertMessage.danger("Invalid input data!"));
return "add";
}
Task task = new Task();
task.setName(fm.getName());
task.setDescription(fm.getDescription());
task = taskRepository.save(task);
redirectAttrs.addFlashAttribute("flashMessage", AlertMessage.success("Task is created sucessfully!"));
return "redirect:/tasks";
}Example 75
| Project: XCoLab-master File: ProposalAdvancingTabController.java View source code |
@PostMapping("c/{proposalUrlString}/{proposalId}/tab/ADVANCING/saveJudgingFeedback")
public String saveJudgingFeedback(HttpServletRequest request, HttpServletResponse response, Model model, @Valid JudgeProposalFeedbackBean judgeProposalFeedbackBean, BindingResult result, RedirectAttributes redirectAttributes, Member member) throws IOException {
final Contest contest = proposalsContext.getContest(request);
Proposal proposal = proposalsContext.getProposalWrapped(request);
ContestPhase contestPhase = ContestClientUtil.getContestPhase(judgeProposalFeedbackBean.getContestPhaseId());
ProposalsPermissions permissions = proposalsContext.getPermissions(request);
Boolean isPublicRating = permissions.getCanPublicRating();
if (judgeProposalFeedbackBean.getScreeningUserId() != null && permissions.getCanAdminAll()) {
member = MembersClient.getMemberUnchecked(judgeProposalFeedbackBean.getScreeningUserId());
}
// Security handling
if (!(permissions.getCanJudgeActions() && proposal.isUserAmongSelectedJudge(member) || isPublicRating)) {
return ErrorText.ACCESS_DENIED.flashAndReturnRedirect(request);
}
final String redirectUrl = proposal.getWrapped().getProposalLinkUrl(contest, contestPhase.getContestPhasePK());
if (result.hasErrors()) {
AlertMessage.danger("Your rating was NOT saved! Please check the form for errors.").flash(request);
redirectAttributes.addFlashAttribute("judgeProposalFeedbackBean", judgeProposalFeedbackBean);
return "redirect:" + redirectUrl + "#rating";
}
if (permissions.getCanJudgeActions() && proposal.isUserAmongSelectedJudge(member)) {
isPublicRating = false;
}
//find existing ratings
List<ProposalRating> existingRatings = ProposalJudgeRatingClientUtil.getJudgeRatingsForProposalAndUser(member.getUserId(), proposal.getProposalId(), contestPhase.getContestPhasePK());
JudgingUtil.saveRatings(existingRatings, judgeProposalFeedbackBean, proposal.getProposalId(), contestPhase.getContestPhasePK(), member.getUserId(), isPublicRating);
AlertMessage.success("Rating saved successfully.").flash(request);
return "redirect:" + redirectUrl;
}Example 76
| Project: duo-registration-master File: DuoDeviceMgmtController.java View source code |
@RequestMapping(method = RequestMethod.POST, params = "sendsmscode")
public String sendSMSCode(@ModelAttribute("DuoPerson") DuoPersonObj duoperson, BindingResult result, HttpSession session, SessionStatus status, ModelMap model, final RedirectAttributes redirectAttributes, HttpServletRequest request) throws UnsupportedEncodingException, Exception {
logger.info("2FA Info - " + getIPForLog(request) + " - " + duoperson.getUsername() + " is SMSing passcode to " + duoperson.getPhonenumber());
duoPhoneService.objActionById(duoperson.getPhone_id(), "passcodeSMS");
redirectAttributes.addFlashAttribute("smsPhoneNumber", duoperson.getPhonenumber());
redirectAttributes.addFlashAttribute("smsSent", true);
//return form view
return "redirect:/secure/devicemgmt";
}Example 77
| Project: shopizer-master File: TaxClassController.java View source code |
@PreAuthorize("hasRole('TAX')")
@RequestMapping(value = "/admin/tax/taxclass/save.html", method = RequestMethod.POST)
public String saveTaxClass(@Valid @ModelAttribute("taxClass") TaxClass taxClass, BindingResult result, RedirectAttributes model, HttpServletRequest request, Locale locale) throws Exception {
Map<String, String> activeMenus = new HashMap<String, String>();
activeMenus.put("tax", "tax");
activeMenus.put("taxclass", "taxclass");
setMenu(model, (Map<String, Menu>) request.getAttribute("MENUMAP"), "tax", activeMenus);
MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);
ResponseData responseData = new ResponseData();
//requires code and name
if (taxClass.getCode().equals(TaxClass.DEFAULT_TAX_CLASS)) {
ObjectError error = new ObjectError("code", messages.getMessage("message.taxclass.alreadyexist", locale));
result.addError(error);
}
//check if the code already exist
TaxClass taxClassDb = taxClassService.getByCode(taxClass.getCode(), store);
if (taxClassDb != null) {
ObjectError error = new ObjectError("code", messages.getMessage("message.taxclass.alreadyexist", locale));
result.addError(error);
}
if (result.hasErrors()) {
return ControllerConstants.Tiles.Tax.taxClasses;
}
taxClassService.create(taxClass);
responseData.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);
responseData.setMessage("Request completed successfully");
model.addFlashAttribute("response", responseData);
return ControllerConstants.REDIRECT_PREFIX + "/admin/tax/taxclass/list.html";
}Example 78
| Project: belladati-sdk-tutorial-master File: TutorialController.java View source code |
/**
* Landing page after OAuth authorization, reached by redirect from the
* BellaDati server. Completes OAuth.
*/
@RequestMapping("/authorize")
public ModelAndView requestAccessToken(@RequestParam(value = "redirectUrl", required = false) String redirectUrl, RedirectAttributes redirectAttributes) {
try {
manager.completeOAuth();
} catch (AuthorizationException e) {
redirectAttributes.addFlashAttribute("error", "Authentication failed: " + e.getMessage());
}
if (redirectUrl == null) {
return new ModelAndView("redirect:/");
} else {
return new ModelAndView("redirect:" + redirectUrl);
}
}Example 79
| Project: javasec-master File: RmMessageController.java View source code |
/**
* 从页é?¢çš„表å?•获å?–å?•æ?¡è®°å½•idå¹¶åˆ é™¤ï¼Œå¦‚request.idä¸ºç©ºåˆ™åˆ é™¤å¤šæ?¡è®°å½•(request.ids)
*/
@RequestMapping(value = "delete", method = RequestMethod.POST)
public String delete(HttpServletRequest request, RedirectAttributes redirectAttributes) {
//定义æˆ?åŠŸåˆ é™¤çš„è®°å½•æ•°
int deleteCount = 0;
String id = request.getParameter(REQUEST_ID);
if (id != null && id.length() > 0) {
deleteCount = rmMessageService.delete(new Long(id));
} else {
//从request获�多�记录id
Long[] ids = RmJspHelper.getLongArrayFromRequest(request, REQUEST_IDS);
if (ids != null && ids.length != 0) {
//åˆ é™¤å¤šæ?¡è®°å½•
deleteCount += rmMessageService.delete(ids);
}
}
redirectAttributes.addFlashAttribute("message", "åˆ é™¤æˆ?功: " + deleteCount);
return "redirect:/message";
}Example 80
| Project: mystamps-master File: SeriesController.java View source code |
@PostMapping(path = Url.INFO_SERIES_PAGE, params = "action=ADD")
public String addToCollection(@PathVariable("id") Integer seriesId, @AuthenticationPrincipal CustomUserDetails currentUserDetails, RedirectAttributes redirectAttributes, HttpServletResponse response) throws IOException {
if (seriesId == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
boolean seriesExists = seriesService.isSeriesExist(seriesId);
if (!seriesExists) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
Integer userId = currentUserDetails.getUserId();
collectionService.addToCollection(userId, seriesId);
redirectAttributes.addFlashAttribute("justAddedSeries", true);
redirectAttributes.addFlashAttribute("justAddedSeriesId", seriesId);
String collectionSlug = currentUserDetails.getUserCollectionSlug();
return redirectTo(Url.INFO_COLLECTION_PAGE, collectionSlug);
}Example 81
| Project: ExcelToBarcode-master File: MainController.java View source code |
@RequestMapping(value = "/", method = RequestMethod.POST)
public String excelUpload(@RequestParam("fileToUpload") MultipartFile file, Model model, RedirectAttributes redirectAttributes) throws IOException {
LOG.info("Here I am and here is the multipart:");
if (file == null) {
LOG.info("OH no! file was null!");
return "/index";
}
LOG.info("File: " + file.getName() + " / " + file.getSize());
if (!xlsxContentType.equalsIgnoreCase(file.getContentType())) {
redirectAttributes.addAttribute("message", "File type was wrong - it should be .xlsx");
LOG.info("Content type was wrong; expected " + xlsxContentType + " but got: " + file.getContentType());
return "redirect:/index.html";
}
// if(! file.getOriginalFilename().endsWith(".xlsx")) {
// LOG.info("Problem: file name was wrong extension: " + file.getOriginalFilename());
// redirectAttributes.addAttribute("message", "File type was wrong - it should be .xlsx");
// return "redirect:/";
// }
LOG.info("about to get input stream");
// fixme - we should allow access to more than one sheet
xSSFWorkbook = new XSSFWorkbook(file.getInputStream());
// This is a list of integers corresponding to the live columns
columnList = getLiveColumnList();
model.addAttribute("columnList", columnList);
sheetPreview = getSheetPreview(xSSFWorkbook.getSheetAt(0), columnList);
model.addAttribute("sheetPreview", sheetPreview);
model.addAttribute("optionList", optionList);
return "/index";
}Example 82
| Project: InSpider-master File: DatasetController.java View source code |
/**
* Performs actions of the Dataset configuration view.<br/>
* A dataset can be removed, added, updated (uuid) and made (in)active.<br/>
* The proper working depends on the lists having the order in which items appear on the html form.
* @return view url
*/
@Transactional
@RequestMapping(value = "/ba/datasetconfig/{bronhouderId}", method = RequestMethod.POST)
public String updateDataset(@PathVariable Long bronhouderId, @RequestParam(value = "thema", required = true) String themaName, @ModelAttribute BronhouderDatasetForm bronhouderDatasetForm, Model model, RedirectAttributes redirectAttributes, //w1502 019
RefreshPolicy refreshPolicy) {
for (BronhouderDataset bronhouderDataset : bronhouderDatasetForm.getBronhouderDatasets()) {
Dataset dataset = this.managerDao.getDataSet(bronhouderDataset.getId());
if (dataset.getBronhouder().getId().equals(bronhouderId)) {
if (dataset.getDatasetType().getNaam().equals(bronhouderDataset.getType())) {
dataset.setNaam(bronhouderDataset.getNaam());
dataset.setActief(bronhouderDataset.isActief());
// W1502 019
dataset.setRefreshPolicy(bronhouderDataset.getRefreshPolicy());
final String oldUuid = dataset.getUuid();
final String newUuid = bronhouderDataset.getUuid();
if (!oldUuid.equals(newUuid)) {
dataset.setUuid(newUuid);
removeAndReimportDataAfterUuidChange(dataset, oldUuid, newUuid);
}
this.managerDao.update(dataset);
}
}
}
// Redirect after POST pattern
redirectAttributes.addAttribute("thema", themaName);
return "redirect:/ba/datasetconfig/" + bronhouderId;
}Example 83
| Project: jcommune-master File: UserProfileController.java View source code |
/**
* Update user security info. Check if the user enter valid data and update user security info in database.
* In error case return into the edit profile page and draw the error.
* <p/>
*
* @param editedProfileDto dto populated by user
* @param result binding result which contains the validation result
* @param response http servlet response
* @return in case of errors return back to edit security page, in another case return to user profile page
* @throws org.jtalks.jcommune.plugin.api.exceptions.NotFoundException
* if edited user doesn't exist in system
*/
@RequestMapping(value = "/users/*/security", method = RequestMethod.POST)
public ModelAndView saveEditedSecurity(@Valid @ModelAttribute(EDITED_USER) EditUserProfileDto editedProfileDto, BindingResult result, HttpServletResponse response, RedirectAttributes redirectAttributes) throws NotFoundException {
if (result.hasErrors()) {
return new ModelAndView(EDIT_PROFILE, EDITED_USER, editedProfileDto);
}
long editedUserId = editedProfileDto.getUserSecurityDto().getUserId();
checkPermissionForEditNotificationsOrSecurity(editedUserId);
JCUser user = retryTemplate.execute(new SaveProfileRetryCallback(editedUserId, editedProfileDto, SECURITY));
if (editedProfileDto.getUserSecurityDto().getNewUserPassword() != null) {
redirectAttributes.addFlashAttribute(IS_PASSWORD_CHANGED_ATTRIB, true);
}
//redirect to the view profile page
return new ModelAndView("redirect:/users/" + user.getId() + "/" + SECURITY);
}Example 84
| Project: jTalk-master File: UserProfileController.java View source code |
/**
* Update user security info. Check if the user enter valid data and update user security info in database.
* In error case return into the edit profile page and draw the error.
* <p/>
*
* @param editedProfileDto dto populated by user
* @param result binding result which contains the validation result
* @param response http servlet response
* @return in case of errors return back to edit security page, in another case return to user profile page
* @throws org.jtalks.jcommune.plugin.api.exceptions.NotFoundException
* if edited user doesn't exist in system
*/
@RequestMapping(value = "/users/*/security", method = RequestMethod.POST)
public ModelAndView saveEditedSecurity(@Valid @ModelAttribute(EDITED_USER) EditUserProfileDto editedProfileDto, BindingResult result, HttpServletResponse response, RedirectAttributes redirectAttributes) throws NotFoundException {
if (result.hasErrors()) {
return new ModelAndView(EDIT_PROFILE, EDITED_USER, editedProfileDto);
}
long editedUserId = editedProfileDto.getUserSecurityDto().getUserId();
checkPermissionForEditNotificationsOrSecurity(editedUserId);
JCUser user = retryTemplate.execute(new SaveProfileRetryCallback(editedUserId, editedProfileDto, SECURITY));
if (editedProfileDto.getUserSecurityDto().getNewUserPassword() != null) {
redirectAttributes.addFlashAttribute(IS_PASSWORD_CHANGED_ATTRIB, true);
}
//redirect to the view profile page
return new ModelAndView("redirect:/users/" + user.getId() + "/" + SECURITY);
}Example 85
| Project: ngrinder-master File: FileEntryController.java View source code |
/**
* Provide new file creation form data.
*
* @param user current user
* @param path path in which a file will be added
* @param testUrl url which the script may use
* @param fileName fileName
* @param scriptType Type of script. optional
* @param createLibAndResources true if libs and resources should be created as well.
* @param redirectAttributes redirect attributes storage
* @param model model.
* @return script/editor"
*/
@RequestMapping(value = "/new/**", params = "type=script", method = RequestMethod.POST)
public String createForm(User user, @RemainedPath String path, @RequestParam(value = "testUrl", required = false) String testUrl, @RequestParam("fileName") String fileName, @RequestParam(value = "scriptType", required = false) String scriptType, @RequestParam(value = "createLibAndResource", defaultValue = "false") boolean createLibAndResources, @RequestParam(value = "options", required = false) String options, RedirectAttributes redirectAttributes, ModelMap model) {
fileName = StringUtils.trimToEmpty(fileName);
String name = "Test1";
if (StringUtils.isEmpty(testUrl)) {
testUrl = StringUtils.defaultIfBlank(testUrl, "http://please_modify_this.com");
} else {
name = UrlUtils.getHost(testUrl);
}
ScriptHandler scriptHandler = fileEntryService.getScriptHandler(scriptType);
FileEntry entry = new FileEntry();
entry.setPath(fileName);
if (scriptHandler instanceof ProjectHandler) {
if (!fileEntryService.hasFileEntry(user, PathUtils.join(path, fileName))) {
fileEntryService.prepareNewEntry(user, path, fileName, name, testUrl, scriptHandler, createLibAndResources, options);
redirectAttributes.addFlashAttribute("message", fileName + " project is created.");
return "redirect:/script/list/" + encodePathWithUTF8(path) + "/" + fileName;
} else {
redirectAttributes.addFlashAttribute("exception", fileName + " is already existing. Please choose the different name");
return "redirect:/script/list/" + encodePathWithUTF8(path) + "/";
}
} else {
String fullPath = PathUtils.join(path, fileName);
if (fileEntryService.hasFileEntry(user, fullPath)) {
model.addAttribute("file", fileEntryService.getOne(user, fullPath));
} else {
model.addAttribute("file", fileEntryService.prepareNewEntry(user, path, fileName, name, testUrl, scriptHandler, createLibAndResources, options));
}
}
model.addAttribute("breadcrumbPath", getScriptPathBreadcrumbs(PathUtils.join(path, fileName)));
model.addAttribute("scriptHandler", scriptHandler);
model.addAttribute("createLibAndResource", createLibAndResources);
return "script/editor";
}Example 86
| Project: kanban-app-master File: KanbanBoardController.java View source code |
@RequestMapping("wall")
public synchronized ModelAndView wallBoard(@ModelAttribute("project") KanbanProject project, @PathVariable("projectName") String projectName, @RequestParam(value = "scrollTop", required = false) String scrollTop, @ModelAttribute("workStreams") Map<String, String> workStreams, @RequestParam(value = "highlight", required = false) String highlight, @ModelAttribute("error") String error, RedirectAttributes redirectAttributes) throws IOException {
Map<String, Object> model = initBoard("wall", projectName, error, scrollTop);
KanbanBoard board = project.getBoard(BoardIdentifier.WALL, workStreams.get(projectName));
model.put("board", board);
model.put("highlight", highlight);
return new ModelAndView("/project.jsp", model);
}Example 87
| Project: carmaint-master File: SignupController.java View source code |
@RequestMapping(value = "signup", method = RequestMethod.POST)
public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors, RedirectAttributes ra) {
if (errors.hasErrors()) {
return null;
}
Account account = accountRepository.save(signupForm.createAccount());
userService.signin(account);
MessageHelper.addSuccessAttribute(ra, "Congratulations! You have successfully signed up.");
return "redirect:/";
}Example 88
| Project: spring-framework-issues-master File: TestController.java View source code |
// OK
@RequestMapping("/test1")
String test1(RedirectAttributes redir) {
redir.addFlashAttribute("name", "World");
return "redirect:/";
}Example 89
| Project: servlet3-showcase-master File: PjaxFormController.java View source code |
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String edit(@RequestHeader(value = "X-PJAX", defaultValue = "false") boolean isPjax, Model model, RedirectAttributes redirectAttributes) {
if (!isPjax) {
redirectAttributes.addFlashAttribute("message", "新增�功");
return "redirect:/form";
} else {
model.addAttribute("message", "新增�功");
return "form/index_fragment";
}
}Example 90
| Project: appleframework-master File: BaseController.java View source code |
protected void addFlashMessage(RedirectAttributes redirectAttributes, Message message) {
if (redirectAttributes != null && message != null) {
redirectAttributes.addFlashAttribute(FlashMessageDirective.FLASH_MESSAGE_ATTRIBUTE_NAME, message);
}
}Example 91
| Project: belladati-sdk-demo-web-master File: AuthorizationController.java View source code |
/**
* Landing page after OAuth authorization. Completes OAuth.
*/
@RequestMapping(value = "/authorize", method = RequestMethod.GET)
public ModelAndView requestAccessToken(RedirectAttributes redirectAttributes) {
try {
serviceManager.completeOAuth();
} catch (AuthorizationException e) {
redirectAttributes.addFlashAttribute("error", "Authentication failed: " + e.getMessage());
}
return new ModelAndView("redirect:/");
}Example 92
| Project: Fingra.ph_Statistics-Web-master File: SignupController.java View source code |
@RequestMapping(method = RequestMethod.POST, value = "/signup")
public String signup(@Valid Member member, BindingResult bindingResult, RedirectAttributes ra) {
memberService.create(member);
ra.addFlashAttribute("member", member);
return "redirect:/signup/result";
}Example 93
| Project: btpka3.github.com-master File: UserAction.java View source code |
/**
* 新增用户。
*/
@RequestMapping(value = "/list", method = { RequestMethod.POST })
public String newUser(@RequestParam(value = "hospitalId") Long hospitalId, @RequestParam(value = "name") String name, @RequestParam(value = "remark", required = false) String remark, Model model, RedirectAttributes redirectAttributes) {
Long userId = userService.insert(hospitalId, name, remark);
// 相当于设置302跳转时URL上的�数
redirectAttributes.addAttribute("hospitalId", hospitalId);
redirectAttributes.addAttribute("userId", userId);
return "redirect:detail.do";
}Example 94
| Project: mybatis-spring-boot-master File: CountryController.java View source code |
@RequestMapping(value = "/delete/{id}")
public ModelAndView delete(@PathVariable Integer id, RedirectAttributes ra) {
ModelAndView result = new ModelAndView("redirect:/countries");
countryService.deleteById(id);
ra.addFlashAttribute("msg", "åˆ é™¤æˆ?功!");
return result;
}Example 95
| Project: spring-jpetstore-master File: OrderController.java View source code |
@RequestMapping(value = "newOrder", params = "confirmed")
public String newOrder(OrderForm orderForm, SessionStatus status, RedirectAttributes attributes) {
Order order = orderHelper.newOrder(orderForm, cart);
attributes.addAttribute("orderId", order.getOrderId());
attributes.addFlashAttribute("message", "Thank you, your order has been submitted.");
status.setComplete();
return "redirect:/order/viewOrder";
}Example 96
| Project: spring4-showcase-master File: UserController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public String create(@ModelAttribute("user") User user, BindingResult result, RedirectAttributes redirectAttributes) {
if ("admin".equals(user.getName())) {
result.rejectValue("name", "用户å??ä¸?能为admin");
return "showCreateForm";
} else {
redirectAttributes.addFlashAttribute("success", "创建�功");
}
return "redirect:/user";
}Example 97
| Project: podcastpedia-master File: UpdateMetadataController.java View source code |
/** This creates the view for the admin home page */
@RequestMapping(method = RequestMethod.POST)
public String postToBiggerForm(@ModelAttribute("updatePodcastByFeedUrlForm") PodcastByFeedUrlForm podcastByFeedUrlForm, Model model, final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("updatePodcastOwnMetadataByFeedUrlForm", podcastByFeedUrlForm);
return "redirect:/admin/update/metadata/details";
}Example 98
| Project: terasoluna-gfw-functionaltest-master File: ValidationController.java View source code |
@RequestMapping(value = "bytemin", method = RequestMethod.POST)
public String validateByteMin(@Validated({ ValidationForm.ValidateByteMin.class }) ValidationForm form, BindingResult bindingResult, Model model, RedirectAttributes attributes) {
if (bindingResult.hasErrors()) {
return bytemin(model);
}
attributes.addFlashAttribute(ResultMessages.success().add(SUCCESS));
return "redirect:/validation/bytemin/";
}