下面列出了怎么用org.springframework.web.bind.annotation.ModelAttribute的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 列表页面
* @return
*/
@RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
public void list(@ModelAttribute JwSystemUserJwid query,HttpServletResponse response,HttpServletRequest request,
@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
String userId = query.getUserId();
VelocityContext velocityContext = new VelocityContext();
if(StringUtils.isNotEmpty(userId)){
PageQuery<JwSystemUserJwid> pageQuery = new PageQuery<JwSystemUserJwid>();
pageQuery.setPageNo(pageNo);
pageQuery.setPageSize(pageSize);
pageQuery.setQuery(query);
velocityContext.put("jwSystemUserJwid",query);
velocityContext.put("pageInfos",SystemTools.convertPaginatedList(jwSystemUserJwidService.queryPageList(pageQuery)));
}
String viewName = "system/back/jwSystemUserJwid-list.vm";
ViewVelocity.view(request,response,viewName,velocityContext);
}
/**
* Display empty reflection form.
*/
@RequestMapping("/newReflection")
public String newReflection(@ModelAttribute("reflectionForm") ReflectionForm refForm, HttpServletRequest request) {
// get session value
String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID);
HttpSession ss = SessionManager.getSession();
UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
refForm.setUserID(user.getUserID());
refForm.setSessionMapID(sessionMapID);
// get the existing reflection entry
SessionMap<String, Object> sessionMap = getSessionMap(request);
Long toolSessionID = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
NotebookEntry entry = service.getEntry(toolSessionID, user.getUserID());
if (entry != null) {
refForm.setEntryText(entry.getEntry());
}
return "pages/learning/notebook";
}
@RequestMapping("index")
public String list(@ModelAttribute Page page,
@RequestParam Map<String, Object> parameterMap, Model model) {
String tenantId = tenantHolder.getTenantId();
List<PropertyFilter> propertyFilters = PropertyFilter
.buildFromMap(parameterMap);
propertyFilters.add(new PropertyFilter("EQS_tenantId", tenantId));
page.setDefaultOrder("id", Page.DESC);
page = expenseRequestManager.pagedQuery(page, propertyFilters);
model.addAttribute("page", page);
return "expense/index";
}
@RequestMapping("/openNotebook")
public String openNotebook(@ModelAttribute("learningForm") LearningForm learningForm, HttpServletRequest request,
HttpServletResponse response) {
// set the finished flag
PixlrUser pixlrUser = this.getCurrentUser(learningForm.getToolSessionID());
PixlrDTO pixlrDTO = new PixlrDTO(pixlrUser.getPixlrSession().getPixlr());
request.setAttribute("pixlrDTO", pixlrDTO);
NotebookEntry notebookEntry = pixlrService.getEntry(pixlrUser.getPixlrSession().getSessionId(),
CoreNotebookConstants.NOTEBOOK_TOOL, PixlrConstants.TOOL_SIGNATURE, pixlrUser.getUserId().intValue());
if (notebookEntry != null) {
learningForm.setEntryText(notebookEntry.getEntry());
}
Long toolSessionID = pixlrUser.getPixlrSession().getSessionId();
request.setAttribute(AttributeNames.ATTR_IS_LAST_ACTIVITY, pixlrService.isLastActivity(toolSessionID));
return "pages/learning/notebook";
}
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user,
@ModelAttribute Order order) {
if (order.getDeliveryName() == null) {
order.setDeliveryName(user.getFullname());
}
if (order.getDeliveryStreet() == null) {
order.setDeliveryStreet(user.getStreet());
}
if (order.getDeliveryCity() == null) {
order.setDeliveryCity(user.getCity());
}
if (order.getDeliveryState() == null) {
order.setDeliveryState(user.getState());
}
if (order.getDeliveryZip() == null) {
order.setDeliveryZip(user.getZip());
}
return "orderForm";
}
@RestAccessControl(permission = Permission.MANAGE_USERS)
@RequestMapping(value = "/{target:.+}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse<UserDto>> updateUser(@ModelAttribute("user") UserDetails user, @PathVariable String target, @Valid @RequestBody UserRequest userRequest, BindingResult bindingResult) {
logger.debug("updating user {} with request {}", target, userRequest);
//field validations
if (bindingResult.hasErrors()) {
throw new ValidationGenericException(bindingResult);
}
this.getUserValidator().validatePutBody(target, userRequest, bindingResult);
this.getUserValidator().validateUpdateSelf(target, user.getUsername(), bindingResult);
if (bindingResult.hasErrors()) {
throw new ValidationGenericException(bindingResult);
}
UserDto userDto = this.getUserService().updateUser(userRequest);
return new ResponseEntity<>(new SimpleRestResponse<>(userDto), HttpStatus.OK);
}
@RequestMapping
public String unapprove(
@Valid @ModelAttribute("form") CommentBulkUnapproveForm form,
BindingResult errors,
String query,
AuthorizedUser authorizedUser,
RedirectAttributes redirectAttributes,
Model model) {
redirectAttributes.addAttribute("query", query);
if (errors.hasErrors()) {
logger.debug("Errors: {}", errors);
return "redirect:/_admin/{language}/comments/index";
}
Collection<Comment> unapprovedComments;
try {
unapprovedComments = commentService.bulkUnapproveComment(form.toCommentBulkUnapproveRequest(), authorizedUser);
} catch (ServiceException e) {
return "redirect:/_admin/{language}/comments/index";
}
redirectAttributes.addFlashAttribute("unapprovedComments", unapprovedComments);
return "redirect:/_admin/{language}/comments/index";
}
@RequestMapping(path = "/removeTheme")
public String removeTheme(@ModelAttribute ThemeForm themeForm, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Remove the theme
if (themeForm.getId() != null) {
themeService.removeTheme(themeForm.getId());
}
String currentTheme = Configuration.get(ConfigurationKeys.DEFAULT_THEME);
if (themeForm.getName().equals(currentTheme)) {
Configuration.updateItem(ConfigurationKeys.DEFAULT_THEME, CSSThemeUtil.DEFAULT_HTML_THEME);
configurationService.persistUpdate();
}
themeForm.clear();
return unspecified(themeForm, request);
}
@RequestMapping(method=RequestMethod.POST)
public RedirectView submitForm(Model model, @Validated @ModelAttribute("deptForm") DepartmentForm deptForm, BindingResult bindingResult){
model.addAttribute("deptForm", deptForm);
RedirectView redirectView = new RedirectView();
redirectView.setContextRelative(true);
redirectView.setUrl("/smp/admin_add_department.html");
List<Tbldepartment> depts = reportService.getAllDepartment();
model.addAttribute("depts", depts);
if(bindingResult.hasErrors()) {
deptForm = new DepartmentForm();
model.addAttribute("deptForm", deptForm);
} else{
managementService.addDepartment(deptForm);
deptForm = new DepartmentForm();
model.addAttribute("deptForm", deptForm);
}
return redirectView;
}
/**
* 待办任务.
*/
@RequestMapping("workspace-personalTasks")
public String personalTasks(@ModelAttribute Page page,
@RequestParam Map<String, Object> parameterMap, Model model) {
String userId = currentUserHolder.getUserId();
String tenantId = tenantHolder.getTenantId();
page = humanTaskConnector.findPersonalTasks(userId, tenantId,
page.getPageNo(), page.getPageSize());
// List<PropertyFilter> propertyFilters = PropertyFilter
// .buildFromMap(parameterMap);
// propertyFilters.add(new PropertyFilter("EQS_status", "active"));
// propertyFilters.add(new PropertyFilter("EQS_assignee", userId));
// page = taskInfoManager.pagedQuery(page, propertyFilters);
model.addAttribute("page", page);
return "humantask/workspace-personalTasks";
}
@ModelAttribute(value = "baseUrl", binding = false)
public String getBaseUrl(UriComponentsBuilder uriBuilder) {
UriComponents publicComponents = UriComponentsBuilder.fromUriString(this.publicUrl).build();
if (publicComponents.getScheme() != null) {
uriBuilder.scheme(publicComponents.getScheme());
}
if (publicComponents.getHost() != null) {
uriBuilder.host(publicComponents.getHost());
}
if (publicComponents.getPort() != -1) {
uriBuilder.port(publicComponents.getPort());
}
if (publicComponents.getPath() != null) {
uriBuilder.path(publicComponents.getPath());
}
return uriBuilder.path("/").toUriString();
}
/**
* 列表页面
* @return
*/
@RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
public void list(@ModelAttribute WeixinTmessgaeTask query,HttpServletResponse response,HttpServletRequest request,
@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
String jwid = request.getSession().getAttribute("jwid").toString();
query.setJwid(jwid);
PageQuery<WeixinTmessgaeTask> pageQuery = new PageQuery<WeixinTmessgaeTask>();
pageQuery.setPageNo(pageNo);
pageQuery.setPageSize(pageSize);
VelocityContext velocityContext = new VelocityContext();
pageQuery.setQuery(query);
velocityContext.put("weixinTmessgaeTask",query);
velocityContext.put("pageInfos",SystemTools.convertPaginatedList(weixinTmessgaeTaskService.queryPageList(pageQuery)));
List<WeixinTmessage> tmessages = weixinTmessageService.queryByJwid(jwid);
velocityContext.put("tmessages", tmessages);
List<WeixinTag> weixinTags = weixinTagService.getAllTags(jwid);
velocityContext.put("weixinTags", weixinTags);
String viewName = "tmessage/back/weixinTmessgaeTask-list.vm";
ViewVelocity.view(request,response,viewName,velocityContext);
}
/**
* 列表页面
* @return
*/
@RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
public void list(@ModelAttribute WeixinTmessage query,HttpServletResponse response,HttpServletRequest request,
@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
String jwid = request.getSession().getAttribute("jwid").toString();
query.setJwid(jwid);
PageQuery<WeixinTmessage> pageQuery = new PageQuery<WeixinTmessage>();
pageQuery.setPageNo(pageNo);
pageQuery.setPageSize(pageSize);
VelocityContext velocityContext = new VelocityContext();
pageQuery.setQuery(query);
velocityContext.put("weixinTmessage",query);
PageList<WeixinTmessage> pageList = weixinTmessageService.queryPageList(pageQuery);
List<WeixinTmessage> tmessgaes = pageList.getValues();
if(tmessgaes != null && tmessgaes.size() > 0) {
for (WeixinTmessage tmessgae : tmessgaes) {
tmessgae.setExample(tmessgae.getExample().replaceAll("\n", "<br/>"));
}
}
pageList.setValues(tmessgaes);
velocityContext.put("pageInfos",SystemTools.convertPaginatedList(pageList));
String viewName = "tmessage/back/weixinTmessage-list.vm";
ViewVelocity.view(request,response,viewName,velocityContext);
}
@RequestMapping("/saveOrUpdate")
public String saveOrUpdatePedagogicalPlannerForm(@ModelAttribute NbPedagogicalPlannerForm plannerForm,
HttpServletRequest request) {
MultiValueMap<String, String> errorMap = plannerForm.validate(null);
if (errorMap.isEmpty()) {
String content = plannerForm.getBasicContent();
Long toolContentID = plannerForm.getToolContentID();
NoticeboardContent noticeboard = nbService.retrieveNoticeboard(toolContentID);
noticeboard.setContent(content);
nbService.saveNoticeboard(noticeboard);
} else {
request.setAttribute("errorMap", errorMap);
}
return "authoring/pedagogicalPlannerForm";
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, params = "!action")
public String updateTask(@PathVariable("id") Long id, @ModelAttribute("task") @Valid TaskForm fm, BindingResult result, RedirectAttributes redirectAttrs) {
log.debug("updating task @" + fm);
if (result.hasErrors()) {
return "edit";
}
Task task = taskRepository.findOne(id);
if (task == null) {
throw new TaskNotFoundException(id);
}
task.setName(fm.getName());
task.setDescription(fm.getDescription());
taskRepository.save(task);
redirectAttrs.addFlashAttribute("flashMessage", AlertMessage.info("Task is updated sucessfully!"));
return "redirect:/tasks";
}
/**
* 保存信息
* @return
*/
@RequestMapping(value = "/doAdd",method ={RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public AjaxJson doAdd(@ModelAttribute WeixinAutoresponse weixinAutoresponse){
AjaxJson j = new AjaxJson();
try {
weixinAutoresponse.setCreateTime(new Date());
weixinAutoresponseService.doAdd(weixinAutoresponse);
j.setMsg("保存成功");
} catch (Exception e) {
log.error(e.getMessage());
j.setSuccess(false);
j.setMsg("保存失败");
}
return j;
}
@RequestMapping(value = "/user", params = "add", method = RequestMethod.POST)
public String postAddUser(@ModelAttribute @Valid User user,
BindingResult result, Model model) {
System.out.println("result->has errors:-"+result.hasErrors()+" "+result);
if (result.hasErrors()) {
System.out.println(result.getAllErrors().toString());
ArrayList<Role> roles = new ArrayList<Role>();
roles.add(Role.ADMIN);
roles.add(Role.HEAD_OF_DEPARTMENT);
model.addAttribute("roles", roles);
return "user/add";
} else {
System.out.println("Inside postAddUser");
user = userService.save(user);
return "redirect:user?id=" + user.getId();
}
}
@RequestMapping(value = "/doUpdateInitStateJobQueue")
@ResponseBody
public String doUpdateInitStateJobQueue(@ModelAttribute("view") JobRunQueueView view) {
try {
long id = view.getId();
String jobIdList = view.getJobIdList();
JobRunQueueInfo newInfo = new JobRunQueueInfo();
newInfo.setId(id);
newInfo.setJobIdList(jobIdList);
newInfo.setCurrentPorcessId("");
if(StringUtils.isNotBlank(jobIdList)) {
String[] ids = jobIdList.split(",");
for(String s : ids) {
JobConfigInfo jci = jobService.getJobConfigById(Long.parseLong(s));
if(null == jci) {
return "job config id="+s+" not exist!";
}
}
int length = jobIdList.split(",").length;
newInfo.setJobCount(length);
} else {
return "job id list is empty!";
}
newInfo.setSuccessList("");
newInfo.setFailureList("");
newInfo.setQueueState(JobRunQueueState.INIT);
queueService.modifyJobRunQueueConfig(newInfo);
return "success";
} catch (ValidationException e) {
logger.error("update job queue state failure.", e);
return e.getMessage();
}
}
@RequestMapping(value = "/apiurl/v1/address", method = POST)
@ResponseBody
@ResponseStatus(ACCEPTED)
public void saveAddressUrlV1(@Valid @ModelAttribute final AddressParamV1 addressParamV1) {
Address address = convertFromV1(addressParamV1);
addressService.save(address);
}
@SuppressWarnings("unused")
public void modelAttribute(
@ModelAttribute("attrName") @Valid TestBean annotatedAttr,
Errors errors,
int intArg,
@ModelAttribute TestBean defaultNameAttr,
@ModelAttribute(name="noBindAttr", binding=false) @Valid TestBean noBindAttr,
TestBean notAnnotatedAttr) {
}
/**
* 任务列表.
*/
@RequestMapping("issues")
public String issues(@ModelAttribute Page page, Model model)
throws Exception {
page = plmIssueManager.pagedQuery(
"from PlmIssue order by createTime desc", page.getPageNo(),
page.getPageSize());
model.addAttribute("page", page);
return "plm/issues";
}
/**
* Generates a fake incident report to test for errorCallback
*
* @return ModelAndView model and view
*/
@RequestMapping(method = RequestMethod.POST, params = "methodToCall=errorCheck")
public ModelAndView errorCheck(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
if (true) {
throw new RuntimeException("Generate fake incident report");
}
return getModelAndView(form);
}
@RequestMapping(value="/upload.do")
public String firmwareUpload(@ModelAttribute("parameterVO") ParameterVO po,
HttpServletRequest request,
Locale locale,
ModelMap model)
throws Exception {
HttpSession session = request.getSession(false);
if(session != null){
//페이지 권한 확인
GroupAuthorization requestAuth = (GroupAuthorization) session.getAttribute("requestAuth");
if(!requestAuth.getAuthorizationDBRead().equals("1")){
model.addAttribute("authMessage", "사용자관리 메뉴는 읽기 권한이 없습니다.");
return "forward:" + HeritProperties.getProperty("Globals.MainPage");
}
}
/* String deviceModel = po.getDeviceModel();
String[] tokens = deviceModel.split("\\|");
if (tokens.length == 2) {
po.setOui(tokens[0]);
po.setModelName(tokens[1]);
}
*/
HashMap param = new HashMap<String, Object>();
int page = StringUtil.parseInt(request.getParameter("page"), 1);
PagingUtil resultPagingUtil = firmwareService.getFirmwareListPaging(page, 0, po);
List deviceModelList = deviceService.getDeviceModelListByDeviceType("TR-069");
/**
* 데이터 셋팅
*/
model.addAttribute("page", page);
model.addAttribute("param", po);
model.addAttribute("deviceModelList", deviceModelList);
model.addAttribute("resultPagingUtil", resultPagingUtil);
return "/v2/firmware/upload";
}
@RequestMapping(value="/search-booking-get", method=RequestMethod.POST)
public String searchBookingSubmit(@ModelAttribute UIData uiData, Model model) {
Long id = new Long(uiData.getBookingid());
BookingRecord booking = bookingClient.getForObject("http://book-apigateway/api/booking/get/"+id, BookingRecord.class);
Flight flight = new Flight(booking.getFlightNumber(), booking.getOrigin(),booking.getDestination()
,booking.getFlightDate(),new Fares(booking.getFare(),"AED"));
Passenger pax = booking.getPassengers().iterator().next();
Passenger paxUI = new Passenger(pax.getFirstName(),pax.getLastName(),pax.getGender(),null);
uiData.setPassenger(paxUI);
uiData.setSelectedFlight(flight);
uiData.setBookingid(id.toString());
model.addAttribute("uidata", uiData);
return "bookingsearch";
}
@ResponseBody
@RequestMapping(value = "/doAdd")
public String doAdd(@ModelAttribute("workerInfo") WorkerInfo workerInfo) {
Boolean isSuccess = workerService.insert(workerInfo);
if (isSuccess) {
AuditLogUtils.saveAuditLog(getAuditLogInfo(workerInfo, "001002003", AuditLogOperType.insert.getValue()));
return "success";
} else {
return "fail";
}
}
@GetMapping("/changePassword")
public String changePassword(@ModelAttribute ChangePasswordCommand changePasswordCommand, Model model) {
if (webSecurityUtil.isUsersFirstLogin()) {
webMessageUtil.addWarnMsg(model, "user.changePassword.firstLogin");
}
return CHANGE_PASSWORD_PAGE;
}
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public ModelAndView editEmployee(@ModelAttribute @Valid Employee employee, BindingResult result,
@PathVariable String id, final RedirectAttributes redirectAttributes) throws EmployeeNotFound {
if (result.hasErrors())
return new ModelAndView("employee-edit");
ModelAndView mav = new ModelAndView("redirect:/admin/employee/list");
String message = "Employee was successfully updated.";
eService.changeEmployee(employee);
redirectAttributes.addFlashAttribute("message", message);
return mav;
}
@PostMapping(value = "/job-launcher")
public RedirectView launchJob(@ModelAttribute("jobLauncher") final JobLauncherModel jobLauncherModel,
final BindingResult bindingResult,
final HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
this.validator.validate(jobLauncherModel, bindingResult);
final RedirectView redirectView;
final String jobName = jobLauncherModel.getJobName();
final String applicationInstanceId = jobLauncherModel.getApplicationInstanceId();
if (bindingResult.hasErrors()) {
redirectAttributes.addFlashAttribute("jobLauncher", jobLauncherModel);
redirectAttributes.addFlashAttribute(BindingResult.MODEL_KEY_PREFIX + "jobLauncher", bindingResult);
redirectView = this.createRedirectView(
"job-launcher?job-name=" + jobName
+ "&application-instance-id=" + applicationInstanceId,
request);
} else {
this.jobLauncherFeService.launchJob(jobLauncherModel);
redirectView = this.createRedirectView(
"batch-job-executions?job-name=" + jobName + "&application-instance-id=" + applicationInstanceId,
request);
}
return redirectView;
}
@RequestMapping(method = RequestMethod.POST)
public String save(
@Valid @ModelAttribute("form") SetupForm form,
BindingResult result,
RedirectAttributes redirectAttributes) {
Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
if (blog != null) {
throw new HttpForbiddenException();
}
if (result.hasErrors()) {
return "setup";
}
setupService.setup(form.buildSetupRequest());
return "redirect:/_admin/login";
}
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
FieldError error = errors.getFieldError("age");
assertNotNull("Must have field error for age property", error);
assertEquals("value2", error.getRejectedValue());
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
如果文章对你有帮助,欢迎点击上方按钮打赏作者