Java Code Examples for javax.servlet.http.HttpServletRequest.setAttribute()

The following are Jave code examples for showing how to use setAttribute() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: CleanupPreviewLessonsAction.java   View Source Code Vote up 7 votes
@Override
   public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException {
if (!getSecurityService().isSysadmin(getUserID(), "display cleanup preview lessons", false)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a sysadmin");
    return null;
}

if (!(request.isUserInRole(Role.SYSADMIN))) {
    request.setAttribute("errorName", "CleanupPreviewLessonsAction");
    request.setAttribute("errorMessage", AdminServiceProxy.getMessageService(getServlet().getServletContext())
	    .getMessage("error.need.sysadmin"));
    return mapping.findForward("error");
}

long[] lessonCount = getLessonService().getPreviewLessonCount();
request.setAttribute("previewCount", lessonCount[0]);
request.setAttribute("allLessonCount", lessonCount[1]);

return mapping.findForward("cleanup");
   }
 
Example 2
Project: lams   File: MonitoringAction.java   View Source Code Vote up 6 votes
@Override
   public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException, JSONException, DokumaranConfigurationException, URISyntaxException {
String param = mapping.getParameter();

request.setAttribute("initialTabId", WebUtil.readLongParam(request, AttributeNames.PARAM_CURRENT_TAB, true));

if (param.equals("summary")) {
    return summary(mapping, form, request, response);
} else if (param.equals("fixFaultySession")) {
    return fixFaultySession(mapping, form, request, response);
} else if (param.equals("launchTimeLimit")) {
    return launchTimeLimit(mapping, form, request, response);
} else if (param.equals("addOneMinute")) {
    return addOneMinute(mapping, form, request, response);
}

return mapping.findForward(DokumaranConstants.ERROR);
   }
 
Example 3
Project: Pet-Supply-Store   File: AbstractUIServlet.java   View Source Code Vote up 6 votes
/**
 * Checks if specific cookies exist and save their value as message.
 * 
 * @param request
 * @param response
 */
protected void checkforCookie(HttpServletRequest request, HttpServletResponse response) {
	if (request.getCookies() != null) {
		for (Cookie cook : request.getCookies()) {
			if (cook.getName().equals(MESSAGECOOKIE)) {
				request.setAttribute("message", cook.getValue().replaceAll("_", " "));
				cook.setMaxAge(0);
				response.addCookie(cook);
			} else if (cook.getName().equals(PRODUCTCOOKIE)) {
				request.setAttribute("numberProducts", cook.getValue());
			} else if (cook.getName().equals(ERRORMESSAGECOOKIE)) {
				request.setAttribute("errormessage", cook.getValue().replaceAll("_", " "));
				cook.setMaxAge(0);
				response.addCookie(cook);
			}
		}
	}
}
 
Example 4
Project: lams   File: LessonManagerServlet.java   View Source Code Vote up 6 votes
private void showModifyLessonPage(HttpServletRequest request, HttpServletResponse response, Context ctx)
    throws InitializationException, BbServiceException, PersistenceException, IOException, ServletException {

// retrive the LAMS lesson
BbPersistenceManager bbPm = PersistenceServiceFactory.getInstance().getDbPersistenceManager();
Container bbContainer = bbPm.getContainer();
Id contentId = new PkId(bbContainer, CourseDocument.DATA_TYPE, request.getParameter("content_id"));
ContentDbLoader courseDocumentLoader = (ContentDbLoader) bbPm.getLoader(ContentDbLoader.TYPE);
Content bbContent = (Content) courseDocumentLoader.loadById(contentId);

// get LAMS lessons's properties
Calendar startDate = bbContent.getStartDate();
Calendar endDate = bbContent.getEndDate();
FormattedText description = bbContent.getBody();

request.setAttribute("bbContent", bbContent);
request.setAttribute("startDate", startDate);
request.setAttribute("endDate", endDate);
request.setAttribute("description", description);

request.getRequestDispatcher("/modules/modify.jsp").forward(request, response);
   }
 
Example 5
Project: lams   File: MonitoringAction.java   View Source Code Vote up 6 votes
private ActionForward viewReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {

Long uid = WebUtil.readLongParam(request, ResourceConstants.ATTR_USER_UID);
Long sessionID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);

IResourceService service = getResourceService();
ResourceUser user = service.getUser(uid);
NotebookEntry notebookEntry = service.getEntry(sessionID, CoreNotebookConstants.NOTEBOOK_TOOL,
	ResourceConstants.TOOL_SIGNATURE, user.getUserId().intValue());

ResourceSession session = service.getResourceSessionBySessionId(sessionID);

ReflectDTO refDTO = new ReflectDTO(user);
if (notebookEntry == null) {
    refDTO.setFinishReflection(false);
    refDTO.setReflect(null);
} else {
    refDTO.setFinishReflection(true);
    refDTO.setReflect(notebookEntry.getEntry());
}
refDTO.setReflectInstrctions(session.getResource().getReflectInstructions());

request.setAttribute("userDTO", refDTO);
return mapping.findForward("success");
   }
 
Example 6
Project: kettle_support_kettle8.0   File: QuartzController.java   View Source Code Vote up 6 votes
@RequestMapping(value = ACTION_LIST)
public String quartz(HttpServletRequest request,
		HttpServletResponse response) {
	try {
		Iterator<?> it = request.getParameterMap().entrySet().iterator();
		QuartzSchedule entity = new QuartzSchedule();
		while (it.hasNext()) {
			Map.Entry<?, ?> ent = (Entry<?, ?>) it.next();
			entity.setValue((String) ent.getKey(),
					((String[]) ent.getValue())[0]);
		}
		request.setAttribute("group", entity.getGroup());
		request.setAttribute("title", entity.getName());
		Map<?, ?> map = (Map<?, ?>) service.iQuartzScheduleService
				.selectByWhere(entity);
		List<?> list = service.iQuartzGroupService
				.selectByWhere(new QuartzGroup());
		request.setAttribute(LIST, list);
		request.setAttribute(ENTITY, map);
	} catch (SchedulerException e) {
		e.printStackTrace();
	}
	return VIEW_WIDGET + VIEW_QUARTZ + PAGE_LIST;
}
 
Example 7
Project: lams   File: AuthoringAction.java   View Source Code Vote up 6 votes
/**
    * Ajax call, will add one more input line for new survey item instruction.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    */
   private ActionForward newInstruction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {
int count = NumberUtils.stringToInt(request.getParameter(AuthoringAction.INSTRUCTION_ITEM_COUNT), 0);
List instructionList = new ArrayList(++count);
for (int idx = 0; idx < count; idx++) {
    String item = request.getParameter(AuthoringAction.INSTRUCTION_ITEM_DESC_PREFIX + idx);
    if (item == null) {
	instructionList.add("");
    } else {
	instructionList.add(item);
    }
}
request.setAttribute(SurveyConstants.ATTR_INSTRUCTION_LIST, instructionList);
return mapping.findForward(SurveyConstants.SUCCESS);
   }
 
Example 8
Project: My-Blog   File: ArticleController.java   View Source Code Vote up 5 votes
@GetMapping(value = "/{cid}")
public String editArticle(@PathVariable String cid, HttpServletRequest request) {
    ContentVo contents = contentsService.getContents(cid);
    request.setAttribute("contents", contents);
    List<MetaVo> categories = metasService.getMetas(Types.CATEGORY.getType());
    request.setAttribute("categories", categories);
    request.setAttribute("active", "article");
    return "admin/article_edit";
}
 
Example 9
Project: lams   File: AuthoringAction.java   View Source Code Vote up 5 votes
/**
    * Initializes import questions page.
    */
   private ActionForward importInit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID);
request.setAttribute(AssessmentConstants.ATTR_SESSION_MAP_ID, sessionMapID);

return mapping.findForward(AssessmentConstants.SUCCESS);
   }
 
Example 10
Project: kettle_support_kettle8.0   File: KettleResultController.java   View Source Code Vote up 5 votes
@RequestMapping(value = ACTION_VIEW, method = RequestMethod.GET)
public String view(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
	Iterator<?> it = request.getParameterMap().entrySet().iterator();
	KettleResult entity = new KettleResult();
	while (it.hasNext()) {
		Map.Entry<?, ?> ent = (Entry<?, ?>) it.next();
		entity.setValue((String) ent.getKey(),
				((String[]) ent.getValue())[0]);
	}
	entity = (KettleResult) service.iKettleResultService.select(entity);
	request.setAttribute("entity", entity);
	return VIEW_WIDGET + VIEW_KETTLE + VIEW_RESULT + PAGE_VIEW;
}
 
Example 11
Project: lams   File: Action.java   View Source Code Vote up 5 votes
/**
 * Adds the specified errors keys into the appropriate request attribute
    * for use by the &lt;html:errors&gt; tag, if any messages are required.
 * Initialize the attribute if it has not already been. Otherwise, ensure
    * that the request attribute is not set.
 *
 * @param request   The servlet request we are processing
 * @param errors  Errors object
 * @since Struts 1.2.1
 */
protected void addErrors(
	HttpServletRequest request,
	ActionMessages errors) {

	if (errors == null){
		//	bad programmer! *slap*
		return;
	}

	// get any existing errors from the request, or make a new one
	ActionMessages requestErrors = (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
	if (requestErrors == null){
		requestErrors = new ActionMessages();
	}
	// add incoming errors
	requestErrors.add(errors);

	// if still empty, just wipe it out from the request
	if (requestErrors.isEmpty()) {
		request.removeAttribute(Globals.ERROR_KEY);
		return;
	}

	// Save the errors
	request.setAttribute(Globals.ERROR_KEY, requestErrors);
}
 
Example 12
Project: springMvc4.x-project   File: DemoInterceptor.java   View Source Code Vote up 5 votes
@Override
public void postHandle(HttpServletRequest request, //③
		HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
	long startTime = (Long) request.getAttribute("startTime");
	request.removeAttribute("startTime");
	long endTime = System.currentTimeMillis();
	System.out.println("本次请求处理时间为:" + new Long(endTime - startTime)+"ms");
	request.setAttribute("handlingTime", endTime - startTime);
}
 
Example 13
Project: crm   File: DepartmentAction.java   View Source Code Vote up 5 votes
@At
@Ok("beetl:/WEB-INF/base/department.html")
public void edit(@Param("id")Long id,
                  HttpServletRequest request){
    if(id == null || id == 0){
        request.setAttribute("department", null);
    }else{
        request.setAttribute("department", departmentService.fetch(id));
    }
}
 
Example 14
Project: lams   File: AuthoringAction.java   View Source Code Vote up 5 votes
@Override
   public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {

String param = mapping.getParameter();
// -----------------------Spreadsheet Author function ---------------------------
if (param.equals("start")) {
    ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
    request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());
    return start(mapping, form, request, response);
}
if (param.equals("definelater")) {
    // update define later flag to true
    Long contentId = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID));
    ISpreadsheetService service = getSpreadsheetService();
    Spreadsheet spreadsheet = service.getSpreadsheetByContentId(contentId);

    spreadsheet.setDefineLater(true);
    service.saveOrUpdateSpreadsheet(spreadsheet);
    
    //audit log the teacher has started editing activity in monitor
    service.auditLogStartEditingActivityInMonitor(contentId);

    request.setAttribute(AttributeNames.ATTR_MODE, ToolAccessMode.TEACHER.toString());
    return start(mapping, form, request, response);
}
if (param.equals("initPage")) {
    return initPage(mapping, form, request, response);
}

if (param.equals("updateContent")) {
    return updateContent(mapping, form, request, response);
}

return mapping.findForward(SpreadsheetConstants.ERROR);
   }
 
Example 15
Project: PUC-INF1407   File: ServletPessoa.java   View Source Code Vote up 5 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	Pessoa pessoa = new Pessoa();
	pessoa.setNome("Maria");
	
	Endereco endereco = new Endereco();
	endereco.setLogradouro("Rua que sobe e desce");
	endereco.setNumero(8752);
	endereco.setBairro("Muito Longe");
	pessoa.setEndereco(endereco);
	
	request.setAttribute("pessoa", pessoa);
	request.getRequestDispatcher("mostraPessoa.jsp").forward(request, response);
}
 
Example 16
Project: lams   File: AuthoringTaskListConditionAction.java   View Source Code Vote up 5 votes
private ActionForward switchItem(ActionMapping mapping, HttpServletRequest request, boolean up) {
// get back sessionMAP
String sessionMapID = WebUtil.readStrParam(request, TaskListConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);

int sequenceId = NumberUtils.stringToInt(request.getParameter(TaskListConstants.PARAM_SEQUENCE_ID), -1);
if (sequenceId != -1) {
    SortedSet<TaskListCondition> conditionList = getTaskListConditionList(sessionMap);
    List<TaskListCondition> rList = new ArrayList<TaskListCondition>(conditionList);
    // get current and the target item, and switch their sequnece
    TaskListCondition condition = rList.get(sequenceId);
    TaskListCondition repCondition;
    if (up) {
	repCondition = rList.get(--sequenceId);
    } else {
	repCondition = rList.get(++sequenceId);
    }
    int upSeqId = repCondition.getSequenceId();
    repCondition.setSequenceId(condition.getSequenceId());
    condition.setSequenceId(upSeqId);

    // put back list, it will be sorted again
    conditionList.clear();
    conditionList.addAll(rList);
}

request.setAttribute(TaskListConstants.ATTR_SESSION_MAP_ID, sessionMapID);
return mapping.findForward(TaskListConstants.SUCCESS);
   }
 
Example 17
Project: lams   File: McAction.java   View Source Code Vote up 4 votes
/**
    * removes a question from the questions map
    */
   public ActionForward removeQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
McAuthoringForm mcAuthoringForm = (McAuthoringForm) form;

String sessionMapId = request.getParameter(McAppConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(sessionMapId);
request.setAttribute(McAppConstants.ATTR_SESSION_MAP_ID, sessionMapId);

Integer questionIndexToDelete = WebUtil.readIntParam(request, "questionIndex");
mcAuthoringForm.setQuestionIndex(questionIndexToDelete);

List<McQuestionDTO> questionDTOs = (List<McQuestionDTO>) sessionMap.get(McAppConstants.QUESTION_DTOS);

//exclude Question with questionIndex From List
List<McQuestionDTO> tempQuestionDtos = new LinkedList<>();
int queIndex = 0;
for (McQuestionDTO questionDTO : questionDTOs) {

    String questionText = questionDTO.getQuestion();
    Integer displayOrder = questionDTO.getDisplayOrder();
    if ((questionText != null) && !questionText.isEmpty()) {

	if (!displayOrder.equals(questionIndexToDelete)) {
	    ++queIndex;
	    questionDTO.setDisplayOrder(queIndex);
	    tempQuestionDtos.add(questionDTO);

	} else {
	    List<McQuestionDTO> deletedQuestionDTOs = (List<McQuestionDTO>) sessionMap
		    .get(McAppConstants.LIST_DELETED_QUESTION_DTOS);
	    deletedQuestionDTOs.add(questionDTO);
	    sessionMap.put(McAppConstants.LIST_DELETED_QUESTION_DTOS, deletedQuestionDTOs);
	}
    }
}
questionDTOs = tempQuestionDtos;
sessionMap.put(McAppConstants.QUESTION_DTOS, questionDTOs);

return (mapping.findForward("itemList"));
   }
 
Example 18
Project: central-medic-center   File: AllocateDoctor.java   View Source Code Vote up 4 votes
private void redirectToLogin(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	RequestDispatcher rs = request.getRequestDispatcher("login.jsp");
	request.setAttribute("error", "Please login again");
	rs.forward(request, response);
}
 
Example 19
Project: lams   File: MonitoringAction.java   View Source Code Vote up 4 votes
/**
    * Performs all necessary actions for showing statistic page.
    *
    * @param request
    */
   private void statistic(HttpServletRequest request) {
Long toolContentID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID));

forumService = getForumService();
Map sessionTopicsMap = new TreeMap<SessionDTO, List<MessageDTO>>(new SessionDTOComparator());
Map sessionAvaMarkMap = new HashMap();
Map sessionTotalMsgMap = new HashMap();

List sessList = forumService.getSessionsByContentId(toolContentID);
Iterator sessIter = sessList.iterator();
while (sessIter.hasNext()) {
    ForumToolSession session = (ForumToolSession) sessIter.next();
    List topicList = forumService.getRootTopics(session.getSessionId());
    Iterator iter = topicList.iterator();
    int totalMsg = 0;
    int msgNum;
    float totalMsgMarkSum = 0;
    float msgMarkSum = 0;
    for (; iter.hasNext();) {
	MessageDTO msgDto = (MessageDTO) iter.next();
	// get all message under this topic
	List topicThread = forumService.getTopicThread(msgDto.getMessage().getUid());
	// loop all message under this topic
	msgMarkSum = 0;
	Iterator threadIter = topicThread.iterator();
	for (msgNum = 0; threadIter.hasNext(); msgNum++) {
	    MessageDTO dto = (MessageDTO) threadIter.next();
	    if (dto.getMark() != null) {
		msgMarkSum += dto.getMark().floatValue();
	    }
	}
	// summary to total mark
	totalMsgMarkSum += msgMarkSum;
	// set average mark to topic message DTO for display use
	msgDto.setMark(msgMarkSum / msgNum);
	totalMsg += msgNum;
    }

    float averMark = totalMsg == 0 ? 0 : totalMsgMarkSum / totalMsg;

    SessionDTO sessionDto = new SessionDTO();
    sessionDto.setSessionID(session.getSessionId());
    sessionDto.setSessionName(session.getSessionName());

    sessionTopicsMap.put(sessionDto, topicList);
    sessionAvaMarkMap.put(session.getSessionId(), averMark);
    sessionTotalMsgMap.put(session.getSessionId(), new Integer(totalMsg));
}
request.setAttribute("topicList", sessionTopicsMap);
request.setAttribute("markAverage", sessionAvaMarkMap);
request.setAttribute("totalMessage", sessionTotalMsgMap);
request.setAttribute(ForumConstants.ATTR_SESSION_MAP_ID,
	WebUtil.readStrParam(request, ForumConstants.ATTR_SESSION_MAP_ID));
   }
 
Example 20
Project: unitimes   File: LookupTables.java   View Source Code Vote up 2 votes
/**
 * Get all departments that are not external and store it in request object
 * @param request
 * @throws Exception
 */
public static void setupNonExternalDepts(HttpServletRequest request, Long sessionId) throws Exception {
    request.setAttribute(Department.DEPT_ATTR_NAME, Department.findAllNonExternal(sessionId));
}