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

The following are Jave code examples for showing how to use getSession() 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: ServletWebRequest.java   View Source Code Vote up 7 votes
@Override
public String getDescription(boolean includeClientInfo) {
	HttpServletRequest request = getRequest();
	StringBuilder sb = new StringBuilder();
	sb.append("uri=").append(request.getRequestURI());
	if (includeClientInfo) {
		String client = request.getRemoteAddr();
		if (StringUtils.hasLength(client)) {
			sb.append(";client=").append(client);
		}
		HttpSession session = request.getSession(false);
		if (session != null) {
			sb.append(";session=").append(session.getId());
		}
		String user = request.getRemoteUser();
		if (StringUtils.hasLength(user)) {
			sb.append(";user=").append(user);
		}
	}
	return sb.toString();
}
 
Example 2
Project: Guestbook9001   File: EditController.java   View Source Code Vote up 7 votes
@GetMapping("/delete/{id}")
public String getDelete(HttpServletRequest request, HttpServletResponse response, @PathVariable long id,
						Model model) throws IOException {
	HttpSession session = request.getSession(true);
	Entry entry = getEntryDao().getEntry(id);

	if(entry == null) {
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
		return null;
	}

	if(canEdit(session, entry)) {
		model.addAttribute("entry", entry);
		return "delete";
	}

	response.sendError(HttpServletResponse.SC_FORBIDDEN);
	return null;
}
 
Example 3
Project: DDNS_Server   File: LoginServlet.java   View Source Code Vote up 6 votes
public void doPost(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
    
    String n=request.getParameter("username");  
    String p=request.getParameter("userpass"); 
    HttpSession session = request.getSession(false);
    
    DB dbProperties = new DB(getServletContext().getInitParameter("dbHost"), getServletContext().getInitParameter("dbPort"), getServletContext().getInitParameter("dbName"), getServletContext().getInitParameter("dbUser"), getServletContext().getInitParameter("dbPassword"));
    
    if(LoginDao.validate(n, p, request, dbProperties) != null){ 
        session.setAttribute("LoggedUser", LoginDao.validate(n, p, request, dbProperties));            
    } else{  
    	request.setAttribute("login_error", "<p style=\"color:red\">Sorry user name or password error</p>");
    }  

	RequestDispatcher rd = getServletContext().getRequestDispatcher(request.getContextPath() + "/login.jsp");
	rd.forward(request, response);
	
    doGet(request, response);
}
 
Example 4
Project: full-javaee-app   File: AdministratorCreateCompanyServlet.java   View Source Code Vote up 6 votes
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();
    String name = request.getParameter("name") != null ? request.getParameter("name").trim() : "",
            viewLimit = request.getParameter("viewLimit") != null ? request.getParameter("viewLimit").trim() : "";

    if (name.isEmpty() || viewLimit.isEmpty()) {
        session.setAttribute("companyError", "Please enter a name and profile view limit");
    } else {
        Companies company = new Companies();
        company.setName(name);
        company.setViewLimit(Integer.parseInt(viewLimit));
        company.setProfilesViewed(0);
        company.setProfilesViewedThisMonth(0);

        try {
            company = CompanyDataAccessObject.persist(company);
            List<Companies> companyList = CompanyDataAccessObject.getAll();
            session.setAttribute("companyList", companyList);
        } catch (Exception e) {
            session.setAttribute("companyError", "An error occurred");
            e.printStackTrace();
        }
    }
    response.sendRedirect("admin/admin-company-list.jsp");
}
 
Example 5
Project: timesheet-upload   File: GlobalExceptionHandler.java   View Source Code Vote up 6 votes
@ExceptionHandler({Exception.class})
public ModelAndView handleGenericException(Exception ex, HttpServletRequest request) {
    //LOG HERE
    ModelAndView model = new ModelAndView("error");
    AppErrorInfo errorInfo = new AppErrorInfo();
    HttpSession session = request.getSession(false);

    errorInfo.setErrorCode("TIMESHEET.SERVER.ERROR");
    errorInfo.setErrorDetails("");
    errorInfo.setErrorMessage(messageSource.getMessage("internal.server.error",
            new String[]{}, Locale.US));
    errorInfo.setHttpStatusCode(500);
    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("ecasErrorInfo", errorInfo);
    return model;
}
 
Example 6
Project: supervisor   File: HomeController.java   View Source Code Vote up 6 votes
@RequestMapping(value="auth")
public void authUser(HttpServletRequest request,HttpServletResponse response,String email,String password) throws Exception{
	User usercent=new User();
	usercent.setEmail(email);
	usercent.setPassword(MD5Utils.MD5(password));
	User user=manageServiceImpl.valUserCenter(usercent);
       
	if (null != user) {
		LOG.info("login suc.");
		user.setLoginTimes(user.getLoginTimes()+1);
		user.setLastLoginIp(request.getRemoteAddr());
		manageServiceImpl.reCordUserLogin(user);
		HttpSession session = request.getSession();
		session.setAttribute("curUser", user);
		session.setAttribute("username", user.getUsername());
		
		setCookie(response, "name", user.getUsername(),"/", COOKIE_TIME);
		setCookie(response, "email", user.getEmail() + "","/", COOKIE_TIME);
		response.getWriter().print("suc");
	}else{
		response.getWriter().print("false");
	}
	
}
 
Example 7
Project: session-cloud   File: SSOLoginService.java   View Source Code Vote up 6 votes
public static void doSSOLogin(HttpServletRequest httpRequest) {
    HttpSessionManager sessionManager =(HttpSessionManager) httpRequest.getAttribute(HttpSessionManager.class.getName());
    String alias = httpRequest.getParameter("_s");

    SessionRepository<Session> sessionRepository =
    (SessionRepository<Session>) httpRequest.getAttribute(SessionRepository.class.getName());
    for(Map.Entry<String, String> entry : sessionManager.getSessionIds(httpRequest).entrySet()) {
        String aliasId = entry.getKey();
        String sessionValue = entry.getValue();
        Session session = sessionRepository.getSession(sessionValue);
        HttpSession httpSession = httpRequest.getSession();
        if(session != null && session.getAttribute("username") != null && httpSession.getAttribute("username") == null ) {
            httpSession.setAttribute("username", session.getAttribute("username"));
        }

        log.info("[SSOLoginService] doSSOLogin aliasId {} : session value{}",aliasId,sessionValue);
    }

    if(StringUtils.isEmpty(alias)) {
        alias = sessionManager.getNewSessionAlias(httpRequest);
    }
    
    httpRequest.setAttribute("alias",alias);
}
 
Example 8
Project: boutique-de-jus   File: AuthAction.java   View Source Code Vote up 5 votes
/**
 * Logs out the user and invalidates the session
 * @return
 *  the method always returns SUCCESS or throws an error if logout fails.
 * @throws ServletException
 */
public String logout() throws ServletException {
    final HttpServletRequest request = ServletActionContext.getRequest();
    final HttpSession session = request.getSession();

    //perform container login
    request.logout();
    session.invalidate();
    return SUCCESS;
}
 
Example 9
Project: convertigo-engine   File: ModifyXPathText.java   View Source Code Vote up 5 votes
@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    HttpSession session = request.getSession();

    CheStudio cheStudio = CallAction.getStudio(session);
    if (cheStudio != null) {
        SourcePickerViewWrap spv = cheStudio.getSourcePickerView();
        if (spv != null) {
            String xpath = request.getParameter("xpath").trim();
            spv.modifyXpathText(xpath);
        }
    }
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: TestBug49158.java   View Source Code Vote up 5 votes
@Override
public void service(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    HttpSession session = req.getSession();
    session.invalidate();
    session = req.getSession();
    session.invalidate();
    req.getSession();
}
 
Example 11
Project: the-vigilantes   File: ModulLevering.java   View Source Code Vote up 5 votes
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession();
    String modul = request.getParameter("modul");
    session.setAttribute("modul", modul);
    RequestDispatcher rd = request.getRequestDispatcher("JSP/ModulLevering.jsp");
        rd.include(request, response);    
}
 
Example 12
Project: full-javaee-app   File: AdministratorViewClientStatistics.java   View Source Code Vote up 5 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	HttpSession session = request.getSession();

	int clientID = Integer.parseInt(request.getParameter("clientID"));
	Clients client = ClientPersistence.getByID(clientID);

	session.setAttribute("client", client);
	response.sendRedirect("admin/admin-client-logs.jsp");
}
 
Example 13
Project: tomcat7   File: TestTomcat.java   View Source Code Vote up 5 votes
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException {
    HttpSession s = req.getSession(true);
    s.getId();
    res.getWriter().write("Hello world");
}
 
Example 14
Project: Towan   File: TowanController.java   View Source Code Vote up 5 votes
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String doLogout(HttpServletRequest request) {

	HttpSession session = request.getSession();
	session.invalidate();

	return "index";
}
 
Example 15
Project: ssm-rbac   File: GlobalController.java   View Source Code Vote up 5 votes
/**
 * 解锁客户端
 */
@RequestMapping("doUnlockCheck")
@ResponseBody
private AjaxResult doUnlock(HttpServletRequest request, @RequestParam("password") String password) {
    HttpSession session = request.getSession();
    UserEntity member = (UserEntity) session.getAttribute(IConstants.RBAC_SESSION_MEMBER);
    if (member.getPassword().equals(CommonUtils.MD5(password))) {
        session.setAttribute(IConstants.RBAC_SESSION_LOCK, null);
        return new AjaxResult();
    }
    return new AjaxResult(false, "密码错误!");
}
 
Example 16
Project: 112016.pizzeria-app   File: LoginController.java   View Source Code Vote up 5 votes
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	HttpSession session = request.getSession();
	String email = request.getParameter("email");
	String password = request.getParameter("password");
	Utilisateur user = utilisateurService.connexion(email, password);
	if(user != null) {
		session.setAttribute("user", user);
		response.sendRedirect(response.encodeRedirectURL("./admin/home"));			
	} else {
		request.setAttribute("erreur", "Email ou mot de passe incorect");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/login.jsp");
		dispatcher.forward(request, response);
	}
}
 
Example 17
Project: OnlineElectionVotingSystem   File: ForgotServlet.java   View Source Code Vote up 4 votes
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String emailid = request.getParameter("email");
	String page="";
	String sql ="select * from register where email='"+emailid+"' ";
	System.out.println(emailid);

	if(emailid.equals(""))
	{ 
		page="error.jsp?msg=abc";
	}
	else
	{
		Model m = new Model(); 
		m.setEmail(emailid); 
		try
		{
			ResultSet rs =Dao.validate(m,sql);
			if (rs.next())
			{
				String password= rs.getString(12);
				HttpSession session = request.getSession();
				session.setAttribute("email", emailid);
				session.setAttribute("pass", password);
				String data = "12345678901234567890123456789012345678901234567890";
				String otp="";
				char ch[]=data.toCharArray();
				
				for (int i=0; i<4; i++)
				{
					int j = (int)((Math.random()) * 50);
					otp=otp+ch[j];
				}
				session.setAttribute("otp",otp);
				PasswordMail pm = new PasswordMail(); 
				boolean status = pm.sendMail(emailid, otp);
				if(status)
				{ 
					page="otp.jsp?msg=send";
				}	 
			}
		}		
		catch(Exception e)
		{
			e.printStackTrace();
		}			 
	}
	response.sendRedirect(page);
}
 
Example 18
Project: convertigo-engine   File: Context.java   View Source Code Vote up 4 votes
public void setRequest(HttpServletRequest request){
	httpServletRequest = request;
	httpSession = request.getSession();
	requestHeaders = null;
}
 
Example 19
Project: ChronoBike   File: XSLTServlet.java   View Source Code Vote up 4 votes
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{	
	HttpSession javaSession = req.getSession(true);
	OnlineSession appSession = (OnlineSession)javaSession.getAttribute("AppSession");
	int n = appSession.getOnceHttpSessionMaxInactiveInterval_s();
	if(n != 0)
		javaSession.setMaxInactiveInterval(n);
	
	String path = req.getServletPath() ;
	
	if (path.equalsIgnoreCase("/showhelp"))
	{
		ShowHelp(appSession, res) ;
		return ;
	}
	 
	if (path.equalsIgnoreCase("/showprintscreen"))
	{
		m_view.mergeOutputForPrintScreen(appSession) ;
		ShowPrintScreen(appSession, res) ;
		return ;
	}
			 
	// make output
	if (appSession.isUpdatedValues())
	{
		m_view.updateOutput(appSession) ;
	}
	else
	{
		m_view.mergeOutput(appSession) ;
	}
	
	// render output
	Document xmlOutput = appSession.getXMLOutput();
	if (xmlOutput == null)
	{
		res.setStatus(500);
	}
	else
	{
		String sessionid = javaSession.getId() ;
		xmlOutput.getDocumentElement().setAttribute("SESSIONID", sessionid) ;

		String csServletPath = req.getRequestURI();
		String s = csServletPath.replaceFirst("XSLTServlet", appSession.getActionAlias()) ; 
		s = res.encodeURL(s) ;
		xmlOutput.getDocumentElement().setAttribute("URL", s) ;
		renderOutput(xmlOutput, res, appSession.isZoom(), appSession.isBold());
	}
}
 
Example 20
Project: OMIPlatform   File: AuthSuccessHandler.java   View Source Code Vote up 4 votes
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    HttpSession session=request.getSession();
    response.sendRedirect("/education/home");
}