Java Code Examples for org.springframework.ui.ModelMap#addAttribute()

The following examples show how to use org.springframework.ui.ModelMap#addAttribute() . 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 File: MediaController.java    From spring-blog with MIT License 6 votes vote down vote up
@RequestMapping(value="/media")
public String media(ModelMap map){
    String contextPath = servletContext.getContextPath();
    String staticDir = "/static/img/public/";
    String staticPath = servletContext.getRealPath(staticDir);
    List<String> images = new ArrayList();
    File staticFileDir = new File(staticPath);
    if (staticFileDir.list() != null && staticFileDir.list().length > 0){
        for (String file: staticFileDir.list()){
            if (file.matches("[a-zA-Z0-9._-]+\\.(jpg|png|gif|svg)$")){
                images.add(contextPath + staticDir + file);
            }
        }
    }
    map.addAttribute("images", images);
    return "media";
}
 
Example 2
Source File: IndexController.java    From FlyCms with MIT License 6 votes vote down vote up
/**
 * 首页
 *
 * @return
 */
@GetMapping(value = {"/" , "/index", "/index-{sort}"})
public String index(@PathVariable(value = "sort", required = false) String sort,@RequestParam(value = "p", defaultValue = "1") int p,ModelMap modelMap){
    //String welcome = messageSourceUtil.getMessage("welcome");
    if("hot".equals(sort)){
        sort="hot";
    }else if("recommend".equals(sort)){
        sort="recommend";
    }else{
        sort=null;
    }
    modelMap.addAttribute("sort", sort);
    modelMap.addAttribute("p", p);
    modelMap.addAttribute("user", getUser());
    return theme.getPcTemplate("index");
}
 
Example 3
Source File: GoogleAction.java    From albert with MIT License 6 votes vote down vote up
@RequestMapping("/search")
public String search(HttpServletRequest request,ModelMap model,String wd,Integer start) throws ClientProtocolException, IOException{
	
	String ip = Tools.getNoHTMLString(getIpAddr(request));
	String temp =wd;
	
	if(null==start){
		wd = wd+"&start="+1+"&num=10";
		start =1;
	}else{
		wd = wd+"&start="+start+"&num=10";
	}
	
	List<GoogleSearchResult>  list = googleService.search(wd);
	
	log.info("ip:"+ip+"搜索了"+temp);
	
	model.addAttribute("list", list);
	model.addAttribute("wd", temp);
	model.addAttribute("start", start);
	
	return "google/search";
}
 
Example 4
Source File: Stm2000Controller.java    From oslits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Stm2000 SVN Repository 허용 역할 목록을 삭제한다.
 * @param request
 * @param model
 * @return
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes" })
@RequestMapping(value="/stm/stm2000/stm2000/deleteStm2000SvnAuthGrpList.do")
public ModelAndView deleteStm2000SvnAuthGrpList(HttpServletRequest request, HttpServletResponse response, ModelMap model )	throws Exception {
	try{
		// request 파라미터를 map으로 변환
		Map paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);
		
		//역할그룹 제거
		stm2000Service.deleteStm2000SvnAuthGrpList(paramMap);
		
		// 삭제 성공여부 및 삭제성공 메시지 세팅
		model.addAttribute("errorYn", "N");
		model.addAttribute("message", egovMessageSource.getMessage("success.common.delete"));
		
		return new ModelAndView("jsonView");

	}catch(Exception e){
		Log.error("deleteStm2000SvnAuthGrpList()", e);
		// 삭제 실패여부 및 실패메시지 세팅
		model.addAttribute("errorYn", "Y");
		model.addAttribute("message", egovMessageSource.getMessage("fail.common.delete"));
		return new ModelAndView("jsonView");
	}
}
 
Example 5
Source File: PortalPreferenceController.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/admin/preferencedetail/update", method = RequestMethod.POST)
public String updatePreferences(@ModelAttribute("preferenceForm") PortalPreferenceForm form, BindingResult result,
                                @ModelAttribute(ModelKeys.TOKENCHECK) String sessionToken,
                                @RequestParam String token,
                                @RequestParam(required = false) String referringPageId,
                                ModelMap modelMap,
                                SessionStatus status) {
    checkTokens(sessionToken, token, status);

    formValidator.validate(form, result);
    if (result.hasErrors()) {
        modelMap.addAttribute(ModelKeys.REFERRING_PAGE_ID, referringPageId);
        addNavigationMenusToModel(SELECTED_ITEM, (Model) modelMap, referringPageId);
        return ViewNames.ADMIN_PREFERENCE_DETAIL;
    }

    final Set<Map.Entry<String, PortalPreference>> entries = form.getPreferenceMap().entrySet();

    for (Map.Entry<String, PortalPreference> entry : entries) {
        preferenceService.savePreference(entry.getValue());
    }

    modelMap.clear();
    status.setComplete();
    return "redirect:/app/admin/preferences?action=update&referringPageId=" + referringPageId;
}
 
Example 6
Source File: ChangePasswordController.java    From CognitoDemo with Apache License 2.0 5 votes vote down vote up
/**
 * Display the change password form.  This form is displayed differently for a forgotten password and
 * for a password change for a logged in user (e.g., a user with an active session). The changeType
 * variable controls the way the form is displayed.
 * 
 * @return
 */
@GetMapping("change_password")
public ModelAndView changePassword( ModelMap modelMap, HttpServletRequest request ) {
    if (request.getSession().getAttribute(USER_SESSION_ATTR) != null) {
        // if the user is logged in (they know their password) then the change is just an old to new password
        // change without emailing the password.
        UserInfo info = (UserInfo)request.getSession().getAttribute(USER_SESSION_ATTR);
        if (info != null) {
            modelMap.addAttribute("user_name_val", info.getUserName());
        }
    }
    return new ModelAndView("change_password", modelMap );
}
 
Example 7
Source File: CmsTaskAct.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
@RequestMapping("/task/v_list.do")
public String list(Integer pageNo, HttpServletRequest request, ModelMap model) {
	Pagination pagination = manager.getPage(CmsUtils.getSiteId(request),cpn(pageNo), CookieUtils
			.getPageSize(request));
	model.addAttribute("pagination",pagination);
	model.addAttribute("pageNo",pagination.getPageNo());
	return "task/list";
}
 
Example 8
Source File: MembershipCardAction.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 会员卡列表
 * @param pageForm
 * @param model
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/control/membershipCard/list") 
public String execute(PageForm pageForm,ModelMap model,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception {
	StringBuffer jpql = new StringBuffer("");
	//存放参数值
	List<Object> params = new ArrayList<Object>();
	
	
	PageView<MembershipCard> pageView = new PageView<MembershipCard>(settingService.findSystemSetting_cache().getBackstagePageNumber(),pageForm.getPage(),10);
	//当前页
	int firstindex = (pageForm.getPage()-1)*pageView.getMaxresult();;	
	//排序
	LinkedHashMap<String,String> orderby = new LinkedHashMap<String,String>();
	
	orderby.put("id", "desc");//根据id字段降序排序
	
	
	//删除第一个and
	String jpql_str = StringUtils.difference(" and", jpql.toString());
	
	//调用分页算法类
	QueryResult<MembershipCard> qr = membershipCardService.getScrollData(MembershipCard.class, firstindex, pageView.getMaxresult(), jpql_str, params.toArray(),orderby);		
	
	pageView.setQueryResult(qr);
	model.addAttribute("pageView", pageView);
	
	return "jsp/membershipCard/membershipCardList";
}
 
Example 9
Source File: AdminController.java    From diamond with Apache License 2.0 5 votes vote down vote up
@RequestMapping(params = "method=listConfigLike", method = RequestMethod.GET)
public String listConfigLike(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, ModelMap modelMap) {
    if (StringUtils.isBlank(dataId) && StringUtils.isBlank(group)) {
        modelMap.addAttribute("message", "模糊查询请至少设置一个查询参数");
        return "/admin/config/list";
    }
    Page<ConfigInfo> page = this.configService.findConfigInfoLike(pageNo, pageSize, group, dataId);

    String accept = request.getHeader("Accept");
    if (accept != null && accept.indexOf("application/json") >= 0) {
        try {
            String json = JSONUtils.serializeObject(page);
            modelMap.addAttribute("pageJson", json);
        }
        catch (Exception e) {
            log.error("序列化page对象出错", e);
        }
        return "/admin/config/list_json";
    }
    else {
        modelMap.addAttribute("page", page);
        modelMap.addAttribute("dataId", dataId);
        modelMap.addAttribute("group", group);
        modelMap.addAttribute("method", "listConfigLike");
        return "/admin/config/list";
    }
}
 
Example 10
Source File: ReportDesignController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/changechartppy")
@Menu(type = "report", subtype = "reportdesign")
public ModelAndView changechartppy(ModelMap map,HttpServletRequest request, @Valid ReportModel reportModel, @Valid ChartProperties chartProperties,  HashMap<String,String> semap) throws Exception {
	ReportModel model = this.getModel(reportModel.getId(), super.getOrgi(request));
	if (null!=model) {
		model.setExchangerw(reportModel.isExchangerw());
		model.setIsloadfulldata("true".equals(reportModel.getIsloadfulldata())?"true":"false");
		model.setPagesize(reportModel.getPagesize());
		ChartProperties oldChartppy = model.getChartProperties();
		oldChartppy = oldChartppy==null? new ChartProperties():oldChartppy;
		oldChartppy.setLegen(chartProperties.isLegen());
		oldChartppy.setLegenalign(chartProperties.getLegenalign());
		oldChartppy.setDataview(chartProperties.isDataview());
		oldChartppy.setFormat(StringUtils.isBlank(chartProperties.getFormat())?"val":chartProperties.getFormat());
		Base64 base64 = new Base64();
		model.setChartcontent(base64.encodeToString(UKTools.toBytes(oldChartppy))) ;
		reportModelRes.save(model);
	}
	map.addAttribute("eltemplet", templateRes.findByIdAndOrgi(model.getTempletid(), super.getOrgi(request)));
	map.addAttribute("element", model);
	map.addAttribute("reportModel", model);
	if (model != null && !StringUtils.isBlank(model.getPublishedcubeid())) {
		PublishedCube cube = publishedCubeRepository.findOne(model.getPublishedcubeid());
		map.addAttribute("cube", cube);
		if (!model.getMeasures().isEmpty()) {
			map.addAttribute("reportData",reportCubeService.getReportData(model, cube.getCube(), request, true, semap));
		}
	}
	return request(super.createRequestPageTempletResponse("/apps/business/report/design/elementajax"));
}
 
Example 11
Source File: BlogController.java    From spring-blog with MIT License 5 votes vote down vote up
@RequestMapping(value={"/", "", "/blog"}, method=RequestMethod.GET)
public String home(
    @PageableDefault(size = 5, sort = {"postDate"}, direction = Sort.Direction.DESC) Pageable pageable,
    ModelMap map
) {
    Page<BlogPost> posts = blogRepository.findByStatusOrderByPostDateAsc(BlogPost.STATUS_ACTIVE, pageable);
    List<BlogPost> blogPosts = new ArrayList<>(posts.getContent());
    map.addAttribute("currentPage", pageable.getPageNumber() + 1);
    map.addAttribute("numPages", posts.getTotalPages());
    map.addAttribute("postCount", posts.getTotalElements());
    map.addAttribute("blogPosts", blogPosts);
    return "home";
}
 
Example 12
Source File: EmailAdminController.java    From FlyCms with MIT License 5 votes vote down vote up
@GetMapping(value = "/edit_templets_email/{id}")
public String updateEmailTemplets(@PathVariable(value = "id", required = false) int id,ModelMap modelMap){
    Email email=emailService.findEmailTempletById(id);
    if(email==null){
        return theme.getAdminTemplate("404");
    }
    modelMap.put("email", email);
    modelMap.addAttribute("admin", getAdminUser());
    return theme.getAdminTemplate("webconfig/edit_email");
}
 
Example 13
Source File: AnkushHybridClusterCreation.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/clusterConf/{clusterId}", method = RequestMethod.GET)
public String clusterConf(ModelMap model,
		@PathVariable("clusterId") String clusterId) {
	logger.info("Inside  clusterConf view");
	model.addAttribute("title", "clusterConf");
	model.addAttribute("cssFiles", cssFiles);
	model.addAttribute("jsFiles", jsFiles);
	model.addAttribute("clusterId", clusterId);
	return "hybridCluster/hybridClusterCreation/hybridClusterCreate";
}
 
Example 14
Source File: UserController.java    From springboot-learning-example with Apache License 2.0 5 votes vote down vote up
/**
 * 处理 "/users/{id}" 的 PUT 请求,用来更新 User 信息
 *
 */
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String putUser(ModelMap map,
                      @ModelAttribute @Valid User user,
                      BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        map.addAttribute("action", "update");
        return "userForm";
    }

    userService.update(user);
    return "redirect:/users/";
}
 
Example 15
Source File: KbsController.java    From youkefu with Apache License 2.0 4 votes vote down vote up
@RequestMapping({"/addtype"})
@Menu(type="apps", subtype="kbs")
public ModelAndView addtype(ModelMap map , HttpServletRequest request ){
	map.addAttribute("kbsTypeResList", kbsTypeRes.findByOrgi(super.getOrgi(request))) ;
	return request(super.createRequestPageTempletResponse("/apps/business/kbs/addtype"));
}
 
Example 16
Source File: MessageAction.java    From albert with MIT License 4 votes vote down vote up
@RequestMapping("/getThemeDetail")
	public String getAirticleDetail(@RequestParam("id")int id,ModelMap model,HttpServletRequest request) throws UnsupportedEncodingException{
		
		String ip = StringFilter(getIpAddr(request));
		
		ThemeDTO theme = messageService.getThemeById(id);
		
		log.info("ip:"+ip+" 查看了主题:"+theme.getTheme());
		
		model.addAttribute("theme", theme);
		
		List<MessageDTO> messages = messageService.getMessagesByThemeId(id);
		
		model.addAttribute("messages", messages);
		
//		if(!isMobile()){
			return "message/themeDetailNew";
//		}else{
//			return "mobile/themeDetail";
//		}
	}
 
Example 17
Source File: UserController.java    From FlyCms with MIT License 4 votes vote down vote up
@GetMapping(value = "/ucenter/online_recharge")
public String userOnlineRecharge(ModelMap modelMap){
    modelMap.addAttribute("user", getUser());
    return theme.getPcTemplate("user/online_recharge");
}
 
Example 18
Source File: FirmwareController.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
   * Here
   * @param request
   * @param locale
   * @param model
   * @return
   * @throws Exception
   */
  @RequestMapping(value="/device/status.do")
  public String deviceUpgradeScheduleStatus(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]);
}
*/

Map<String, String[]> paramMap = request.getParameterMap();

String[] tokens = paramMap.get("deviceModelId");
String deviceModelId = "";
String firmwareId = "";
List firmwareList = null;
List versionList = null;
  	if (tokens != null && tokens.length > 0) {
  		deviceModelId = tokens[0];
  		firmwareList = firmwareService.getFirmwareListWithDeviceModelId(deviceModelId);
  	}
tokens = paramMap.get("firmwareId");
  	if (tokens != null && tokens.length > 0) {    		
  		firmwareId = tokens[0];
  		versionList = firmwareService.getFirmwareVersionList(firmwareId);
  	}

int page = StringUtil.parseInt(request.getParameter("page"), 1);
      PagingUtil resultPagingUtil = deviceService.getDeviceFirmwareListPaging(page, 0, paramMap);
      List deviceModelList = deviceService.getDeviceModelList(null);
      

/**
 * 데이터 셋팅
 */
model.addAttribute("page", page);
model.addAttribute("param", paramMap);
model.addAttribute("firmwareList", firmwareList);
model.addAttribute("deviceModelList", deviceModelList);
model.addAttribute("versionList", versionList);
model.addAttribute("resultPagingUtil", resultPagingUtil);

ObjectMapper objectMapper = new ObjectMapper();

model.addAttribute("paramJson", objectMapper.writeValueAsString(paramMap));
model.addAttribute("firmwareListJson", objectMapper.writeValueAsString(firmwareList));
model.addAttribute("versionListJson", objectMapper.writeValueAsString(versionList));
model.addAttribute("deviceModelListJson", objectMapper.writeValueAsString(deviceModelList));
model.addAttribute("resultPagingUtilJson", objectMapper.writeValueAsString(resultPagingUtil));

  	return "/v2/firmware/status";
  }
 
Example 19
Source File: Dsh1000Controller.java    From oslits with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Dsh1001 대시보드 신호등, 차트 클릭 시 요구사항 목록 조회 
 * @param 
 * @return 
 * @exception Exception
 */
@SuppressWarnings("unchecked")
@RequestMapping(value="/dsh/dsh1000/dsh1000/selectDsh1000ReqList.do")
public ModelAndView selectDsh1000ReqList(@ModelAttribute("dsh1000VO") Dsh1000VO dsh1000VO, HttpServletRequest request, HttpServletResponse response, ModelMap model)	throws Exception {
	
   	try{
   		//리퀘스트에서 넘어온 파라미터를 맵으로 세팅
       	Map<String, String> paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);
       	
      		//현재 페이지 값, 보여지는 개체 수
		String _pageNo_str = paramMap.get("pageNo");
		String _pageSize_str = paramMap.get("pageSize");
		
		int _pageNo = 1;
		int _pageSize = 10;
		
		if(_pageNo_str != null && !"".equals(_pageNo_str)){
			_pageNo = Integer.parseInt(_pageNo_str)+1;  
		}
		if(_pageSize_str != null && !"".equals(_pageSize_str)){
			_pageSize = Integer.parseInt(_pageSize_str);  
		}
		
		//페이지 사이즈
		dsh1000VO.setPageIndex(_pageNo);
		dsh1000VO.setPageSize(_pageSize);
		dsh1000VO.setPageUnit(_pageSize);
		
		// projectId 파라미터를 가져온다. 통합대시보드에서 프로젝트의 신호등 클릭 시 projectId 파라미터를 전달한다.
		String projectId = paramMap.get("projectId");
		// projectId 파라미터가 있을경우 
		if(projectId != null && !"".equals(projectId)) {
			dsh1000VO.setPrjId(projectId);
		// projectId 파라미터가 없을경우 
		}else {
			// session에서 현재 선택된 프로젝트 id를 가져와 세팅한다.
			dsh1000VO.setPrjId((String) request.getSession().getAttribute("selPrjId"));
		}
       	
   		PaginationInfo paginationInfo = PagingUtil.getPaginationInfo(dsh1000VO);  /** paging - 신규방식 */
       	List<Dsh1000VO> dsh1000List = null;

		HttpSession ss = request.getSession();
		LoginVO loginVO = (LoginVO) ss.getAttribute("loginVO");
		dsh1000VO.setLicGrpId(loginVO.getLicGrpId());

   		// 목록 조회  authGrpIds
		dsh1000List = dsh1000Service.selectDsh1000ReqList(dsh1000VO);
	    
   		// 총 건수
	    int totCnt = dsh1000Service.selectDsh1000ReqListCnt(dsh1000VO);
	    paginationInfo.setTotalRecordCount(totCnt);
	    
	    model.addAttribute("list", dsh1000List);
	    
	    //페이지 정보 보내기
		Map<String, Integer> pageMap = new HashMap<String, Integer>();
		pageMap.put("pageNo",dsh1000VO.getPageIndex());
		pageMap.put("listCount", dsh1000List.size());
		pageMap.put("totalPages", paginationInfo.getTotalPageCount());
		pageMap.put("totalElements", totCnt);
		pageMap.put("pageSize", _pageSize);

		model.addAttribute("page", pageMap);
       	
       	//조회성공메시지 세팅
       	model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));
       	
       	return new ModelAndView("jsonView", model);
   	}catch(Exception ex){
   		Log.error("selectDsh1000ReqList()", ex);
   		
   		//조회실패 메시지 세팅
   		model.addAttribute("message", egovMessageSource.getMessage("fail.common.select"));
   		return new ModelAndView("jsonView", model);
   	}
}
 
Example 20
Source File: ResourceAct.java    From Lottery with GNU General Public License v2.0 4 votes vote down vote up
@RequestMapping(value = "/resource/v_upload.do")
public String uploadInput(HttpServletRequest request, ModelMap model) {
	String root = RequestUtils.getQueryParam(request, "root");
	model.addAttribute("root", root);
	return "resource/upload";
}