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

The following are Jave code examples for showing how to use getParameter() 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: appinventor-extensions   File: FeedbackServlet.java   View Source Code Vote up 7 votes
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  PolicyFactory policy = new HtmlPolicyBuilder()
    .allowElements("p").toFactory();
  String query = req.getQueryString();
  String notes = req.getParameter("notes");
  String foundIn = req.getParameter("foundIn");
  String faultData = req.getParameter("faultData");
  String projectId = req.getParameter("projectId");
  if (notes == null) notes = "";
  if (foundIn == null) foundIn = "";
  if (faultData == null) faultData = "";
  if (projectId == null) projectId = "-1";
  notes = policy.sanitize(notes);
  foundIn = policy.sanitize(foundIn);
  projectId = policy.sanitize(projectId);
  PrintWriter out = new PrintWriter(resp.getWriter());
  out.println(String.format(template, notes, foundIn, faultData, projectId));
}
 
Example 2
Project: pay-xxpay-master   File: OAuth2RequestParamHelper.java   View Source Code Vote up 6 votes
/**
 * 根据key获取;如果有state,从state中获取;否则从request中获取
 * @param request
 * @param name
 * @return
 */
public static String getParameter(HttpServletRequest request, String name){
	String state = request.getParameter("state");
	if(state != null){
		String[] stateArr = state.split("!");//用!间隔
		if(stateArr != null && stateArr.length > 0){
			for(String s : stateArr){
				String key = s.split("=")[0];
				String value = s.split("=")[1];
				if(name.equals(key)){
					return value;
				}
			}
		}
		return null;
	}else{
		return request.getParameter(name);
	}
}
 
Example 3
Project: hotelApp   File: CategoryServlet.java   View Source Code Vote up 6 votes
/**
 * doPost method to display categories of Hotels page.
 *
 * @param request
 * @param response
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    StringBuilder sb = new StringBuilder();
    PrintWriter out = response.getWriter();

    if (getUsername(request) != null) {
        String type = request.getParameter("type");
        String[] titles = new String[] {"Hotels", "Reviews", "Attractions"};

        for (int i = 0; i < titles.length; i++) {
            if (type.equals(titles[i])) {
                sb.append("<label class=\"list-group-item list-group-item-action active\">");
                sb.append(titles[i]).append("</label>");
            }
            else {
                sb.append("<label class=\"list-group-item list-group-item-action\" ");
                sb.append("onclick=\"tableTitle('" + titles[i] + "')\">");
                sb.append(titles[i]).append("</label>");
            }
        }

        out.println(sb.toString());
    }
}
 
Example 4
Project: service-hive   File: CanaryTestZuulFilter.java   View Source Code Vote up 6 votes
@Override
public Object run() {
    try {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Object blueOrGreen = request.getParameter("env");

        RequestMetadata requestMetadata = RequestMetadata.getCurrent().init();
        if (blueOrGreen != null ) {
            requestMetadata.add("env", "canary");
        } else {
            requestMetadata.add("env", "prod");
        }

    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}
 
Example 5
Project: FastBootWeixin   File: WxOAuth2Interceptor.java   View Source Code Vote up 6 votes
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    WxWebUser sessionUser = WxWebUtils.getWxWebUserFromSession(request);
    if (sessionUser != null) {
        return true;
    }
    String code = request.getParameter("code");
    String state = request.getParameter("state");
    if (!StringUtils.isEmpty(code)) {
        WxWebUser wxWebUser = wxUserManager.getWxWebUser(code);
        if (wxWebUser != null && wxWebUser.getOpenId() != null) {
            if (wxOAuth2Callback != null) {
                wxOAuth2Callback.after(new WxOAuth2Callback.WxOAuth2Context(wxWebUser, state, response, request));
            }
            WxWebUtils.setWxWebUserToSession(request, wxWebUser);
            return true;
        }
    }
    String requestUrl = getRequestUrl(request);
    logger.info("WxOAuth2Interceptor request url is : " + requestUrl);
    // 如果重定向到授权,则肯定可以获得信息,但是如果重定向到基本,则无法获得信息,所以默认重定向到授权
    String redirectUrl = WxRedirectUtils.redirect(requestUrl, false);
    logger.info("WxOAuth2Interceptor redirect to auth url : " + redirectUrl);
    response.sendRedirect(redirectUrl);
    return false;
}
 
Example 6
Project: lams   File: QaMonitoringStarterAction.java   View Source Code Vote up 6 votes
/**
    * validates request paramaters based on tool contract
    *
    * @param request
    * @param mapping
    * @return ActionForward
    * @throws ServletException
    */
   protected ActionForward validateParameters(HttpServletRequest request, ActionMapping mapping,
    QaMonitoringForm qaMonitoringForm) throws ServletException {

String strToolContentId = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID);

if ((strToolContentId == null) || (strToolContentId.length() == 0)) {
    QaUtils.cleanUpSessionAbsolute(request);
    throw new ServletException("No Tool Content ID found");
} else {
    try {
	long toolContentId = new Long(strToolContentId).longValue();

	qaMonitoringForm.setToolContentID(new Long(toolContentId).toString());
    } catch (NumberFormatException e) {
	QaUtils.cleanUpSessionAbsolute(request);
	throw e;
    }
}
return null;
   }
 
Example 7
Project: ssm-web   File: SeMenuController.java   View Source Code Vote up 5 votes
@RequestMapping(value = "/se_menu_list_data.do", method = {RequestMethod.POST}, produces = "application/json")
@ResponseBody
public String seMenuListDataHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws ServletException {
    PageProperty pp = new PageProperty();
    String[] enableSorts = {"id", "captionname", "menucode", "visible", "sourceurl"};

    String parentcode = request.getParameter("parentcode");
    if (!Utils.strIsNull(parentcode)) {
        pp.putParamMap("parentcode", parentcode.replace("%", "/%"));
    }

    setPageInfo(request, pp, enableSorts);
    PageList<SeMenu> seMenuList = seMenuService.getPageList(pp);
    return JSON.toJSONString(seMenuList, WriteNullStringAsEmpty);
}
 
Example 8
Project: tianti   File: CmsController.java   View Source Code Vote up 5 votes
/**
 * 文章置顶
 * @param request
 * @return
 */
@RequestMapping("/article/ajax/top")
@ResponseBody
public AjaxResult ajaxArticleTop(HttpServletRequest request){
	AjaxResult ajaxResult = new AjaxResult();
	ajaxResult.setSuccess(false);
	
	try {
		Boolean isTop = false;
		String[] ids = request.getParameterValues("ids");
		String topFlag = request.getParameter("topFlag");
		if(StringUtils.isNotBlank(topFlag) && topFlag.equals("1")){
			isTop = true;
		}
		if(ids != null && ids.length > 0){
			for(String id:ids){
				Article article = this.articleService.find(id);
				article.setIsTop(isTop);
				this.articleService.update(article);
			}
		}
		ajaxResult.setSuccess(true);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return ajaxResult;
}
 
Example 9
Project: ToDoApp-Spring   File: CalculatorController.java   View Source Code Vote up 5 votes
@RequestMapping(value = "/calculator", method = RequestMethod.POST)
public String add(Model model, HttpServletRequest request) {
    String s1 = request.getParameter("s1");
    String s2 = request.getParameter("s2");
    String ans = service.calculation(s1, s2, request.getParameter("r1"));
    model.addAttribute("ans", ans);
    model.addAttribute("s1", s1);
    model.addAttribute("s2", s2);
    return "calculator";
}
 
Example 10
Project: ralasafe   File: LoginFilter.java   View Source Code Vote up 5 votes
private User validUser(HttpServletRequest httpReq,
		HttpServletResponse httpResp) {
	// convert uniqueFields to object
	UserType userType = WebUtil.getUserType(httpReq);
	FieldMetadata[] uniqueFields = userType.getUserMetadata()
			.getMainTableMetadata().getUniqueFields();

	User expectUser = new User();
	for (int i = 0; i < uniqueFields.length; i++) {
		FieldMetadata fieldMetadata = uniqueFields[i];
		String javaType = fieldMetadata.getJavaType();

		String paramName = fieldMetadata.getName();
		if (uniqueFieldsParams != null) {
			paramName = uniqueFieldsParams[i];
		}
		String rawValue = httpReq.getParameter(paramName);

		Object value = parse(javaType, rawValue);
		expectUser.set(fieldMetadata.getName(), value);
	}

	String rawPassword = httpReq.getParameter(passwordParam);
	String password = encrypt.encrypt(rawPassword);

	UserManager manager = Factory.getUserManager(userType.getName());
	User findUser = manager.selectByUniqueFields(expectUser);

	if (findUser != null
			&& findUser.get(userPasswordField).equals(password)) {
		return findUser;
	} else {
		return null;
	}
}
 
Example 11
Project: Integrate   File: JwtAuthenticationTokenFilter.java   View Source Code Vote up 5 votes
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getParameter(this.tokenHeader);
    String userAppname = request.getParameter(this.appName);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String ybid = jwtTokenUtil.getYBidFromTocken(authToken);
    String appname = jwtTokenUtil.getAppnameFromTocken(authToken);

    logger.info("checking authentication for user " + ybid);

    if (ybid != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(ybid);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + ybid + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
 
Example 12
Project: urule   File: FrameServletHandler.java   View Source Code Vote up 5 votes
public void fileRename(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	String path=req.getParameter("path");
	path=Utils.decodeURL(path);
	String newPath=req.getParameter("newPath");
	newPath=Utils.decodeURL(newPath);
	repositoryService.fileRename(path, newPath);
	loadProjects(req, resp);			
}
 
Example 13
Project: lams   File: AuthoringAction.java   View Source Code Vote up 5 votes
/**
    * repopulateRequestParameters reads and saves request parameters
    *
    * @param request
    * @param voteAuthoringForm
    * @param voteGeneralAuthoringDTO
    */
   protected void repopulateRequestParameters(HttpServletRequest request, VoteAuthoringForm voteAuthoringForm,
    VoteGeneralAuthoringDTO voteGeneralAuthoringDTO) {

String toolContentID = request.getParameter(VoteAppConstants.TOOL_CONTENT_ID);
voteAuthoringForm.setToolContentID(toolContentID);
voteGeneralAuthoringDTO.setToolContentID(toolContentID);

String httpSessionID = request.getParameter(VoteAppConstants.HTTP_SESSION_ID);
voteAuthoringForm.setHttpSessionID(httpSessionID);
voteGeneralAuthoringDTO.setHttpSessionID(httpSessionID);

String lockOnFinish = request.getParameter(VoteAppConstants.LOCK_ON_FINISH);
voteAuthoringForm.setLockOnFinish(lockOnFinish);
voteGeneralAuthoringDTO.setLockOnFinish(lockOnFinish);

String useSelectLeaderToolOuput = request.getParameter(VoteAppConstants.USE_SELECT_LEADER_TOOL_OUTPUT);
voteAuthoringForm.setUseSelectLeaderToolOuput(useSelectLeaderToolOuput);
voteGeneralAuthoringDTO.setUseSelectLeaderToolOuput(useSelectLeaderToolOuput);

String allowText = request.getParameter(VoteAppConstants.ALLOW_TEXT);
voteAuthoringForm.setAllowText(allowText);
voteGeneralAuthoringDTO.setAllowText(allowText);

String showResults = request.getParameter(VoteAppConstants.SHOW_RESULTS);
voteAuthoringForm.setShowResults(showResults);
voteGeneralAuthoringDTO.setShowResults(showResults);

String maxNominationCount = request.getParameter(VoteAppConstants.MAX_NOMINATION_COUNT);
voteAuthoringForm.setMaxNominationCount(maxNominationCount);
voteGeneralAuthoringDTO.setMaxNominationCount(maxNominationCount);

String minNominationCount = request.getParameter(MIN_NOMINATION_COUNT);
voteAuthoringForm.setMinNominationCount(minNominationCount);
voteGeneralAuthoringDTO.setMinNominationCount(minNominationCount);

String reflect = request.getParameter("reflect");
voteAuthoringForm.setReflect(reflect);
voteGeneralAuthoringDTO.setReflect(reflect);

String reflectionSubject = request.getParameter("reflectionSubject");
voteAuthoringForm.setReflectionSubject(reflectionSubject);
voteGeneralAuthoringDTO.setReflectionSubject(reflectionSubject);

String maxInputs = request.getParameter(VoteAppConstants.MAX_INPUTS);
if (maxInputs == null) {
    logger.info("Since minNomcount is equal to null hence setting it to '0'");
    maxInputs = "0";
}
voteAuthoringForm.setMaxInputs(new Short(maxInputs));

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());
   }
 
Example 14
Project: DWSurvey   File: UserAction.java   View Source Code Vote up 5 votes
public String save() throws Exception {
	HttpServletRequest request=Struts2Utils.getRequest();
	User user=accountManager.getCurUser();
	String email = request.getParameter("email");
	String cellphone = request.getParameter("cellphone");
	String name = request.getParameter("name");
	user.setEmail(email);
	user.setCellphone(cellphone);
	user.setName(name);
	accountManager.saveUp(user);
	return SUCCESS;
}
 
Example 15
Project: lams   File: LearningAction.java   View Source Code Vote up 5 votes
/**
    * Saves burning questions entered by user. It also updates its values in SessionMap.
    */
   private void saveBurningQuestions(HttpServletRequest request) {
initializeScratchieService();

String sessionMapID = WebUtil.readStrParam(request, ScratchieConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(sessionMapID);
final Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
Collection<ScratchieItem> items = (Collection<ScratchieItem>) sessionMap.get(ScratchieConstants.ATTR_ITEM_LIST);

for (ScratchieItem item : items) {
    final Long itemUid = item.getUid();

    final String burningQuestion = request.getParameter(ScratchieConstants.ATTR_BURNING_QUESTION_PREFIX + itemUid);
    // update question in sessionMap
    item.setBurningQuestion(burningQuestion);

    // update new entry
    service.saveBurningQuestion(sessionId, itemUid, burningQuestion);
}

// handle general burning question
final String generalQuestion = request.getParameter(ScratchieConstants.ATTR_GENERAL_BURNING_QUESTION);
service.saveBurningQuestion(sessionId, null, generalQuestion);
// update general question in sessionMap
sessionMap.put(ScratchieConstants.ATTR_GENERAL_BURNING_QUESTION, generalQuestion);
   }
 
Example 16
Project: redesocial   File: EstadoControle.java   View Source Code Vote up 5 votes
/**
 * Processa todas as requisições sejam elas do tipo GET ou POST
 * @param request requisição
 * @param response resposta
 * @throws javax.servlet.ServletException se ocorre um erro no Servlet
 * @throws java.io.IOException se ocorre um erro de entrada e saída
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String operacao = request.getParameter("operacao");

    try {
        switch (operacao){
            case "CriarNovo":
                this.criarNovo(request, response);
                break;
            case "Cadastrar":
                this.cadastrar(request, response);
                break;
            case "Listar":
                this.listar(request, response);
                break;
            case "Excluir":
                this.excluir(request, response);
                break;
            case "Editar":
                this.editar(request, response);
                break;
        }
    } catch (Exception ex){

    }
}
 
Example 17
Project: ralasafe   File: QueryTreeHandler.java   View Source Code Vote up 5 votes
public Node getNode(HttpServletRequest req){
	Query  query=new Query();
	int id=getId(req);
	int pid=getParentId(req);
	String name=req.getParameter("name");
	String desc=req.getParameter("description");
	boolean isLeaf=WebUtil.getBooleanParameter(req,"isLeaf", false);
	
	query.setId(id);
	query.setIsLeaf(isLeaf);
	query.setName(name);
	query.setPid(pid);
	query.setDescription(desc);
	return query;
}
 
Example 18
Project: Queue-Manager-Cloud-Dispatcher   File: PersistenceWithMS.java   View Source Code Vote up 5 votes
@Override
protected void doUndo(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException, SQLException {
	// TODO Auto-generated method stub
	String id = request.getParameter("Id");
       if (id != null && !id.trim().isEmpty()) {
       	int ID = Integer.parseInt(id);
       	int amount = msDAO.getAmount(COMPONENT, ID) - FIXEDVALUE;
       	msDAO.updateIncidentToPerson(id, amount, COMPONENT);
       }
       
       response.sendRedirect(LINKNAME);
}
 
Example 19
Project: logistimo-web-service   File: CreateEntityServlet.java   View Source Code Vote up 4 votes
private void createSystemConfiguration(HttpServletRequest req, HttpServletResponse resp,
                                       ConfigurationMgmtService cms)
    throws ServiceException, IOException {

  // Get the request parameters
  String userId = req.getParameter(USERID);
  String configType = req.getParameter("configtype");
  String details = req.getParameter("details");
  boolean hasErrors = false;

  // Check for parameter errors
  String strMessage = "";
  if (configType == null || configType.isEmpty()) {
    strMessage =
        "<b>The following errors have to be corrected:</b><br><br>No configuration type has been chosen. Please choose a configuration type.<br>";
    hasErrors = true;
  }
  if (details == null || details.isEmpty()) {
    strMessage +=
        "No configuration details have been provided. Please enter configuration details.<br>";
    hasErrors = true;
  }

  // Create a configuration object
  if (!hasErrors) { // implies no parameter errors
    try {
      // Validate the config. details
      ConfigValidator.validate(configType, details);

      // Create the config object and add to data store
      IConfig c = JDOUtils.createInstance(IConfig.class);
      c.setKey(configType);
      c.setConfig(details);
      c.setUserId(userId);
      c.setLastUpdated(new Date());
      cms.addConfiguration(configType, c);

      // Form return message
      strMessage =
          "Successfully created configuration for key '" + configType
              + "'. &nbsp;&nbsp;[<a href=\"/s/admin/system_configuration.jsp?configtype="
              + configType + "\">view configuration</a>]";
    } catch (ConfigurationException e) {
      xLogger.severe("Exception when creating configuration: {0}", e.getMessage());
      strMessage =
          "<b>Configuration detail format is invalid.</b><br><br>" + "Error: " + e.getMessage()
              + "<br><br>Click the browser's Back button, correct errors and Save again.<br>";
    }
  } else {
    strMessage += "<br>Click 'Back' on browser to continue editing configuration.<br>";
  }

  writeToScreenWithMode(req, resp, strMessage, Constants.MODE_MANAGE,
      Constants.VIEW_SYSTEMCONFIGURATION);
}
 
Example 20
Project: lams   File: QaAction.java   View Source Code Vote up 4 votes
/**
    * opens up an new screen within the current page for editing a question
    */
   public ActionForward newEditableQuestionBox(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
QaAuthoringForm qaAuthoringForm = (QaAuthoringForm) form;

String httpSessionID = qaAuthoringForm.getHttpSessionID();

SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(httpSessionID);

String questionIndex = request.getParameter("questionIndex");

qaAuthoringForm.setEditableQuestionIndex(questionIndex);

List<QaQuestionDTO> questionDTOs = (List<QaQuestionDTO>) sessionMap.get(QaAppConstants.LIST_QUESTION_DTOS);

String editableQuestion = "";
String editableFeedback = "";
boolean requiredBoolean = false;
int minWordsLimit = 0;
Iterator<QaQuestionDTO> iter = questionDTOs.iterator();
while (iter.hasNext()) {
    QaQuestionDTO qaQuestionDTO = iter.next();
    String displayOrder = qaQuestionDTO.getDisplayOrder();

    if (displayOrder != null && !displayOrder.equals("")) {
	if (displayOrder.equals(questionIndex)) {
	    editableFeedback = qaQuestionDTO.getFeedback();
	    editableQuestion = qaQuestionDTO.getQuestion();
	    requiredBoolean = qaQuestionDTO.isRequired();
	    minWordsLimit = qaQuestionDTO.getMinWordsLimit();
	    break;
	}

    }
}

String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID);
qaAuthoringForm.setContentFolderID(contentFolderID);

String strToolContentID = request.getParameter(AttributeNames.PARAM_TOOL_CONTENT_ID);

String richTextTitle = request.getParameter(QaAppConstants.TITLE);
String richTextInstructions = request.getParameter(QaAppConstants.INSTRUCTIONS);

qaAuthoringForm.setTitle(richTextTitle);
qaAuthoringForm.setInstructions(richTextInstructions);

QaUtils.setFormProperties(request, qaAuthoringForm, strToolContentID, httpSessionID);

qaAuthoringForm.setRequired(requiredBoolean);
qaAuthoringForm.setMinWordsLimit(minWordsLimit);
qaAuthoringForm.setEditableQuestionText(editableQuestion);
qaAuthoringForm.setFeedback(editableFeedback);

request.setAttribute(QaAppConstants.TOTAL_QUESTION_COUNT, new Integer(questionDTOs.size()));

return mapping.findForward("editQuestionBox");
   }