下面列出了org.springframework.web.bind.annotation.ExceptionHandler#org.springframework.ui.Model 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequestMapping(method = RequestMethod.GET, value = "{registrationProtocol}")
public String edit(Model model, @PathVariable RegistrationProtocol registrationProtocol, @ModelAttribute RegistrationProtocolBean bean) {
try {
bean.setCode(registrationProtocol.getCode());
bean.setDescription(registrationProtocol.getDescription());
bean.setEnrolmentByStudentAllowed(registrationProtocol.getEnrolmentByStudentAllowed());
bean.setPayGratuity(registrationProtocol.getPayGratuity());
bean.setAllowsIDCard(registrationProtocol.getAllowsIDCard());
bean.setOnlyAllowedDegreeEnrolment(registrationProtocol.getOnlyAllowedDegreeEnrolment());
bean.setAlien(registrationProtocol.getAlien());
bean.setExempted(registrationProtocol.getExempted());
bean.setMobility(registrationProtocol.getMobility());
bean.setMilitary(registrationProtocol.getMilitary());
bean.setForOfficialMobilityReporting(registrationProtocol.getForOfficialMobilityReporting());
bean.setAttemptAlmaMatterFromPrecedent(registrationProtocol.getAttemptAlmaMatterFromPrecedent());
model.addAttribute("bean", bean);
return view("edit");
} catch (DomainException de) {
model.addAttribute("error", de.getLocalizedMessage());
return redirectHome();
}
}
/**
* 詳細画面
*
* @param userId
* @param model
* @return
*/
@GetMapping("/show/{userId}")
public String showUser(@PathVariable Long userId, Model model) {
// 1件取得する
val user = userService.findById(userId);
model.addAttribute("user", user);
if (user.getUploadFile() != null) {
// 添付ファイルを取得する
val uploadFile = user.getUploadFile();
// Base64デコードして解凍する
val base64data = uploadFile.getContent().toBase64();
val sb = new StringBuilder().append("data:image/png;base64,").append(base64data);
model.addAttribute("image", sb.toString());
}
return "modules/users/users/show";
}
/**
* 函数功能说明 : 进入后台登陆页面.
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping("/login")
public String login(HttpServletRequest req, Model model) {
String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
String error = null;
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if (PermissionException.class.getName().equals(exceptionClassName)) {
error = "网络异常,请联系龙果管理员";
} else if (exceptionClassName != null) {
error = "错误提示:" + exceptionClassName;
}
model.addAttribute("message", error);
return "system/login";
}
@RequestMapping(value = "/student/training-history", method = RequestMethod.GET)
public String trainingHistory(Model model, HttpServletRequest request, @RequestParam(value="page",required=false,defaultValue="1") int page) {
UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext()
.getAuthentication()
.getPrincipal();
Page<Training> pageModel = new Page<Training>();
pageModel.setPageNo(page);
pageModel.setPageSize(10);
List<Training> trainingList = trainingService.getTrainingList(pageModel);
Map<Integer,List<TrainingSectionProcess>> processMap = trainingService.getTrainingSectionProcessMapByUserId(userInfo.getUserid());
String pageStr = PagingUtil.getPageBtnlink(page,
pageModel.getTotalPage());
model.addAttribute("trainingList", trainingList);
model.addAttribute("processMap", processMap);
model.addAttribute("pageStr", pageStr);
return "training-history";
}
@RequestMapping(value = "/dependstatistic", method = RequestMethod.GET)
public String PerformancePage(Model model,
@RequestParam(value = "daytime", required = false) Integer daytime) {
//校验参数
if (daytime == null) {
daytime = 0;
}
//list
List<String> timelist = DateTimeHelper.getDateTimeListForPage(fieryConfig.getKeepdataday());
model.addAttribute("datelist", timelist);
model.addAttribute("datelist_selected", daytime);
Map<String, Map<String, String>> performList = logApi.getPerformList(daytime);
model.addAttribute("perfomancelist", performList);
return "dependstatistic";
}
@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();
}
}
@Override
public Object resolveArgumentValue(
MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {
Class<?> type = parameter.getParameterType();
if (Model.class.isAssignableFrom(type)) {
return context.getModel();
}
else if (Map.class.isAssignableFrom(type)) {
return context.getModel().asMap();
}
else {
// Should never happen..
throw new IllegalStateException("Unexpected method parameter type: " + type);
}
}
@GetMapping(value = "/server-scheduler-configuration", params = {"init-add-configuration"})
public void initSchedulerConfigurationAdd(
final Model model,
@RequestParam(name = "application") final String applicationName) {
final ServerSchedulerConfigurationModel configuration;
if (model.containsAttribute("schedulerConfiguration")) {
configuration = (ServerSchedulerConfigurationModel) model.asMap().get("schedulerConfiguration");
} else {
configuration = new ServerSchedulerConfigurationModel();
}
configuration.setApplicationName(applicationName);
final ApplicationContextModel applicationContextModel = this.getApplicationContextModel(applicationName);
model.addAttribute("schedulerConfiguration", configuration);
model.addAttribute("modificationType", new ModificationTypeModel(ModificationTypeModel.ModificationType.ADD));
model.addAttribute("applicationContextModel", applicationContextModel);
model.addAttribute("schedulerStatus", ServerSchedulerConfigurationStatusModel.ServerSchedulerConfigurationStatusType.values());
model.addAttribute("booleanSelector", BooleanModel.values());
}
/**
* 一覧画面 初期表示
*
* @param model
* @return
*/
@GetMapping("/find")
public String findCodeCategory(@ModelAttribute("searchCodeCategoryForm") SearchCodeCategoryForm form, Model model) {
// 入力値から検索条件を作成する
val criteria = modelMapper.map(form, CodeCategoryCriteria.class);
// 10件区切りで取得する
val pages = codeCategoryService.findAll(criteria, form);
// 画面に検索結果を渡す
model.addAttribute("pages", pages);
// カテゴリ分類一覧
val codeCategories = codeHelper.getCodeCategories();
model.addAttribute("codeCategories", codeCategories);
return "modules/system/code_categories/find";
}
@RequestMapping("help-center/{cid}")
public String helpCenterArticleCategory(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size, @PathVariable String cid, Model model) {
List<Order> orders = new ArrayList<Order>();
orders.add(new Order(Direction.ASC, "order"));
orders.add(new Order(Direction.DESC, "updateTime"));
Pageable pageable = new PageRequest(page, size, new Sort(orders));
Page<Article> dataBox = articleService.find(cid, pageable);
if (dataBox.getContent().size() == 1) {
return "redirect:/help-center/" + cid + "/" + dataBox.getContent().get(0).getId();
} else {
List<ArticleCategory> articleCategorys = articleCategoryRepository.findByLevel("二级");
for (ArticleCategory a : articleCategorys) {
if (OTHER_KIND_LEVEL.equals(a.getCode())) {
articleCategorys.remove(a);
break;
}
}
model.addAttribute("nav",HomeNav.HELP );
model.addAttribute("second", articleCategorys);
model.addAttribute("sel", articleCategoryRepository.findOne(cid));
model.addAttribute("aeli", dataBox);
return "cms/template_li";
}
}
@RequestMapping(value="/confirm", method=RequestMethod.POST)
public String ConfirmBooking(@ModelAttribute UIData uiData, Model model) {
Flight flight= uiData.getSelectedFlight();
BookingRecord booking = new BookingRecord(flight.getFlightNumber(),flight.getOrigin(),
flight.getDestination(), flight.getFlightDate(),null,
flight.getFares().getFare());
Set<Passenger> passengers = new HashSet<Passenger>();
Passenger pax = uiData.getPassenger();
pax.setBookingRecord(booking);
passengers.add(uiData.getPassenger());
booking.setPassengers(passengers);
long bookingId =0;
try {
//long bookingId = bookingClient.postForObject("http://book-service/booking/create", booking, long.class);
bookingId = bookingClient.postForObject("http://book-apigateway/api/booking/create", booking, long.class);
logger.info("Booking created "+ bookingId);
}catch (Exception e){
logger.error("BOOKING SERVICE NOT AVAILABLE...!!!");
}
model.addAttribute("message", "Your Booking is confirmed. Reference Number is "+ bookingId);
return "confirm";
}
@RequestMapping(value = "checkCode.do", method = {RequestMethod.POST, RequestMethod.GET})
public Map checkPhone(HttpServletRequest request, Model model,
@RequestParam String code, @RequestParam String token) {
Map<String, Integer> map = new HashMap<>();
String name = request.getParameter("name");
if (!StringUtils.getInstance().isNullOrEmpty(name)) {
request.getSession().setAttribute("name", name);
}
String checkCodeToken = (String) request.getSession().getAttribute("token");
if (StringUtils.getInstance().isNullOrEmpty(checkCodeToken) || !checkCodeToken.equals(token)) {
map.put("result", 0);
return map;
}
//验证码错误
if (!checkCodePhone(code, request)) {
map.put("result", 0);
return map;
}
map.put("result", 1);
return map;
}
@GetMapping("reset_password")
public String resetPasswordForm(
@RequestParam String name,
@RequestParam String email,
@RequestParam String token,
Model model) {
Optional<Account> optionalAcct = Optional.ofNullable(accountService.accountByNameEmail(name, email).getContent());
if(optionalAcct.isPresent()) {
Account acct = optionalAcct.get();
if(acct.getPassword().equals(token)) {
model.addAttribute("acct", acct);
model.addAttribute("token", token);
return RESET_PASSWORD_FORM_PATH;
}
}
return REDIRECT_INDEX_PATH;
}
/**
* Updates node of the cluster.
*
* @param path
* @param cluster
* @param data
* @param model
* @return
* @throws ShepherException
*/
@Auth(Jurisdiction.TEAM_MEMBER)
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@RequestParam("path") String path,
@PathVariable("cluster") String cluster,
@RequestParam(value = "data") String data,
@RequestParam(value = "srcPath", defaultValue = "/") String srcPath,
@RequestParam(value = "srcCluster", defaultValue = "") String srcCluster,
Model model)
throws ShepherException {
String tempData = data;
if (!("/".equals(srcPath)) && !("".equals(srcCluster))) {
tempData = nodeService.getData(srcCluster, srcPath);
}
User user = userHolder.getUser();
if (ClusterUtil.isPublicCluster(cluster)) {
nodeService.update(cluster, path, tempData, user.getName());
return "redirect:/clusters/" + cluster + "/nodes?path=" + ParamUtils.encodeUrl(path);
}
long reviewId = reviewService.create(cluster, path, tempData, user, Action.UPDATE, ReviewStatus.NEW);
return "redirect:/reviews/" + reviewId;
}
@OperationLog("激活注册账号")
@GetMapping("/active/{token}")
public String active(@PathVariable("token") String token, Model model) {
User user = userService.selectByActiveCode(token);
String msg;
if (user == null) {
msg = "请求异常, 激活地址不存在!";
} else if ("1".equals(user.getStatus())) {
msg = "用户已激活, 请勿重复激活!";
} else {
msg = "激活成功!";
user.setStatus("1");
userService.activeUserByUserId(user.getUserId());
}
model.addAttribute("msg", msg);
return "active";
}
/***
* 重置操作员的密码(注意:不是修改当前登录操作员自己的密码) .
*
* @return
*/
@RequiresPermissions("pms:operator:resetpwd")
@RequestMapping("/resetPwdUI")
public String resetOperatorPwdUI(HttpServletRequest req, Long id, Model model) {
PmsOperator operator = pmsOperatorService.getDataById(id);
if (operator == null) {
return operateError("无法获取要重置的信息", model);
}
// 普通操作员没有修改超级管理员的权限
if ("USER".equals(this.getPmsOperator().getType()) && "ADMIN".equals(operator.getType())) {
return operateError("权限不足", model);
}
model.addAttribute("operator", operator);
return "pms/pmsOperatorResetPwd";
}
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
logger.error("Exception during execution of SpringSecurity application", throwable);
StringBuffer sb = new StringBuffer();
sb.append("Exception during execution of Spring Security application! ");
sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));
if (throwable != null && throwable.getCause() != null) {
sb.append(" root cause: ").append(throwable.getCause());
}
model.addAttribute("error", sb.toString());
ModelAndView mav = new ModelAndView();
mav.addObject("error", sb.toString());
mav.setViewName("error");
return mav;
}
/**
* GET Displays create cluster form.
*/
@RequestMapping(path = "/create", method = RequestMethod.GET)
public String createClusterForm(final ClusterForm clusterForm, final Model model) {
// Setup breadcrumbs
setupBreadCrumbs(model, "Create", "/configuration/cluster/create");
return "configuration/cluster/create";
}
@RequestMapping(method=RequestMethod.GET)
public String initForm(Model model){
Biography bio = new Biography();
Education educ = new Education();
Personal personForm = new Personal();
personForm.setBiography(bio);
personForm.setEducation(educ);
references(model);
model.addAttribute("personForm", personForm);
return "personal_update";
}
@PostMapping("forgot")
public String forgot(
@RequestParam String name,
@RequestParam String email,
Model model) {
Optional<Account> optionalAcct = userService.accountByNameEmail(name, email);
if(optionalAcct.isPresent()) {
emailService.passwordResetLink(optionalAcct.get());
}
model.addAttribute("email", email);
return FORGOT_PATH;
}
@GetMapping
public String getCourses(Model model, @PathVariable Department department, @RequestParam(value = "all", required = false) Boolean all) {
ErrorUtils.requireNonNullDepartment(department);
// Determine if only active courses have to be should
boolean active = !(all != null && all);
model.addAttribute("page_description", "View and manage courses for the Department");
model.addAttribute("department", department);
model.addAttribute("page_title", "Courses : " + department.getName() + " Department");
model.addAttribute("page_subtitle", "Course Management");
model.addAttribute("page_path", getPath(department));
model.addAttribute("all", !active);
List<FloatedCourse> floatedCourses = floatedCourseService.getCurrentFloatedCourses(department);
List<Course> courses = courseService.getAllActiveCourse(department, active);
// Add meta tag and no of registrations to each course
for (FloatedCourse floatedCourse : floatedCourses) {
Stream.of(floatedCourse)
.map(FloatedCourse::getCourse)
.map(courses::indexOf)
.filter(index -> index != -1)
.map(courses::get)
.findFirst()
.ifPresent(course -> {
course.setMeta("Floated");
course.setRegistrations(floatedCourse.getCourseRegistrations().size());
});
}
SortUtils.sortCourses(courses);
model.addAttribute("courses", courses);
return "department/courses";
}
@RequestMapping(value="/register", method=RequestMethod.POST)
public String register(Model model,
@RequestParam("j_username")String username,
@RequestParam("j_password")String password1,
@RequestParam("j_password2")String password2
) {
if (username == null || username.isEmpty()) {
return registrationError("username cannot be emtpy", model);
}
boolean existing = m_tweetRepository.getPassword(username) != null;
if (existing) {
return registrationError("user " + username + " already exists!", model);
}
if (password1 == null) {
return registrationError("Password cannot be null", model);
}
if (!password1.equals(password2)) {
return registrationError("Password1 and Password2 must match", model);
}
m_tweetRepository.saveUser(username, password1);
UserDetails userDetails = m_userManager.loadUserByUsername(username);
Authentication auth = new UsernamePasswordAuthenticationToken (userDetails.getUsername (),userDetails.getPassword (),userDetails.getAuthorities ());
SecurityContextHolder.getContext().setAuthentication(auth);
return "redirect:/";
}
/**
* 试题导入页面
*
* @param model
* @return
*/
@RequestMapping(value = "/teacher/question/question-import", method = RequestMethod.GET)
public String questionImportPage(Model model) {
List<Field> fieldList = questionService.getAllField(null);
model.addAttribute("fieldList", fieldList);
return "question-import";
}
@RequestMapping(method = RequestMethod.GET, value = "/", params = "flogin", produces = "text/html")
public String forgotLoginGet(Model uiModel,HttpServletRequest httpServletRequest) {
try {
uiModel.addAttribute("status", "N");
return "public/flogin";
} catch (Exception e) {
log.error(e.getMessage(),e);
throw (new RuntimeException(e));
}
}
/**
* 通过appId返回RedisStandalone实例信息
*
* @param appId
*/
@RequestMapping(value = "/redis/standalone/{appId}.json")
public void getStandaloneAppById(HttpServletRequest request, @PathVariable long appId, Model model) {
if (!handleRedisApp(appId, request, model, ConstUtils.CACHE_REDIS_STANDALONE, false)) {
return;
}
getRedisStandaloneInfo(request, appId, model);
}
/**
* 多命令
* @param appId
* @param statName
* @return
* @throws ParseException
*/
@RequestMapping("/getMutiStatAppStats")
public ModelAndView getMutiStatAppStats(HttpServletRequest request,
HttpServletResponse response, Model model, Long appId) throws ParseException {
String statNames = request.getParameter("statName");
List<String> statNameList = Arrays.asList(statNames.split(ConstUtils.COMMA));
TimeBetween timeBetween = getJsonTimeBetween(request);
List<AppStats> appStats = appStatsCenter.getAppStatsList(appId, timeBetween.getStartTime(), timeBetween.getEndTime(), TimeDimensionalityEnum.MINUTE);
String result = assembleMutiStatAppStatsJsonMinute(appStats, statNameList, timeBetween.getStartDate());
model.addAttribute("data", result);
return new ModelAndView("");
}
@RequestMapping(value = "create", method = RequestMethod.POST)
public String create(@Valid Test newTest, BindingResult result, Model model,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
model.addAttribute("action", "create");
return "test/testForm";
}
service.saveTest(newTest);
redirectAttributes.addFlashAttribute("message", "创建任务成功");
return "redirect:/test/";
}
@GetMapping("user/{username}")
public String user(
@PathVariable("username") String username,
Model model) {
model.addAttribute("username", username);
if(userService.userExisted(username)) {
List<Message> messages = userService.messages(username);
model.addAttribute("messages", messages);
} else {
model.addAttribute("errors", Arrays.asList(String.format("%s 還沒有發表訊息", username)));
}
return USER_PATH;
}
@RequestMapping(method=RequestMethod.GET)
public String initForm(Model model, HttpServletRequest req){
LoginForm adminLoginForm = new LoginForm();
model.addAttribute("adminLoginForm", adminLoginForm);
return "admin_login_form";
}
@RequestMapping("stamp-info-list")
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 = stampInfoManager.pagedQuery(page, propertyFilters);
model.addAttribute("page", page);
return "stamp/stamp-info-list";
}