Java Code Examples for org.springframework.web.servlet.ModelAndView#addObject()

The following examples show how to use org.springframework.web.servlet.ModelAndView#addObject() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: console   File: ConsoleUserController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping("/getConsoleUserById")
// 通过id查找用户
public ModelAndView getConsoleUserById(HttpServletRequest request) {
    int userId = Integer.parseInt(request.getParameter("userId"));
    ConsoleUser user = consoleUserService.getUserById(userId);
    List<ConsoleUserRole> list = CosoleUserRoleService.getConsoleUserRoleByUserId(userId);
    int[] userRole = new int[list.size()];
    for (int i = 0; i < list.size(); i++) {
        userRole[i] = list.get(i).getRoleId();
    }
    ConsoleRoleExample example = new ConsoleRoleExample();
    example.createCriteria();
    List<ConsoleRole> roleList = ConsoleRoleService.getAllConsoleRole(example);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("consoleuser/console_user_detail");
    if (list.size() > 0) {
        modelAndView.addObject("userRole", userRole);
    }
    modelAndView.addObject("roleList", roleList);
    modelAndView.addObject("user", user);
    return modelAndView;
}
 
Example 2
/**
 * 已抓取的网页列表
 *
 * @param query  查询词
 * @param domain 域名
 * @param page   页码
 * @return
 */
@RequestMapping(value = {"list", ""}, method = RequestMethod.GET)
public ModelAndView list(@RequestParam(required = false) String query, @RequestParam(required = false) String domain, @RequestParam(defaultValue = "1", required = false) int page) {
    ModelAndView modelAndView = new ModelAndView("panel/commons/list");
    modelAndView.addObject("query", query);
    modelAndView.addObject("page", page);
    modelAndView.addObject("domain", domain);
    if (StringUtils.isNotBlank(query)) {
        modelAndView.addObject("resultBundle", commonWebpageService.searchByQuery(query, 10, page).getResultList());
    } else if (StringUtils.isNotBlank(domain)) {
        modelAndView.addObject("resultBundle", commonWebpageService.getWebpageByDomain(domain, 10, page).getResultList());
    } else {
        modelAndView.addObject("resultBundle", commonWebpageService.listAll(10, page).getResultList());
    }
    return modelAndView;
}
 
Example 3
@RequestMapping(value = "/users/{userName}", method = RequestMethod.GET)
@Override
public ModelAndView detail(@PathVariable String userName, HttpServletRequest request, HttpServletResponse response) {
	ModelAndView mv = new ModelAndView();
	QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
	userQueryWrapper.eq("user_name", userName);
	UserDTO userDTO = userService.getOne(userQueryWrapper);
	if (userDTO == null) {
		throw new UserException(UserErrorCodeEnum.INVALIDATE_USER);
	}
	Integer pageNumber = 1;
	try {
		pageNumber = Integer.valueOf(request.getParameter("pageNumber"));
	} catch (NumberFormatException e) {
		pageNumber = 1;
	}
	QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
	postQueryWrapper.eq("user_id", userDTO.getUserId());
	postQueryWrapper.orderByDesc("create_date");
	Page<PostDTO> postDTOPage = postService.page(Integer.valueOf(pageNumber), 25, postQueryWrapper);
	Page<PostVO> postVOPage = postDTOPage2PostVOPage(postDTOPage);
	mv.setViewName(this.getJspPrefix() + "/detail");
	mv.addObject("userVO", getDTO2VO().apply(userDTO));
	mv.addObject("postVOPage", postVOPage);
	return mv;
}
 
Example 4
private ModelAndView retrieveUserList(HttpServletRequest req)
{
 List<AppUser> users = this.frameworkContext.getMetaDb().retrieveAllUsers();
 AppUser appUser = retrieveAppUser(req);

 ResultList rs = new ResultList();
 ColumnDescriptor desc = new ColumnDescriptor();
 desc.addColumn("USERNAME", false, 1);
 rs.setColumnDescriptor(desc);

 for(AppUser u : users)
 {
  if(appUser.getName().equals(u.getName()))
	  continue;
  ResultRow row = new ResultRow();
  row.setColumnDescriptor(desc);
  row.addColumn(u.getName());
  rs.addRow(row);
 }
 ModelAndView mv = new ModelAndView(this.jsonView);
 mv.addObject("json_result", ResultListUtil.toJSONString(rs, null, 0, "OK"));
 return mv;
}
 
Example 5
Source Project: EasyHousing   File: AdminController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value="adminLogin.do", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView login(Administrator u, HttpSession httpSession) {
	ModelAndView modelAndView = new ModelAndView();
	
	//没有输入
	if (u.getAdministratorName() == null && u.getAdministratorPassword() == null) {
		modelAndView.setViewName("logIn");
		return modelAndView;
	}
	//查看用户是否存在
	Administrator adminuser = administratorDao.selectAdministrator(u);
	if (adminuser == null) {
		modelAndView.addObject("message", "登录失败,用户名或密码错误!");
		modelAndView.setViewName("logIn");
	}
	else {
		//modelAndView.addObject("message", ");
		httpSession.setAttribute("adminuser", adminuser);
		modelAndView.setViewName("SystemUser/homepage");
	}
	return modelAndView;
}
 
Example 6
@GetMapping("{id}")
/**
 * @Description: 产品展示页
 * @Param: [id]
 * @return: org.springframework.web.servlet.ModelAndView
 * @Author: longzhonghua
 * @Date: 2019/4/12
 */
public ModelAndView showProduct(@PathVariable("id") long id)  throws  Exception{
    Product product = productRepository.findByid(id);
    ModelAndView mav = new ModelAndView("web/shop/show");
    //产品信息
    mav.addObject("product", product);
    //获取登录用户信息
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    mav.addObject("principals", principal);
    System.out.println(principal.toString());
    return mav;
}
 
Example 7
/**
 * 读取启动流程的表单字段
 */
@RequestMapping(value = "getform/start/{processDefinitionId}")
public ModelAndView readStartForm(@PathVariable("processDefinitionId") String processDefinitionId) throws Exception {
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
    boolean hasStartFormKey = processDefinition.hasStartFormKey();

    // 根据是否有formkey属性判断使用哪个展示层
    String viewName = "chapter6/start-process-form";
    ModelAndView mav = new ModelAndView(viewName);

    // 判断是否有formkey属性
    if (hasStartFormKey) {
        Object renderedStartForm = formService.getRenderedStartForm(processDefinitionId);
        mav.addObject("startFormData", renderedStartForm);
        mav.addObject("processDefinition", processDefinition);
    } else { // 动态表单字段
        StartFormData startFormData = formService.getStartFormData(processDefinitionId);
        mav.addObject("startFormData", startFormData);
    }
    mav.addObject("hasStartFormKey", hasStartFormKey);
    mav.addObject("processDefinitionId", processDefinitionId);
    return mav;
}
 
Example 8
Source Project: mumu   File: DefaultExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 没有权限 异常
 * <p/>
 * 后续根据不同的需求定制即可
 */
@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
    ModelAndView mv = new ModelAndView();
    mv.addObject("exception", e);
    mv.setViewName("unauthorized");
    return mv;
}
 
Example 9
Source Project: DataLink   File: MenuController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/toEdit")
public ModelAndView toEdit(HttpServletRequest request) {
    String id = request.getParameter("id");
    MenuInfo menuInfo = new MenuInfo();
    ModelAndView mav = new ModelAndView("menu/edit");
    List<MenuInfo> menuList = menuService.getList();
    if (StringUtils.isNotBlank(id)) {
        menuInfo = menuService.getById(Long.valueOf(id));
    }
    mav.addObject("menuInfo", menuInfo);
    mav.addObject("menuList", menuList);
    mav.addObject("menuTypeList", MenuType.getAllMenuTypes());
    return mav;
}
 
Example 10
Source Project: DataLink   File: HBaseTaskController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/toUpdateHbaseTask")
public ModelAndView toUpdateHbaseTask(Long id) {
    ModelAndView mav = new ModelAndView("task/hbaseTaskUpdate");
    TaskInfo taskInfo = taskService.getTask(id);
    Map<String, PluginWriterParameter> writerParameterMap = getWriterParameters();
    taskInfo.getTaskWriterParameterObjs().forEach(i -> writerParameterMap.put(i.getPluginName(), i));
    HBaseTaskModel hbaseTaskModel = new HBaseTaskModel(
            new TaskModel.TaskBasicInfo(
                    id,
                    taskInfo.getTaskName(),
                    taskInfo.getTaskDesc(),
                    taskInfo.getTargetState(),
                    taskInfo.getGroupId()
            ),
            writerParameterMap,
            groupService.getAllGroups(),
            TargetState.getAllStates(),
            mediaService.getMediaSourcesByTypes(MediaSourceType.HBASE),
            buildZkMediaSources(),
            PluginWriterParameter.RetryMode.getAllModes(),
            RdbmsWriterParameter.SyncMode.getAllModes(),
            (HBaseReaderParameter) taskInfo.getTaskReaderParameterObj(),
            CommitMode.getAllCommitModes(),
            SerializeMode.getAllSerializeModes(),
            PartitionMode.getAllPartitionModes(),
            taskInfo.isLeaderTask() ? "1" : "0"
    );
    hbaseTaskModel.setCurrentWriters(taskInfo.getTaskWriterParameterObjs().stream().collect(Collectors.toMap(PluginWriterParameter::getPluginName, i -> "1")));
    mav.addObject("taskModel", hbaseTaskModel);
    return mav;
}
 
Example 11
private ModelAndView handleFetchSNMP(HttpServletRequest req,
		HttpServletResponse resp) {
	String dbgroup = req.getParameter("group");
	String host = req.getParameter("host");
	SNMPSettings.SNMPSetting snmpSetting = this.frameworkContext.getSnmpSettings().getHostSetting(dbgroup, host);
	ModelAndView mv = new ModelAndView(this.jsonView);
	String community = snmpSetting == null? SNMPSettings.SNMPSetting.DEFAULT_COMMUNITY: snmpSetting.getCommunity();
	String ver = snmpSetting == null? SNMPSettings.SNMPSetting.DEFAULT_VERSION: snmpSetting.getVersion();
	if(community == null || community.isEmpty())community = SNMPSettings.SNMPSetting.DEFAULT_COMMUNITY;
	if(ver == null || ver.isEmpty())ver = SNMPSettings.SNMPSetting.DEFAULT_VERSION;
	String enabled = snmpSetting == null? "yes":snmpSetting.getEnabled();
	StringBuilder sb = new StringBuilder();
	sb.append("{\"status\":0,\"message\":\"OK\", \"community\":\"").append(community)
	  .append("\",\"version\":\"").append(ver)
	  .append("\",\"enabled\":\"").append(enabled).append("\"");
	if("3".equals(ver))
	{
		if(snmpSetting.getUsername()!=null)
			sb.append(",\"username\":\"").append(snmpSetting.getUsername()).append("\"");
		if(snmpSetting.getAuthProtocol()!=null)
			sb.append(",\"authprotocol\":\"").append(snmpSetting.getAuthProtocol()).append("\"");
		if(snmpSetting.getPrivacyProtocol()!=null)
			sb.append(",\"privacyprotocol\":\"").append(snmpSetting.getPrivacyProtocol()).append("\"");
		if(snmpSetting.getContext()!=null)
			sb.append(",\"context\":\"").append(snmpSetting.getContext()).append("\"");
		//logger.info("Ommit pwd: "+snmpSetting.getPassword()+", "+snmpSetting.getPrivacyPassphrase());
	}
	sb.append("}");
    mv.addObject("json_result", sb.toString());
	return mv;
}
 
Example 12
@RequestMapping("/home")
public ModelAndView home(@SAMLUser SAMLUserDetails user) {
    ModelAndView homeView = new ModelAndView("home");
    homeView.addObject("userId", user.getUsername());
    homeView.addObject("samlAttributes", user.getAttributes());
    return homeView;
}
 
Example 13
@RequestMapping("/all")
public ModelAndView allProducts() {
	ModelAndView modelAndView = new ModelAndView();
	
	modelAndView.addObject("products", productService.getAllProducts());
	modelAndView.setViewName("products");
	return modelAndView;
}
 
Example 14
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String username = securityService.getCurrentUsername(request);

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }

    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> items = upload.parseRequest(request);

    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;

        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();

            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }

    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}
 
Example 15
Source Project: spring-boot-demo   File: IndexController.java    License: MIT License 5 votes vote down vote up
@GetMapping(value = {"", "/"})
public ModelAndView index(HttpServletRequest request) {
	ModelAndView mv = new ModelAndView();

	User user = (User) request.getSession().getAttribute("user");
	if (ObjectUtil.isNull(user)) {
		mv.setViewName("redirect:/user/login");
	} else {
		mv.setViewName("page/index");
		mv.addObject(user);
	}

	return mv;
}
 
Example 16
@GetMapping("/my")
public ModelAndView myEvents() {
    CalendarUser currentUser = userContext.getCurrentUser();
    Integer currentUserId = currentUser.getId();
    ModelAndView result = new ModelAndView("events/my", "events", calendarService.findForUser(currentUserId));
    result.addObject("currentUser", currentUser);
    return result;
}
 
Example 17
Source Project: OAuth-2.0-Cookbook   File: HomeController.java    License: MIT License 5 votes vote down vote up
@GetMapping("/resource")
public ModelAndView resource() {
    String result = restTemplate
            .getForObject("http://localhost:8080/api/read", String.class);

    ModelAndView mv = new ModelAndView("resource");
    mv.addObject("result", result);
    return mv;
}
 
Example 18
Source Project: MOOC   File: MainController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(value = {"index",""})
public ModelAndView index(ModelAndView mav) {
	List<Course> freecourses = courseBiz.freeCourse();
	List<Course> vipcourses = courseBiz.vipCourse();
	mav.addObject("freecourses", freecourses);
	mav.addObject("vipcourses", vipcourses);
	mav.setViewName("index");
	return mav;
}
 
Example 19
Source Project: activejpa   File: OwnerController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Custom handler for displaying an owner.
 *
 * @param ownerId the ID of the owner to display
 * @return a ModelMap with the model attributes for the view
 */
@RequestMapping("/owners/{ownerId}")
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
    ModelAndView mav = new ModelAndView("owners/ownerDetails");
    mav.addObject(this.clinicService.findOwnerById(ownerId));
    return mav;
}
 
Example 20
Source Project: SA47   File: ExtraController.java    License: The Unlicense 5 votes vote down vote up
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView listAll() {
	ArrayList<Course> clist = new ArrayList<Course>();
	ArrayList<Student> slist = new ArrayList<Student>();
	ArrayList<Enrolment> elist = new ArrayList<Enrolment>();
	ModelAndView mav = new ModelAndView("ExtraList");
	clist = eService.listCoursesTaughtByLecturer("S2345678E");
	slist = eService.listStudentsEnrolledForCourse(1);
	elist = eService.gradeCourse(5);
	mav.addObject("clist",clist);
	mav.addObject("slist",slist);
	mav.addObject("elist",elist);
	return mav;
}