Spring Framework ModelMap - top ranked examples from Open Source projects

These code examples were ranked by Codota’s semantic indexing as the best open source examples for Spring Framework ModelMap class.

This code example shows how to use the following methods:size, get, keySet
	@Override 
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
 
		ModelMap model = mavContainer.getModel();
		if (model.size() > 0) {
			int lastIndex = model.size()-1;
			String lastKey = new ArrayList<String>(model.keySet()).get(lastIndex);
			if (lastKey.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
				return model.get(lastKey);
			} 
		} 
 
		throw new IllegalStateException(
				"An Errors/BindingResult argument is expected to be declared immediately after the model attribute, " + 
				"the @RequestBody or the @RequestPart arguments to which they apply: " + parameter.getMethod());
	} 
 
} 
8
CodeRank
This code example shows how to use the following methods:get, put
        controller.setClientDetailsService(clientDetailsService);
        controller.setApprovalStore(Mockito.mock(ApprovalStore.class));
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setScheme("https");
        request.addHeader("Host", "foo");
        ModelMap model = new ModelMap();
        model.put("authorizationRequest", new AuthorizationRequest("client", null));
        Authentication auth = UaaAuthenticationTestFactory.getAuthentication("foo@bar.com", "Foo Bar", "foo@bar.com");
        controller.confirm(model, request, auth, new SimpleSessionStatus());
        Map<String, Object> options = (Map<String, Object>) ((Map<String, Object>) model.get("options")).get("confirm");
        assertEquals("https://foo/oauth/authorize", options.get("location"));
        assertEquals("/oauth/authorize", options.get("path"));
    } 
 
} 
7
CodeRank
This code example shows how to use the following methods:
		assertEquals(url + "/value1/v1/value2?key3=value3", this.response.getRedirectedUrl()); 
	} 
 
	@Test(expected=IllegalArgumentException.class) 
	public void uriTemplateNullValue() throws Exception { 
		new RedirectView("/{foo}").renderMergedOutputModel(new ModelMap(), this.request, this.response); 
	} 
 
	@Test 
	public void emptyRedirectString() throws Exception { 
		Map<String, Object> model = new HashMap<String, Object>(); 
 
		RedirectView redirectView = new RedirectView(""); 
		redirectView.renderMergedOutputModel(model, this.request, this.response); 
 
		assertEquals("", this.response.getRedirectedUrl()); 
	} 
 
	// SPR-9016 
 
7
CodeRank
This code example shows how to use the following methods:
		assertEquals(1, this.mavContainer.getModel().size());
	} 
 
	@Test
	public void getModelRedirectModel() { 
		ModelMap redirectModel = new ModelMap("name", "redirectValue");
		this.mavContainer.setRedirectModel(redirectModel);
		this.mavContainer.addAttribute("name", "value");
 
		assertEquals("Default model should be used if not in redirect scenario", 
				"value", this.mavContainer.getModel().get("name"));
 
		this.mavContainer.setRedirectModelScenario(true);
 
		assertEquals("Redirect model should be used in redirect scenario", 
				"redirectValue", this.mavContainer.getModel().get("name"));
	} 
 
	@Test
	public void getModelIgnoreDefaultModelOnRedirect() { 
7
CodeRank
This code example shows how to use the following methods:addAttribute
    @Autowired 
    ApprovalService approvalService;
 
    @RequestMapping(value="id-{id}/approve", method=RequestMethod.POST)
    public ModelMap approve(@PathVariable(value="id") Long id) throws Exception {
        ModelMap model = new ModelMap();
        Object result = approvalService.approve(id);
        if(result.toString().startsWith("Error")) {
            model.addAttribute("status", "error");
        } else { 
            model.addAttribute("status", "success");
        } 
        model.addAttribute("result", result);
        return model;
    } 
 
    @RequestMapping(value="id-{id}/reject", method=RequestMethod.POST)
    public ModelMap reject(@PathVariable(value="id") Long id) throws Exception {
        ModelMap model = new ModelMap();
        approvalService.reject(id);
6
CodeRank
This code example shows how to use the following methods:addAttribute, get
 
	// 直接调用方法需要把root参数保存至model中 
	@RequestMapping(value = "/file/v_list.do") 
	public String list(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		String root = (String) model.get("root");
		if (root == null) {
			root = RequestUtils.getQueryParam(request, "root");
		} 
		String valid=RequestUtils.getQueryParam(request, "valid");
		Boolean validB=null;
		if(StringUtils.isNotBlank(valid)){
			if(valid.equals("1")){
				validB=true;
			}else{ 
				validB=false;
			} 
		} 
		log.debug("list Resource root: {}", root);
		if (StringUtils.isBlank(root)) {

6
CodeRank
This code example shows how to use the following methods:
	} 
 
	@Test 
	public void handleMapReturnValue() throws Exception { 
		mavContainer.addAttribute("attr1", "value1"); 
		Map<String, Object> returnValue = new ModelMap("attr2", "value2"); 
 
		processor.handleReturnValue(returnValue , returnParamMap, mavContainer, webRequest); 
 
		assertEquals("value1", mavContainer.getModel().get("attr1")); 
		assertEquals("value2", mavContainer.getModel().get("attr2")); 
	} 
 
	@SuppressWarnings("unused") 
	private Map<String, Object> map(Map<String, Object> map) { 
		return null; 
	} 
 
} 
6
CodeRank
This code example shows how to use the following methods:
 * 
 * <p>This resolver must be listed ahead of 
 * {@link org.springframework.web.method.annotation.ModelMethodProcessor} and 
 * {@link org.springframework.web.method.annotation.MapMethodProcessor}, 
 * which support {@link Map} and {@link Model} arguments both of which are 
 * "super" types of {@code RedirectAttributes} and would also attempt to 
 * resolve a {@code RedirectAttributes} argument. 
 * 
 * @author Rossen Stoyanchev 
 * @since 3.1 
 */ 
public class RedirectAttributesMethodArgumentResolver implements HandlerMethodArgumentResolver {
 
	@Override 
	public boolean supportsParameter(MethodParameter parameter) {
		return RedirectAttributes.class.isAssignableFrom(parameter.getParameterType());
	} 
 
	@Override 
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
6
CodeRank
This code example shows how to use the following methods:addAttribute
 
	@RequestMapping("/common/v_image_area_select.do") 
	public String imageAreaSelect(String uploadBase, String imgSrcPath,
			Integer zoomWidth, Integer zoomHeight, Integer uploadNum,
			HttpServletRequest request, ModelMap model) {
		model.addAttribute("uploadBase", uploadBase);
		model.addAttribute("imgSrcPath", imgSrcPath);
		model.addAttribute("zoomWidth", zoomWidth);
		model.addAttribute("zoomHeight", zoomHeight);
		model.addAttribute("uploadNum", uploadNum);
		return IMAGE_SELECT_RESULT;
	} 
 
	@RequestMapping("/common/o_image_cut.do") 
	public String imageCut(String imgSrcPath, Integer imgTop, Integer imgLeft,
			Integer imgWidth, Integer imgHeight, Integer reMinWidth,
			Integer reMinHeight, Float imgScale, Integer uploadNum,
			HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		try { 
6
CodeRank
This code example shows how to use the following methods:
		UserFormController controller = new UserFormController(); 
		WebRequest request = new ServletWebRequest(new MockHttpServletRequest()); 
		User user = controller.formBackingObject(request, null); 
		user.addName(new PersonName("This", "is", "Test")); 
		user.getPerson().setGender("F"); 
		controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "Save User", "pass123", "pass123", null, 
		    null, null, new String[0], "true", user, new BindException(user, "user")); 
	} 
	 
} 
6
CodeRank
This code example shows how to use the following methods:addAttribute
		long freeMemoery = runtime.freeMemory();
		long totalMemory = runtime.totalMemory();
		long usedMemory = totalMemory - freeMemoery;
		long maxMemory = runtime.maxMemory();
		long useableMemory = maxMemory - totalMemory + freeMemoery;
		model.addAttribute("props", props);
		model.addAttribute("freeMemoery", freeMemoery);
		model.addAttribute("totalMemory", totalMemory);
		model.addAttribute("usedMemory", usedMemory);
		model.addAttribute("maxMemory", maxMemory);
		model.addAttribute("useableMemory", useableMemory);
		model.addAttribute("version", version);
		model.addAttribute("user", user);
		model.addAttribute("flowMap", cmsStatisticSvc.getWelcomeSiteFlowData(site.getId()));
		return "right"; 
	} 
 
	@Autowired 
	private CmsSiteMng cmsSiteMng;
	@Autowired 
6
CodeRank
This code example shows how to use the following methods:addAttribute
	public ModelMap getModel() {
		if (useDefaultModel()) { 
			return this.defaultModel;
		} 
		else { 
			return (this.redirectModel != null) ? this.redirectModel : new ModelMap();
		} 
	} 
 
	/** 
	 * Whether to use the default model or the redirect model. 
	 */ 
	private boolean useDefaultModel() { 
		return (!this.redirectModelScenario || (this.redirectModel == null && !this.ignoreDefaultModelOnRedirect));
	} 
 
	/** 
	 * Provide a separate model instance to use in a redirect scenario. 
	 * The provided additional model however is not used used unless 
	 * {@link #setRedirectModelScenario(boolean)} gets set to {@code true} to signal 

6
CodeRank
This code example shows how to use the following methods:get
		PatientDashboardGraphController controller = new PatientDashboardGraphController();
		 
		long firstObsDate = new GregorianCalendar(2006, Calendar.FEBRUARY, 9).getTimeInMillis();
		long secondObsDate = new GregorianCalendar(2006, Calendar.FEBRUARY, 10).getTimeInMillis();
		 
		ModelMap map = new ModelMap();
		controller.showGraphData(2, 1, map);
		PatientGraphData graph = (PatientGraphData) map.get("graph");
		String expectedData = String
		        .format(
		            "{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"name\":\"Some concept name\",\"normal\":{\"high\":null,\"low\":null},\"data\":[[%d,2.0],[%d,1.0]],\"units\":\"\"}", 
		            secondObsDate, firstObsDate);
		Assert.assertEquals(expectedData, graph.toString());
	} 
	 
	/** 
	 * Test the path of the form for rendering the json data 
	 *  
	 * @see {@link PatientDashboardGraphController#showGraphData(Integer, Integer, ModelMap)} 
	 */ 
6
CodeRank
This code example shows how to use the following methods:addAttribute
    @RequestMapping("/mobile/oauth2/authorize") 
    /** 
     * A simple login form without register button 
     */ 
    public String oauth2Authorize(ModelMap model) {
        model.addAttribute("release", env.get("release"));
        model.addAttribute("name", "The Upgrade");
        model.addAttribute("description", "The Upgrade brings together self trackers and personal data specialists in a unique platform to build the knowledge that will one day empower every human on earth to realize their full potential.");
        return "oauth2/Authorize"; 
    } 
 
 
    @RequestMapping("/mobile/authenticate") 
    /** 
     * A simple login form without register button 
     */ 
    public String authenticate(ModelMap model) {
        model.addAttribute("release", env.get("release"));
        return "mobile/authenticate"; 
    } 
6
CodeRank
This code example shows how to use the following methods:
@SuppressWarnings("serial") 
public class RedirectAttributesModelMap extends ModelMap implements RedirectAttributes {
 
	private final DataBinder dataBinder;
 
	private final ModelMap flashAttributes = new ModelMap();
 
	/** 
	 * Class constructor. 
	 * @param dataBinder used to format attribute values as Strings. 
	 */ 
	public RedirectAttributesModelMap(DataBinder dataBinder) {
		this.dataBinder = dataBinder;
	} 
 
	/** 
	 * Default constructor without a DataBinder. 
	 * Attribute values are converted to String via {@link #toString()}. 
	 */ 
	public RedirectAttributesModelMap() { 
6
CodeRank
This code example shows how to use the following methods:addAttribute
		return memberEdit(request, model);
	} 
 
	@RequestMapping("/config/v_login_edit.do") 
	public String loginEdit(HttpServletRequest request, ModelMap model) {
		model.addAttribute("configLogin", configMng.getConfigLogin());
		model.addAttribute("emailSender", configMng.getEmailSender());
		model.addAttribute("forgotPasswordTemplate", configMng.getForgotPasswordMessageTemplate());
		model.addAttribute("registerTemplate", configMng.getRegisterMessageTemplate());
		return "config/login_edit"; 
	} 
 
	@RequestMapping("/config/o_login_update.do") 
	public String loginUpdate(ConfigLogin configLogin,
			ConfigEmailSender emailSender, ConfigMessageTemplate msgTpl,
			HttpServletRequest request, ModelMap model) {
		configMng.updateOrSave(configLogin.getAttr());
		configMng.updateOrSave(emailSender.getAttr());
		configMng.updateOrSave(msgTpl.getAttr());
		model.addAttribute("message", "global.success");
6
CodeRank
This code example shows how to use the following methods:addAttribute
	/** 
	 * Return the underlying {@code ModelMap} instance (never {@code null}). 
	 */ 
	public ModelMap getModelMap() { 
		if (this.model == null) { 
			this.model = new ModelMap(); 
		} 
		return this.model; 
	} 
 
	/** 
	 * Return the model map. Never returns {@code null}. 
	 * To be called by application code for modifying the model. 
	 */ 
	public Map<String, Object> getModel() { 
		return getModelMap(); 
	} 
 
 
	/** 

6
CodeRank
This code example shows how to use the following methods:addAttribute
		 
		Writer stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);
		ex.printStackTrace(printWriter);
		 
		ModelMap model = new ModelMap();
		model.addAttribute("error", ex);
		model.addAttribute("stackTrace", stringWriter.toString());
		return new ModelAndView("/error", model);
	} 
	 
	@ExceptionHandler(Exception.class)
	public ModelAndView handleException(Exception ex) {
		logger.info("Catching: " + ex.getClass().getSimpleName());
		logger.error(ex.getMessage(), ex);
		return error(ex);
	} 
 
 
} 
6
CodeRank
This code example shows how to use the following methods:clear, get
	} 
 
	@SuppressWarnings("unchecked") 
	@Test
	public void testCreateFolderSaveAndGet() { 
		ModelMap model = new ModelMap();
		String path = "test2-path";
 
		// add folder 
		scriptController.addFolder(getTestUser(), "", path, model);
		// create 
		scriptController.createForm(getTestUser(), path, "test.com", "file-for-search.py", "jython", false,
						new RedirectAttributesModelMap(), model);
		FileEntry script = (FileEntry) model.get("file");
		scriptController.save(getTestUser(), script, null, "", false, model);
 
		// save another script 
		model.clear();
		script.setPath(script.getPath().replace("file-for-search", "new-file-for-search"));
		scriptController.save(getTestUser(), script, null, "", false, model);

5
CodeRank
This code example shows how to use the following methods:put
                       ModelMap map,
                       @RequestParam(value = "message", required = false) String message) throws Exception {
        CamelConnection conn = connectionFactory.getConnection();
        RouteOperations ops = conn.getRouteOperations(routeId);
        CamelBean route = conn.getRoute(routeId);
        map.put("route", route);
        map.put("message", message);
        map.put("processors", conn.getProcessors(routeId));
        map.put("xml", ops.dumpRouteAsXml());
        return "route"; 
    } 
 
    @RequestMapping("start") 
    public String start(@PathVariable("routeId") String routeId, ModelMap map) throws Exception {
        CamelConnection conn = connectionFactory.getConnection();
        RouteOperations routeOps = conn.getRouteOperations(routeId);
        routeOps.start();
        map.put("message", "ErrorHandler '" + routeId + "' started");
        return getRedirect(routeId);
    } 
5
CodeRank
This code example shows how to use the following methods:addAttribute
	} 
 
	private void putCommonData(CmsStatisticModel statisticModel,
			List<CmsStatistic> list, Integer year, Integer month, Integer day,
			ModelMap model) {
		model.addAttribute("list", list);
		model.addAttribute("total", getTotal(list));
		model.addAttribute("statisticModel", statisticModel.name());
		model.addAttribute("year", year);
		model.addAttribute("month", month);
		model.addAttribute("day", day);
	} 
 
	private Long getTotal(List<CmsStatistic> list) {
		return list.size() > 0 ? list.iterator().next().getTotal() : 0L;
	} 
 
	@Autowired 
	private ChannelMng channelMng;
	@Autowired 
6
CodeRank
This code example shows how to use the following methods:
	 */ 
	@Test
	@Verifies(value = "should not fail if not authenticated", method = "displayPage(ModelMap)") 
	public void displayPage_shouldNotFailIfNotAuthenticated() throws Exception {
		Context.logout();
		new PersonAttributeTypeListController().displayPage(new ModelMap());
	} 
	 
	/** 
	 * @see PersonAttributeTypeListController#displayPage(ModelMap) 
	 */ 
	@SuppressWarnings("unchecked") 
	@Test
	@Verifies(value = "should put all attribute types into map", method = "displayPage(ModelMap)") 
	public void displayPage_shouldPutAllAttributeTypesIntoMap() throws Exception {
		ModelMap map = new ModelMap();
		new PersonAttributeTypeListController().displayPage(map);
		List<PersonAttributeType> alltypes = (List<PersonAttributeType>) map.get("personAttributeTypeList");
		Assert.assertEquals(3, alltypes.size());
	} 
6
CodeRank
This code example shows how to use the following methods:addAttribute
		} 
	} 
	 
	@RequestMapping("/project/addUsers") 
	public void addUsers(long id, ModelMap modelMap, @RequestParam(defaultValue="1") int page) {
		modelMap.addAttribute("users", projectService.queryUsers(id, PageUtil.getOffset(page, LIMIT), LIMIT));
		modelMap.addAttribute("projUsers", projectService.queryProjUsers(id));
		modelMap.addAttribute("project", projectService.queryProject(id));
		 
		long recordCount = projectService.queryUserCount(id);
		modelMap.addAttribute("totalPages", PageUtil.pageCount(recordCount, LIMIT));
		modelMap.addAttribute("currentPage", page);
	} 
 
	@RequestMapping(value="/project/saveUser", method={RequestMethod.POST})
	public String saveUser(long projectId, long userId, String development, String test, 
			String build, String production, String admin, HttpSession session) {
		if(StringUtils.isBlank(development) && StringUtils.isBlank(test) && StringUtils.isBlank(build) &&
				StringUtils.isBlank(production) && StringUtils.isBlank(admin)) {
			session.setAttribute("message", "请选择用户角色");
6
CodeRank
This code example shows how to use the following methods:addAttribute
	private static final int LIMIT = 15;
	 
	@RequestMapping("/profile/{type}/{projectId}") 
	public String profile(@PathVariable("type") String type, @PathVariable("projectId") Long projectId, 
			Long moduleId, ModelMap modelMap, @RequestParam(defaultValue="1")int page) {
		modelMap.addAttribute("modules", moduleService.queryModules(projectId));
		modelMap.addAttribute("configs", configService.queryConfigs(projectId, moduleId, PageUtil.getOffset(page, LIMIT), LIMIT));
		modelMap.addAttribute("moduleId", moduleId);
		modelMap.addAttribute("project", projectService.queryProject(projectId));
		 
		long recordCount = configService.queryConfigCount(projectId, moduleId);
		modelMap.addAttribute("totalPages", PageUtil.pageCount(recordCount, LIMIT));
		modelMap.addAttribute("currentPage", page);
		 
		return "profile/" + type;
	} 
	 
	@RequestMapping("/profile/preview/{projectCode}/{type}") 
	public String preview(@PathVariable("type") String type, @PathVariable("projectCode") String projectCode, 
			Long projectId, ModelMap modelMap) {
6
CodeRank
This code example shows how to use the following methods:
	} 
 
	@Override 
	protected void postHandleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, ModelAndView modelAndView, Map<String, ?> pathVariables)
			throws Exception {
		exportCalendar(modelAndView.getModelMap(), pathVariables);
	} 
 
	private void exportCalendar(ModelMap model, Map<String, ?> pathVariables) {
		Integer year = getModelOrPathAttribute("year", model, pathVariables);
		Integer month = getModelOrPathAttribute("month", model, pathVariables);
 
		model.addAttribute("calendar", bankService.getCalendar(year, month));
	} 
} 

6
CodeRank
This code example shows how to use the following methods:put
    @RequestMapping("context/{camelId}") 
    public String showContext(@PathVariable("camelId") String camelId, ModelMap map) throws Exception {
 
        CamelConnection conn = connectionFactory.getConnection();
 
        map.put("camelId", camelId);
        map.put("routes", conn.getRoutes());
        map.put("consumers", conn.getConsumers());
        map.put("endpoints", conn.getEndpoints());
        map.put("errorhandlers", conn.getErrorHandlers());
 
        return "context"; 
    } 
} 
6
CodeRank
This code example shows how to use the following methods:
	} 
 
	@Override 
	protected void postHandleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, ModelAndView modelAndView, Map<String, ?> pathVariables)
			throws Exception {
		exportAccount(modelAndView.getModelMap(), pathVariables);
	} 
 
	private void exportAccount(ModelMap model, Map<String, ?> pathVariables) {
 
		String accountNumber = getModelOrPathAttribute("accountNumber", model, pathVariables);
		Assert.notNull(accountNumber, "accountNumber required");
 
		Account account = bankService.findAccountByNumberFetchCards(accountNumber);
		model.addAttribute("account", account);
	} 
} 

6
CodeRank
This code example shows how to use the following methods:put
	private BankService bankService;
 
	@RequestMapping("/admin.html") 
	public void admin(ModelMap model) {
 
		model.put("userCount", bankService.countUsers());
		model.put("accountCount", bankService.countAccounts());
		model.put("operationCount", bankService.countOperations());
	} 
} 
6
CodeRank
This code example shows how to use the following methods:
     * <p>Tests the {@link ErrorsProvider#canProvide(Class)} method when the provided resource is null.</p> 
     */ 
    @Test
    public void testCanProvideResourceNull() { 
 
        when(modelAndView.getModel()).thenReturn(new ModelMap());
 
        assertFalse("The provider incorrectly handles null values.", instance.canProvide(Errors.class));
    } 
 
    /** 
     * <p>Tests {@link ErrorsProvider#lookup(ArquillianResource, java.lang.annotation.Annotation...)} method.</p> 
     */ 
    @Test
    public void testLookup() { 
 
        assertNotNull("The returned resource instance was null.", instance.lookup(arquillianResource));
    } 
} 
5
CodeRank
This code example shows how to use the following methods:addAttribute
        } 
        ServiceClass serviceClass = ServiceClass.valueOf(serviceClassString);
        LocalDate departureDate = new LocalDate(departureDateString);
 
        if (StringUtils.hasLength(fromAirportCode) && StringUtils.hasLength(toAirportCode)) {
            model.addAttribute("from", fromAirportCode);
            model.addAttribute("to", toAirportCode);
            model.addAttribute("departureDate", departureDateString);
            model.addAttribute("serviceClass", serviceClassString);
            model.addAttribute("flights",
                    airlineService.getFlights(fromAirportCode, toAirportCode, departureDate, serviceClass));
        } 
        return "flights"; 
    } 
 
    @RequestMapping(value = "{id}") 
    public String singleFlight(@PathVariable("id") long id, ModelMap model) throws NoSuchFlightException {
        Flight flight = airlineService.getFlight(id);
        model.addAttribute(flight);
        return "flight"; 
6
CodeRank
See Code Examples for Spring Framework ModelMap Methods: