Java Code Examples for javax.servlet.http.HttpSession

The following are top voted examples for showing how to use javax.servlet.http.HttpSession. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Monsters_Portal   File: PedidoController.java   View source code 8 votes vote down vote up
@RequestMapping("Admin/RestorePedido")
public void restore(HttpSession session, Long id, HttpServletResponse response) {
	if(Permissoes.checar(session, EnumMetodo.RESTAURAR, entidade)){			//	Consulta a permissão
		dao.restore(id);													//	Ação no banco
		relatorio.gerarRelatorio(session, EnumMetodo.RESTAURAR, entidade);	//	Gera Relatório e armazena no banco
		response.setStatus(200);											//	Indica para a requisição AJAX que tudo ocorreu bem
	}
}
 
Example 2
Project: EasyHousing   File: AdminRentController.java   View source code 8 votes vote down vote up
@RequestMapping(value="adminAddRentHouseDeal.do", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView adminAddRentHouseDeal(@RequestParam(value ="inputTime") @DateTimeFormat(pattern="yyyy-MM-dd") Date date,HttpServletRequest request, RentHouseDeal rentHouseDeal) {
	ModelAndView modelAndView = new ModelAndView();
	HttpSession session = request.getSession();
	rentHouseDeal.setRentTime(date);
	
	System.err.println("ctbb");
	System.err.println(date);
	System.err.println(rentHouseDeal.getRentHouseDay());
	System.err.println(rentHouseDeal.getRentTime());
	
	rentHouseDealDao.insertRentHouseDeal(rentHouseDeal);
	
	List<RentHouseDeal> rentHouseDealList = rentHouseDealDao.selectAll();
	session.setAttribute("rentHouseDealList", rentHouseDealList);
	
	modelAndView.setViewName("SystemUser/managerRentHistory");
	return modelAndView;
}
 
Example 3
Project: LojaDeInstrumentosMusicais   File: ConsultaClientesVendaServlet.java   View source code 7 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
      HttpSession sessao = request.getSession();  
      ArrayList<Cliente> Lista = new ArrayList();
      ServicoCliente sc = new ServicoCliente();
      String codigoempresa = (String) sessao.getAttribute("Empresa");
      
      try {
        Lista = (ArrayList<Cliente>) sc.procurarCliente("", Integer.parseInt(codigoempresa));
    } catch (Exception e) {
    }
    
      sessao.setAttribute("ListaClientes", Lista);
      
      RequestDispatcher dispatcher
 = request.getRequestDispatcher("/venda.jsp");
dispatcher.forward(request, response);
    
    
}
 
Example 4
Project: belling-admin   File: OnlineNoticeServer.java   View source code 7 votes vote down vote up
/**
 * 连接建立成功调用的方法-与前端JS代码对应
 * 
 * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
 */
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
	// 单个会话对象保存
	this.session = session;
	webSocketSet.add(this); // 加入set中
	this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
	String uId = (String) httpSession.getAttribute("userid"); // 获取当前用户
	String sessionId = httpSession.getId();
	this.userid = uId + "|" + sessionId;
	if (!OnlineUserlist.contains(this.userid)) {
		OnlineUserlist.add(userid); // 将用户名加入在线列表
	}
	routetabMap.put(userid, session); // 将用户名和session绑定到路由表
	System.out.println(userid + " -> 已上线");
	String message = getMessage(userid + " -> 已上线", "notice", OnlineUserlist);
	broadcast(message); // 广播
}
 
Example 5
Project: LojaDeInstrumentosMusicais   File: ExcluirProdutoServlet.java   View source code 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
    //Instância serviço de servidor para efetuar consulta e ligação com ClienteDAO
    ServicoProduto sp = new ServicoProduto();
    
    //Criação se sessão para retorno em tela
    HttpSession sessao = request.getSession();
    
    
    //Atribuição de valores digitados na tela de fornecedor e código da empresa
    String codigoproduto = request.getParameter("codigoproduto");
    String codigoempresa = (String) sessao.getAttribute("Empresa");
        
    try {
        sp.excluirProduto(Integer.parseInt(codigoproduto), Integer.parseInt(codigoempresa));
    } catch (Exception e) {
    }
    
    sessao.setAttribute("produtoexcluido", codigoproduto);
    response.sendRedirect(request.getContextPath() + "/consultarProduto.jsp");

    }
 
Example 6
Project: lams   File: LearnerAction.java   View source code 6 votes vote down vote up
public ActionForward deleteLearnerFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
HttpSession ss = SessionManager.getSession();


UserDTO currentUser = (UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER);
Long detailID = WebUtil.readLongParam(request, "detailId");

if (submitFilesService == null) {
    submitFilesService = getSubmitFilesService();
}
FileDetailsDTO fileDetail = submitFilesService.getFileDetails(detailID, request.getLocale());

if (fileDetail.getOwner().getUserID().equals(currentUser.getUserID()) && (StringUtils.isBlank(fileDetail.getMarks()))) {

    submitFilesService.removeLearnerFile(detailID,null);

} else {
  response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not allowed to delete this item");
}
return null;
   }
 
Example 7
Project: atbash-octopus   File: ServletContainerSessionManager.java   View source code 6 votes vote down vote up
public Session getSession(SessionKey key) throws SessionException {
    /*
    if (!WebUtils.isHttp(key)) {
        String msg = "SessionKey must be an HTTP compatible implementation.";
        throw new IllegalArgumentException(msg);
    }
    */

    HttpServletRequest request = key.getServletRequest();

    Session session = null;

    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        session = createSession(httpSession, request.getRemoteHost());
    }

    return session;

}
 
Example 8
Project: Trabalhos-FIAP   File: AdminFilter.java   View source code 6 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) req;
       HttpServletResponse response = (HttpServletResponse) res;
       
       HttpSession session = request.getSession(false);
       
       String redirecionamento = request.getContextPath() + "/login.xhtml";
       
       if (session == null || session.getAttribute("usuario") == null) {
       	response.sendRedirect(redirecionamento);
       } else {
       	Usuario usuario = (Usuario) session.getAttribute("usuario");
       	
       	if(!usuario.getAdmin()) {
       		response.sendRedirect(redirecionamento);
       	} else {
       		chain.doFilter(request, response);
       	}
       }
}
 
Example 9
Project: codemotion-2017-taller-de-jhipster   File: CustomAuditEventRepositoryIntTest.java   View source code 6 votes vote down vote up
@Test
public void testAddEventWithWebAuthenticationDetails() {
    HttpSession session = new MockHttpSession(null, "test-session-id");
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setSession(session);
    request.setRemoteAddr("1.2.3.4");
    WebAuthenticationDetails details = new WebAuthenticationDetails(request);
    Map<String, Object> data = new HashMap<>();
    data.put("test-key", details);
    AuditEvent event = new AuditEvent("test-user", "test-type", data);
    customAuditEventRepository.add(event);
    List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
    assertThat(persistentAuditEvents).hasSize(1);
    PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
    assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4");
    assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id");
}
 
Example 10
Project: lams   File: LearningAction.java   View source code 6 votes vote down vote up
/**
    * Display empty reflection form.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    */
   public ActionForward newReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {

initKalturaService();

// get session value
String sessionMapID = WebUtil.readStrParam(request, KalturaConstants.ATTR_SESSION_MAP_ID);

ReflectionForm refForm = (ReflectionForm) form;
HttpSession ss = SessionManager.getSession();
UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);

refForm.setUserID(user.getUserID());
refForm.setSessionMapID(sessionMapID);

SessionMap<String, Object> map = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
Long toolSessionID = (Long) map.get(AttributeNames.PARAM_TOOL_SESSION_ID);
NotebookEntry entry = service.getEntry(toolSessionID, user.getUserID());

if (entry != null) {
    refForm.setEntryText(entry.getEntry());
}

return mapping.findForward(KalturaConstants.NOTEBOOK);
   }
 
Example 11
Project: EasyHousing   File: AdminRentController.java   View source code 6 votes vote down vote up
@RequestMapping(value="adminAddRentHouse.do", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView adminAddRentHouse(@RequestParam(value ="inputPublishTime1") @DateTimeFormat(pattern="yyyy-MM-dd") Date inputPublishTime,HttpServletRequest request, RentHouse rentHouse) {
	
	ModelAndView modelAndView = new ModelAndView();
	HttpSession session = request.getSession();
	
	//设置表单时间
	rentHouse.setRentHousePublishTime(inputPublishTime);
	System.err.println(inputPublishTime);
	
	rentHouseDao.insertRentHouse(rentHouse);
	
	List<RentHouse> rentHouseList = rentHouseDao.selectAllRentHouse();
	session.setAttribute("rentHouseList", rentHouseList);
	
	modelAndView.setViewName("SystemUser/managerRent");
	return modelAndView;
}
 
Example 12
Project: ImageClassify   File: AdminInterceptor.java   View source code 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8"); 
	HttpSession session = request.getSession();
	if (!"".equals(session.getAttribute(Constant.USERNAME))&& session.getAttribute(Constant.USERNAME)!=null && !"".equals(session.getAttribute(Constant.TOKEN)) && session.getAttribute(Constant.TOKEN)!=null ) {
		return true; 
	} else {
		PrintWriter out;  
		out = response.getWriter();
		String json;
		Gson gson = new Gson();
		Message<String> message = new Message<String>("-200","管理员未登录,请重新登录","");//初始化message对象
           json = gson.toJson(message, Message.class); //使用gson将Message对象转化为字符串
		out.print(json);  
		return false;
	}
		
}
 
Example 13
Project: Guestbook9001   File: SessionInvalidationFilter.java   View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpSession session = request.getSession(true);
    Long lastActiveObject = (Long) session.getAttribute(LAST_ACTIVE_SESSION_ATTRIBUTE);
    long currentTime = System.currentTimeMillis();

    if(lastActiveObject != null) {
        long lastActive = lastActiveObject.longValue();
        if(currentTime - lastActive > SESSION_TIMEOUT) {
            LOG.info(String.format("Invalidated session of %s due to timeout", LogUtil.getUserInfo(request)));
            session.invalidate();
            session = request.getSession(true);
        }
    }

    session.setAttribute(LAST_ACTIVE_SESSION_ATTRIBUTE, Long.valueOf(currentTime));

    filterChain.doFilter(request, servletResponse);
}
 
Example 14
Project: mmall   File: CategoryManageController.java   View source code 6 votes vote down vote up
/**
 * 更新类品接口
 * @param session
 * @param categoryName
 * @param categoryId
 * @return
 */
@RequestMapping(value = "updateCategoryInfo.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse updateCategoryInfo(HttpSession session,String categoryName,Integer categoryId){
    User user = (User) session.getAttribute(Const.CURRENT_USER);
    if (user == null){
        return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"请先登录");
    }
    //判断这个用户是不是管理员
    ServerResponse<String> checkRoleResult = iUserService.checkUserRole(user);
    if (checkRoleResult.isSuccess()){
        //添加类品
        return iCategoryService.updateCategoryInfo(categoryName, categoryId);
    } else {
        return ServerResponse.createByError("对不起,您没有管理员权限");
    }
}
 
Example 15
Project: spring-io   File: CustomAuditEventRepositoryIntTest.java   View source code 6 votes vote down vote up
@Test
public void testAddEventWithWebAuthenticationDetails() {
    HttpSession session = new MockHttpSession(null, "test-session-id");
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setSession(session);
    request.setRemoteAddr("1.2.3.4");
    WebAuthenticationDetails details = new WebAuthenticationDetails(request);
    Map<String, Object> data = new HashMap<>();
    data.put("test-key", details);
    AuditEvent event = new AuditEvent("test-user", "test-type", data);
    customAuditEventRepository.add(event);
    List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
    assertThat(persistentAuditEvents).hasSize(1);
    PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
    assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4");
    assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id");
}
 
Example 16
Project: opencron   File: RecordService.java   View source code 6 votes vote down vote up
public ChartVo getAsProgress(HttpSession session) {
    String sql = "SELECT " +
            "sum(CASE R.success WHEN 0 THEN 1 ELSE 0 END) failure, " +
            "sum(CASE R.success WHEN 1 THEN 1 ELSE 0 END) success, " +
            "sum(CASE R.success WHEN 2 THEN 1 ELSE 0 END) killed, " +
            "sum(CASE R.jobType WHEN 0 THEN 1 ELSE 0 END) singleton, " +
            "sum(CASE R.jobType WHEN 1 THEN 1 ELSE 0 END) flow, " +
            "sum(CASE J.cronType WHEN 0 THEN 1 ELSE 0 END) crontab, " +
            "sum(CASE J.cronType WHEN 1 THEN 1 ELSE 0 END) quartz, " +
            "sum(CASE R.execType WHEN 0 THEN 1 ELSE 0 END) auto, " +
            "sum(CASE R.execType WHEN 1 THEN 1 ELSE 0 END) operator, " +
            "sum(CASE R.redoCount>0 WHEN 1 THEN 1 ELSE 0 END) rerun " +
            "FROM T_RECORD R LEFT JOIN T_JOB J ON R.jobid=J.jobid WHERE 1=1 ";

    if (!OpencronTools.isPermission(session)) {
        User user = OpencronTools.getUser(session);
        sql += " AND R.userId = " + user.getUserId() + " AND R.agentId in (" + user.getAgentIds() + ")";
    }
    return queryDao.sqlUniqueQuery(ChartVo.class, sql);
}
 
Example 17
Project: bicycleSharingServer   File: IndexController.java   View source code 6 votes vote down vote up
/**
 * 3.管理员登录执行
 *
 * @return index/index_content.jsp
 */
@RequestMapping(value = "admin-index-login-execute", method = RequestMethod.POST)
public String loginExecute(Map<String, Object> requestMap, HttpSession session,
                           @RequestParam("name") String name, @RequestParam("password") String password) {
    int loginSuccess = adminService.login(name, password);
    String view = "redirect:/admin-index-index-show";
    if (loginSuccess == 1) { //登录成功
        Admin admin = adminService.getAdminByName(name);
        requestMap.put("admin", admin);
        session.setAttribute("admin", admin);
    } else { //登录失败
        requestMap.put("adminLoginError", "1");
        view = "index/index_login";
    }
    return view;
}
 
Example 18
Project: parabuild-ci   File: HttpServletRequestTest.java   View source code 6 votes vote down vote up
/**
 * Verifies that a request with a bad session ID causes a new session to be generated only when explicitly requested.
 */
public void testGetSessionWithBadCookie() throws Exception {
    WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
    ServletUnitContext context = new ServletUnitContext();
    ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );

    HttpSession originalSession = context.newSession();
    String originalID = originalSession.getId();
    request.addCookie( new Cookie( ServletUnitHttpSession.SESSION_COOKIE_NAME, originalID ) );
    request.getSession();

    String badID = originalID + "BAD";
    request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );
    request.addCookie( new Cookie( ServletUnitHttpSession.SESSION_COOKIE_NAME, badID ) );

    assertNull( "Unexpected session returned for bad cookie", request.getSession( false ) );
    assertNotNull( "Should have returned session when asked", request.getSession( true ));
    assertNotSame( "Created session", originalSession, request.getSession( true ) );
}
 
Example 19
Project: zhkuas_ssm_maven   File: AdminController.java   View source code 6 votes vote down vote up
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(String username,String password,HttpSession session,HttpServletRequest request){
	Admin admin  = new Admin();
	admin.setUsername(username);
	admin.setPassword(password);
	//校验用户名密码
	if(admin.getUsername()==null||admin.getUsername().equals("")){
		request.setAttribute("result", "用户名不能为空!");
		return "admin_login";
	}else if(admin.getPassword()==null||admin.getPassword().equals("")){
		request.setAttribute("result", "密码不能为空!");
		return "admin_login";
	}
	
	//将password md5加密
	admin.setPassword(ServiceUtils.toMD5(admin.getPassword()));
	admin=adminService.findAdmin(admin);
	if(admin==null){
		request.setAttribute("result", "用户名或者密码错误!");
		return "admin_login";
	}
	session.setAttribute(Constants.SessionKey.ADMIN_USER.toString(), admin);
	return "redirect:index";
}
 
Example 20
Project: Equella   File: UserSessionServiceImpl.java   View source code 6 votes vote down vote up
private void clearSession()
{
	final HttpSession session = getCurrentSession(false);
	if( session != null )
	{
		synchronized( session )
		{
			final String keyPrefix = getKeyPrefix().toString();

			for( Enumeration<?> e = session.getAttributeNames(); e.hasMoreElements(); )
			{
				String name = (String) e.nextElement();
				if( name.startsWith(keyPrefix) )
				{
					session.removeAttribute(name);
				}
			}
		}
	}
}
 
Example 21
Project: parabuild-ci   File: ServletUtilities.java   View source code 6 votes vote down vote up
/**
 * Adds a {@link ChartDeleter} object to the session object with the name 
 * <code>JFreeChart_Deleter</code> if there is not already one bound to the 
 * session and adds the filename to the list of charts to be deleted.
 *
 * @param tempFile  the file to be deleted.
 * @param session  the HTTP session of the client.
 */
protected static void registerChartForDeletion(File tempFile, 
        HttpSession session) {

    //  Add chart to deletion list in session
    if (session != null) {
        ChartDeleter chartDeleter 
            = (ChartDeleter) session.getAttribute("JFreeChart_Deleter");
        if (chartDeleter == null) {
            chartDeleter = new ChartDeleter();
            session.setAttribute("JFreeChart_Deleter", chartDeleter);
        }
        chartDeleter.addChart(tempFile.getName());
    }
    else {
        System.out.println("Session is null - chart will not be deleted");
    }
}
 
Example 22
Project: jira-confluence-javamelody   File: JiraMonitoringFilter.java   View source code 6 votes vote down vote up
private void putRemoteUserInSession(HttpServletRequest httpRequest) {
	final HttpSession session = httpRequest.getSession(false);
	if (session != null && session.getAttribute(SessionListener.SESSION_REMOTE_USER) == null) {
		// si session null, la session n'est pas encore créée (et ne le sera
		// peut-être jamais),
		try {
			final Object user = getUser(session);
			// objet utilisateur, peut être null
			if (user instanceof Principal) {
				final String remoteUser = ((Principal) user).getName();
				session.setAttribute(SessionListener.SESSION_REMOTE_USER, remoteUser);
			}
		} catch (final Exception e) {
			// tant pis
			return;
		}
	}
}
 
Example 23
Project: timesheet-upload   File: IndexController.java   View source code 6 votes vote down vote up
@GetMapping("/settings")
public String settings(HttpSession session, Model model) {
    log.info("Inside settings method of IndexController");
    Employee employee = (Employee) session.getAttribute("user");
    //Check if the employee object exist in the session.
    if (employee == null) {
        log.error("Cannot find employee object in the session, so forwarding to Login page");
        model.addAttribute("css", "danger");
        model.addAttribute("msg", "Your session expired, please login to continue!!");
        return "redirect:/login";
    }
    //Check for employee role and forward to corresponding page.
    if (employee.isEmployeeRole()) {
        return "employee/settings";
    } else if (employee.isSupervisorRole()) {
        return "staff/settings";
    } else if (employee.isAdminRole()) {
        return "staff/settings";
    } else {
        log.error("Cannot validate the role. Redirecting to the Login page.");
        model.addAttribute("css", "danger");
        model.addAttribute("msg", "Cannot validate the role, please login to continue!!");
        return "redirect:/login";
    }
}
 
Example 24
Project: lazycat   File: CometConnectionManagerValve.java   View source code 6 votes vote down vote up
/**
 * Register requests for tracking, whenever needed.
 *
 * @param request
 *            The servlet request to be processed
 * @param response
 *            The servlet response to be created
 *
 * @exception IOException
 *                if an input/output error occurs
 * @exception ServletException
 *                if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
	// Perform the request
	getNext().invoke(request, response);

	if (request.isComet() && !response.isClosed()) {
		// Start tracking this connection, since this is a
		// begin event, and Comet mode is on
		HttpSession session = request.getSession(true);

		// Track the connection for webapp reload
		cometRequests.add(request);

		// Track the connection for session expiration
		synchronized (session) {
			Request[] requests = (Request[]) session.getAttribute(cometRequestsAttribute);
			if (requests == null) {
				requests = new Request[1];
				requests[0] = request;
				session.setAttribute(cometRequestsAttribute, requests);
			} else {
				Request[] newRequests = new Request[requests.length + 1];
				for (int i = 0; i < requests.length; i++) {
					newRequests[i] = requests[i];
				}
				newRequests[requests.length] = request;
				session.setAttribute(cometRequestsAttribute, newRequests);
			}
		}
	}

}
 
Example 25
Project: lams   File: ExtendedAccessLogValve.java   View source code 6 votes vote down vote up
public void addElement(StringBuffer buf, Date date, Request request,
        Response response, long time) {
    HttpSession session = null;
    if (request != null) {
        session = request.getSession(false);
        if (session != null)
            buf.append(wrap(session.getAttribute(attribute)));
    }
}
 
Example 26
Project: MaximoForgeViewerPlugin   File: BIMViewer.java   View source code 6 votes vote down vote up
/**
 * Retrieves a stored resize option from the HTTP session and makes it 
 * available to the .jsp.  This version is used when the viewer is
 * displayed on an application main tab
 * @return
 */
public int jspGetRezieOption()
{
	HttpServletRequest thisRequest = _wcs.getRequest();
    HttpSession session = thisRequest.getSession();
    Object o = session.getAttribute( ATTRIB_RESIZE );
    if( o == null || !(o instanceof String) )
    {
    	return 0;
    }
    String option = (String)o;
    if( option.length() == 0 )
    {
    	return 0;
    }
    return Integer.parseInt( option );
}
 
Example 27
Project: sjk   File: UserController.java   View source code 6 votes vote down vote up
/**
 * 普通用户修改密码
 * 
 * @param keywords
 * @param request
 * @param model
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/update-pwd.d", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public @ResponseBody
String updatePWD(@RequestParam("o_pwd") String oldPwd, @RequestParam("n_pwd") String newPwd, HttpSession session,
        Model model, HttpServletResponse resp) throws IOException {
    User u = (User) session.getAttribute("user");
    JSONObject json = new JSONObject();
    if (u == null) {
        json.put("status", false);
        json.put("msg", "登陆超时,请重新登陆。");
        return json.toJSONString();
    }
    if (!u.getPassword().equals(PWDHelper.escape(oldPwd))) {
        json.put("status", false);
        json.put("msg", "原密码不对");
        return json.toJSONString();
    } else {
        newPwd = PWDHelper.escape(newPwd);
        service.updatePwd(u.getId(), newPwd);
        json.put("status", true);
        json.put("msg", "更新成功");
        return json.toJSONString();
    }
}
 
Example 28
Project: timesheet-upload   File: GlobalExceptionHandler.java   View source code 6 votes vote down vote up
@ExceptionHandler({CustomException.class})
public ModelAndView handleCustomException(Exception excptn, HttpServletRequest request) {
    HttpSession session = request.getSession(false);

    ModelAndView model = new ModelAndView("error");
    CustomException ex = (CustomException) excptn;

    AppErrorInfo errorInfo = new AppErrorInfo();
    errorInfo.setErrorCode(ex.getErrorCode());
    errorInfo.setErrorDetails(ex.getErrorDetails());
    errorInfo.setErrorMessage(messageSource.getMessage(ex.getErrorCode(),
            new String[]{}, Locale.US));
    errorInfo.setHttpStatusCode(ex.getHttpStatusCode());
    errorInfo.setSessionId(session.getId());
    StringWriter sw = new StringWriter();
    ex.printStackTrace(new PrintWriter(sw));
    String s = sw.toString();
    errorInfo.setStackTrace(s);
    errorInfo.setTimeStamp(System.currentTimeMillis());
    model.addObject("errorInfo", errorInfo);
    return model;
}
 
Example 29
Project: full-javaee-app   File: AdministratorClientUpdateServlet.java   View source code 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	HttpSession session = request.getSession();
	int clientID = Integer.parseInt(request.getParameter("clientID"));

	HashMap<String, String> details = new HashMap<String, String>();
	details.put("firstName", request.getParameter("firstName").trim());
	details.put("lastName", request.getParameter("lastName").trim());
	details.put("companyID", request.getParameter("companyID"));
	details.put("email", request.getParameter("email").trim().toLowerCase());
	details.put("password", request.getParameter("password").length() < 4 ? "Unchanged" : request.getParameter("password"));
	details.put("viewLimit", request.getParameter("viewLimit").trim());
	details.put("geoLimit", request.getParameter("geoLimit").trim());
	details.put("approved", request.getParameter("approved"));

	try {
		Clients client = ClientPersistence.getByID(clientID);
		client = ClientPersistence.update(details, client);
		List<Clients> clientList = ClientPersistence.getAll();
		session.setAttribute("clientList", clientList);
		response.sendRedirect("admin/admin-client-list.jsp");
	} catch (Exception e) {
		session.setAttribute("clientError", "Failed to create account. Code:" + e);
		response.sendRedirect("admin/admin-client-list.jsp");
	}
}
 
Example 30
Project: Projeto_Integrador_3_Semestre   File: CadastroHotelServlet.java   View source code 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HotelService service = new HotelService();
    HotelDAO dao = new HotelDAO();

    RelatorioDAO relatorioDAO = new RelatorioDAO();
    RelatorioMudancas relatorio = new RelatorioMudancas();

    String nome_hotel = request.getParameter("nome_hotel");
    String data_entrada = request.getParameter("data_entrada");
    String data_saida = request.getParameter("data_saida");
    int quantidade_quartos = Integer.parseInt(request.getParameter("quantidade_quartos"));
    int quantidade_hospedes = Integer.parseInt(request.getParameter("quantidade_hospedes"));
    float preco = Float.parseFloat(request.getParameter("preco"));

    request.setAttribute("erroNome_hotel", service.validaNome(nome_hotel));
    request.setAttribute("erroData_entrada", service.validaEntrada(data_entrada));
    request.setAttribute("erroData_saida", service.validaSaida(data_saida));
    request.setAttribute("erroQuantidade_quartos", service.validaQuantidade_quartos(quantidade_quartos));
    request.setAttribute("erroQuantidade_hospedes", service.validaQuantidade_hospedes(quantidade_hospedes));
    request.setAttribute("erroPreco", service.validaPreco(preco));

    Hotel hotel = new Hotel(nome_hotel.trim(), data_entrada.trim(), data_saida.trim(),
            quantidade_quartos, quantidade_hospedes, preco, true);

    if (service.validaHotel(nome_hotel, quantidade_quartos, data_entrada, data_saida, quantidade_hospedes, preco)) {
        RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/CadastroHotel.jsp");
        dispatcher.forward(request, response);
    } else {
        try {

            dao.inserir(hotel);
            HttpSession sessao = request.getSession();
            int identificacaoF = (int) sessao.getAttribute("id_func");
            relatorio.setId_func(identificacaoF);
            relatorio.setMudanca("Cadastro de hotel efetuado!");
            relatorioDAO.inserir(relatorio);
            response.sendRedirect(request.getContextPath() + "/inicio");

        } catch (Exception ex) {

            Logger.getLogger(CadastroHotelServlet.class.getName()).log(Level.SEVERE, null, ex);

        }
    }
}
 
Example 31
Project: EasyHousing   File: adminAgentController.java   View source code 5 votes vote down vote up
@RequestMapping(value="adminAddAgent.do", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView adminAddAgent(HttpServletRequest request, Agent agent) {
	ModelAndView modelAndView = new ModelAndView();
	HttpSession session = request.getSession();
	agent.setPicUrl("http://os8z6i0zb.bkt.clouddn.com/defaultPhoto.png"); //设置默认头像

	//插入用户上传的图片链接地址
	try {
		// 得到文件
		String path = request.getSession().getServletContext().getRealPath("upload");
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator iter = multiRequest.getFileNames();
		MultipartFile file = multiRequest.getFile(iter.next().toString());
		String fileName = file.getOriginalFilename();
		File dir = new File(path, fileName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		// MultipartFile自带的解析方法
		file.transferTo(dir);
		
		String filePath = path + "\\" + fileName;
		System.err.println(filePath);
		String name = new Date().toInstant().toString();
		new Tool().upload(filePath, name);
		agent.setPicUrl(String.valueOf("http://os8z6i0zb.bkt.clouddn.com/" + name));
	} catch (Exception e) {
		
	}
	
	agentDao.insertAgent(agent);  //插入数据
	
	//更新显示层的经纪人列表
	List<Agent> agentList = agentDao.selectAll();
	session.setAttribute("agentList", agentList);
	
	modelAndView.setViewName("SystemUser/managerAgent");
	return modelAndView;
}
 
Example 32
Project: lams   File: MonitoringAction.java   View source code 5 votes vote down vote up
/**
    * Set Submission Deadline
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws IOException
    */
   public ActionForward setSubmissionDeadline(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException {

IVoteService voteService = VoteServiceProxy.getVoteService(getServlet().getServletContext());

Long contentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID);
VoteContent voteContent = voteService.getVoteContent(contentID);

Long dateParameter = WebUtil.readLongParam(request, VoteAppConstants.ATTR_SUBMISSION_DEADLINE, true);
Date tzSubmissionDeadline = null;
String formattedDate = "";
if (dateParameter != null) {
    Date submissionDeadline = new Date(dateParameter);
    HttpSession ss = SessionManager.getSession();
    org.lamsfoundation.lams.usermanagement.dto.UserDTO teacher = (org.lamsfoundation.lams.usermanagement.dto.UserDTO) ss
	    .getAttribute(AttributeNames.USER);
    TimeZone teacherTimeZone = teacher.getTimeZone();
    tzSubmissionDeadline = DateUtil.convertFromTimeZoneToDefault(teacherTimeZone, submissionDeadline);
    formattedDate = DateUtil.convertToStringForJSON(tzSubmissionDeadline, request.getLocale());
}
voteContent.setSubmissionDeadline(tzSubmissionDeadline);
voteService.updateVote(voteContent);
response.setContentType("text/plain;charset=utf-8");
response.getWriter().print(formattedDate);
return null;
   }
 
Example 33
Project: jmzTab-m   File: ValidationController.java   View source code 5 votes vote down vote up
@GetMapping(value = "/validate/{filename:.+}")
public ModelAndView validateFile(@PathVariable String filename, @QueryParam(
    "version") ValidationService.MzTabVersion version, @QueryParam(
    "maxErrors") int maxErrors, HttpServletRequest request,
    HttpSession session) {
    if (session == null) {
        UriComponents uri = ServletUriComponentsBuilder
            .fromServletMapping(request).
            build();
        return new ModelAndView(
            "redirect:" + uri.toUriString());
    }
    ModelAndView modelAndView = new ModelAndView("validationResult");
    modelAndView.
        addObject("page", new Page("mzTabValidator", versionNumber, gaId));
    modelAndView.addObject("validationFile", filename);
    ValidationService.MzTabVersion validationVersion = version;
    if (validationVersion != null) {
        modelAndView.addObject("validationVersion", validationVersion);
    } else {
        validationVersion = ValidationService.MzTabVersion.MZTAB_1_1;
        modelAndView.addObject("validationVersion", validationVersion);
    }
    if (maxErrors > 0) {
        modelAndView.addObject("validationMaxErrors", maxErrors);
    } else {
        modelAndView.addObject("validationMaxErrors", 100);
    }
    UserSessionFile usf = new UserSessionFile(filename, session.getId());
    modelAndView.addObject("validationResults", validationService.
        asValidationResults(validationService.validate(
            validationVersion, usf, maxErrors)));
    return modelAndView;
}
 
Example 34
Project: parabuild-ci   File: MergeStatusesPage.java   View source code 5 votes vote down vote up
/**
 * @noinspection UNUSED_SYMBOL,UnusedDeclaration
 */
private void showDashboardView(final HttpSession session, final int displayGroupID) {
  setTitle(makeTitle(CAPTION_MERGE_LIST_DASHBOARD_VIEW));
  final List currentMergesStatuses = getUserMergeStates(displayGroupID);
  final DashboardStatusesPanel dashboardStatusesPanel = new DashboardStatusesPanel();
  baseContentPanel().getUserPanel().add(dashboardStatusesPanel);
  dashboardStatusesPanel.populate(currentMergesStatuses);
  markSessionAsDashboard(session);
  lnkStatusesViewSwitch.setDashboardViewSelected();

  // set cookie to rememeber selection
  setStatusViewCookie(Pages.STATUS_VIEW_DASHBOARD);
}
 
Example 35
Project: photoiff   File: Logout.java   View source code 5 votes vote down vote up
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	final HttpSession sessao = request.getSession(false);
	
	if(sessao != null) {
		sessao.invalidate();
	}
	
	response.sendRedirect(request.getContextPath());
}
 
Example 36
Project: convertigo-engine   File: CheckAuthentication.java   View source code 5 votes vote down vote up
@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
	HttpSession httpSession = request.getSession();
	
	// Handle anonymous access for test platform user
	if (EnginePropertiesManager.getProperty(PropertyName.TEST_PLATFORM_USERNAME).length() == 0) {
		if (!Engine.authenticatedSessionManager.isAuthenticated(httpSession)) {
			Engine.authenticatedSessionManager.addAuthenticatedSession(httpSession, new Role[] { Role.TEST_PLATFORM });
		}
	}
	
	boolean bAuthenticated = Engine.authenticatedSessionManager.isAuthenticated(httpSession);
	Role[] roles = Engine.authenticatedSessionManager.getRoles(httpSession);
	if (roles != null) {
		Engine.logAdmin.info("Added roles: " + Arrays.toString(roles));
		ServiceUtils.addRoleNodes(document.getDocumentElement(), roles);
	}
	
	if (bAuthenticated) {
		Engine.logAdmin.info("Check authentication success");
		ServiceUtils.addMessage(document, document.getDocumentElement(), "" + httpSession.getAttribute(SessionKey.ADMIN_USER.toString()), "user", false);
		ServiceUtils.addMessage(document, document.getDocumentElement(), "true", "authenticated", false);
	} else {
		Engine.logAdmin.info("Check authentication failed (no role defined)");
		ServiceUtils.addMessage(document, document.getDocumentElement(), "false", "authenticated", false);
	}
}
 
Example 37
Project: oscm   File: AuthorizationFilter.java   View source code 5 votes vote down vote up
/**
 * Cache the marketplaces. If BES acts as reverse proxy, it is important
 * that no SQL requests are performed. Otherwise for each HTTP request
 * (html, css, images, ajax) that is performed for the target system several
 * SQL requests would be performed on BES side. BES would be dead long time
 * before the target system gets busy.
 */
@SuppressWarnings("unchecked")
private Map<String, VOMarketplace> getMarketplaceMapFromSession(
        HttpSession session) {
    Map<String, VOMarketplace> map = (Map<String, VOMarketplace>) session
            .getAttribute(Constants.SESS_ATTR_MARKETPLACE_MAP);
    if (map != null) {
        return map;
    }
    map = new ConcurrentHashMap<>();
    session.setAttribute(Constants.SESS_ATTR_MARKETPLACE_MAP, map);
    return map;
}
 
Example 38
Project: unitimes   File: SessionListener.java   View source code 5 votes vote down vote up
/**
   * Listener Event when session is destroyed
   */
  public void sessionDestroyed(HttpSessionEvent se) {
      HttpSession session = se.getSession();
sessions.remove(session.getId());
      if(activeSessions > 0) {
	activeSessions--;
}

      Debug.info("TT Session ended ... " + session.getId() + " " +  new Date());
      Debug.info("    - TT Session time ... " +  
              ( (new Date().getTime() - session.getCreationTime())/(1000*60) ) + " minutes" );
      
      session.invalidate();
  }
 
Example 39
Project: CheapStore   File: CartAction.java   View source code 5 votes vote down vote up
@RequestMapping(value = "add.do",method = RequestMethod.POST)
public @ResponseBody CartServerResponse cartAddProduct(int productId,int count,HttpSession session){
    User user = (User) session.getAttribute(Const.CURRENT_USER);
    CartServerResponse cartServerResponse = new CartServerResponse(10,"用户未登录,请登录");
    if(user != null){
        cartServerResponse = cartService.cartAddProduct(user.getId(),productId,count);
    }
    return cartServerResponse;
}
 
Example 40
Project: dashboard1b   File: AdminController.java   View source code 5 votes vote down vote up
@RequestMapping(value="/admin/edit/editSuggestion")
 	public String editSuggestion(@RequestParam String titulo,
 			@RequestParam String contenido,HttpSession session){
 		//ESTO AHORA
Set<Suggestion> lista = (Set<Suggestion>) session.getAttribute("sugerencias");
sugerencias=lista;
 		Suggestion suggestion = (Suggestion) session.getAttribute("sugerencia");
 		Suggestion suggestion2 = suggestion;
 		
 		sugerencias.remove(suggestion);
 		
 		if(!titulo.equals(""))
 			suggestion2.setTitle(titulo);
 		if(!contenido.equals(""))
 		suggestion2.setContent(contenido);
 		
 		sugerencias.add(suggestion2);
 		
 		//Cuando tengamos Service
 		//Suggestion suggestion = (Suggestion) session.getAttribute("sugerencia");
 		//suggestion.setTitle(titulo);
 		//suggestion.setContent(contenido);
 		//suggestionService.update(suggestion);
 		//sugerencias = suggestionService.findAll();
 		
 		session.setAttribute("sugerencia", suggestion2);
 		session.setAttribute("sugerencias", sugerencias);
 		
 		
 		return "admin/home";
 	}