List of usage examples for javax.servlet.http HttpServletRequest getRequestDispatcher
public RequestDispatcher getRequestDispatcher(String path);
From source file:com.darksky.seller.SellerServlet.java
/** * ?/*from ww w . j a v a 2 s .c om*/ * @param request * @param response * @throws ServletException * @throws IOException */ public void testID(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(); System.out.println("-------------------test ID------------------"); String sellerID = request.getParameter("ID"); String iden = "s"; System.out.println("sellerID: " + sellerID); String sql = "select * from seller where sellerID = '" + sellerID + "'"; try { resultSet = statement.executeQuery(sql); if (resultSet.wasNull()) { System.out.println("doesn't exist"); request.getRequestDispatcher("?.jsp").forward(request, response); } else { request.setAttribute("sellerID", sellerID); request.setAttribute("iden", iden); questionAndAnswer(sellerID, request, response); } } catch (SQLException e) { e.printStackTrace(); System.out.println("error"); } System.out.println("-------------------test ID------------------"); System.out.println(); }
From source file:com.juicioenlinea.application.servlets.particular.DemandaServlet.java
private void demandasHechas(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(false); String page = request.getParameter("page"); if (page == null || page.equals("")) { page = "1"; }//from ww w. jav a 2 s. c om int rows = 20; Particular demandante = (Particular) session.getAttribute("usuario"); demandante = new ParticularDAO().read(demandante.getIdParticular()); DemandaDAO dedao = new DemandaDAO(); List<Demanda> demandas = dedao.readAllHechasPage(demandante.getIdParticular(), Integer.parseInt(page), rows); if (demandas.size() < 1 || demandas == null) { request.setAttribute("demandasHechas", null); request.setAttribute("currentPage", null); } else { request.setAttribute("demandasHechas", demandas); request.setAttribute("currentPage", page); request.setAttribute("lastPage", (int) Math.ceil((double) dedao.countDemandas(demandante.getIdParticular()) / rows)); } try { request.getRequestDispatcher("listaDemandasHechas.jsp").forward(request, response); } catch (ServletException | IOException ex) { Logger.getLogger(DemandaServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.jbpm.formbuilder.server.EmbedingServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String profile = request.getParameter("profile"); String usr = request.getParameter("usr"); String pwd = request.getParameter("pwd"); TaskDefinitionService taskService = createTaskService(request, usr, pwd); FormDefinitionService formService = createFormService(request, usr, pwd); FormRepresentationEncoder encoder = FormEncodingFactory.getEncoder(); JsonObject json = new JsonObject(); json.addProperty("embedded", profile); try {/* ww w. j a v a 2s. co m*/ if (profile != null && "designer".equals(profile)) { String userTask = request.getParameter("userTask"); String processName = request.getParameter("processName"); String bpmn2Process = IOUtils.toString(request.getReader()); TaskRef task = taskService.getBPMN2Task(bpmn2Process, processName, userTask); if (task != null) { //get associated form if it exists FormRepresentation form = formService.getAssociatedForm(task.getPackageName(), task); if (form != null) { json.addProperty("formjson", encoder.encode(form)); } json.add("task", toJsonObject(task)); json.addProperty("packageName", task.getPackageName()); } } else { throw new Exception("Unknown profile for POST: " + profile); } request.setAttribute("jsonData", new Gson().toJson(json)); request.getRequestDispatcher("/FormBuilder.jsp").forward(request, response); } catch (TaskServiceException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem getting task from guvnor"); } catch (FormServiceException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem reading form from guvnor"); } catch (FormEncodingException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem encoding form"); } catch (Exception e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:forumbox.EditPost.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from www. j av a 2s. c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getRequestURI(); String[] urlpost = url.split("/"); String idPost = urlpost[3]; JSONParser passPost = new JSONParser(); JSONObject post; try { if (idPost != null) { Object objPost = passPost.parse(new FileReader( "/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/" + idPost + ".json")); post = (JSONObject) objPost; String postuser = post.get("username").toString(); String posttitle = post.get("title").toString(); String postdescription = post.get("description").toString(); /* JSONArray array = (JSONArray) post.get("comments"); ArrayList<String> list; list = new ArrayList<>(); Iterator<String> iterator = array.iterator(); while (iterator.hasNext()) { list.add(iterator.next()); } int listsz = list.size(); */ /* String[] comments = new String[listsz]; for(int i=0;i<listsz;i++){ comments[i]=list.get(i); }*/ request.setAttribute("title", posttitle); request.setAttribute("description", postdescription); request.setAttribute("username", postuser); // request.setAttribute("comments",comments); request.setAttribute("id", idPost); request.getRequestDispatcher("/edit.jsp").forward(request, response); } } catch (Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(e); } }
From source file:com.concursive.connect.web.modules.welcome.servlets.WelcomeServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { try {/* w w w .j av a2 s . c om*/ request.setCharacterEncoding("UTF-8"); } catch (Exception e) { LOG.warn("Unsupported encoding"); } try { // Save the requestURI to be used downstream (it gets rewritten on forwards) String contextPath = request.getContextPath(); String uri = request.getRequestURI(); String queryString = request.getQueryString(); String requestedURL = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString); if ("/index.shtml".equals(requestedURL)) { requestedURL = ""; } request.setAttribute("requestedURL", requestedURL); // Configure the user's client ClientType clientType = (ClientType) request.getSession().getAttribute(Constants.SESSION_CLIENT_TYPE); if (clientType == null) { clientType = new ClientType(); clientType.setParameters(request); request.getSession().setAttribute("clientType", clientType); } // Detect mobile if ("false".equals(request.getParameter("useMobile"))) { clientType.setMobile(false); } // Context startup initializes the prefs ApplicationPrefs applicationPrefs = (ApplicationPrefs) request.getSession().getServletContext() .getAttribute("applicationPrefs"); if (!applicationPrefs.isConfigured()) { RequestDispatcher initialSetup = request.getRequestDispatcher("/Setup.do?command=Default"); initialSetup.forward(request, response); } else if (ApplicationVersion.isOutOfDate(applicationPrefs)) { // If the site is setup, then check to see if this is an upgraded version of the app RequestDispatcher upgrade = getServletConfig().getServletContext() .getRequestDispatcher("/Upgrade.do?command=Default&style=true"); upgrade.forward(request, response); } else if ("true".equals(applicationPrefs.get("PORTAL"))) { // If the site supports a portal, go to the portal // @todo implement mobile pages then turn this back on // if (clientType.getMobile()) { // If a mobile device is detected, offer a low-bandwidth option // RequestDispatcher portal = request.getRequestDispatcher("/Login.do?command=DetectMobile"); // portal.forward(request, response); // } else { String pathToUse = request.getRequestURI().substring(request.getContextPath().length()); RequestDispatcher portal = request .getRequestDispatcher(pathToUse + applicationPrefs.get("PORTAL.INDEX")); portal.forward(request, response); // } } else { // Go to the user's home page if logged in User thisUser = (User) request.getSession().getAttribute(Constants.SESSION_USER); if (thisUser != null && thisUser.getId() > 0) { RequestDispatcher portal = request .getRequestDispatcher("/ProjectManagement.do?command=Default"); portal.forward(request, response); } else { RequestDispatcher portal = request.getRequestDispatcher("/Login.do?command=Default"); portal.forward(request, response); } } } catch (Exception ex) { String msg = "Welcome failed"; response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } }
From source file:com.persistent.cloudninja.controller.CloudNinjaAuthFilter.java
private void forwardToLandingPage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain chain, CloudNinjaUser cloudNinjaUser) { UserActivityQueue userActivityQueue = UserActivityQueue.getUserActivityQueue(); String tenantId = null;/* w ww. j a v a 2 s.c om*/ synchronized (userActivityQueue) { try { Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String date = dateFormat.format(calendar.getTime()); UserActivityQueueMessage message; String cookie = httpServletRequest.getAttribute("cookieNameAttr").toString(); tenantId = AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX, cookie); message = new UserActivityQueueMessage(tenantId, cloudNinjaUser.getMemberId(), dateFormat.parse(date)); userActivityQueue.add(message); } catch (ParseException e) { e.printStackTrace(); } } try { rsBundle = ResourceBundle.getBundle("acs"); String landingPageURL = "/" + tenantId; landingPageURL = landingPageURL + rsBundle.getString("tenant.dashboard.landing.page.url").trim(); httpServletRequest.getRequestDispatcher(landingPageURL).forward(httpServletRequest, httpServletResponse); } catch (ServletException exception) { logger.error(exception.getMessage()); exception.printStackTrace(); } catch (IOException exception) { logger.error(exception.getMessage()); exception.printStackTrace(); } }
From source file:com.pureinfo.tgirls.sns.servlet.TestSNSEntryServlet.java
@Override protected void doPost(HttpServletRequest _req, HttpServletResponse _resp) throws ServletException, IOException { System.out.println("==================test entry=====POST=============="); try {//from w w w.j a v a2s . c o m String userId = _req.getParameter("id"); if (StringUtils.isEmpty(userId)) { userId = "1"; } System.out.println("----user id----" + userId); IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class); User u = mgr.getUserByTaobaoId(userId); System.out.println("user:::;" + u); addCookie(u, _req, _resp); Cookie[] cookies = _req.getCookies(); if (cookies == null) { System.out.println("=====cookie is null======="); } else { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "(" + cookie.getMaxAge() + ")]"); } } int i = new Random().nextInt(); Cookie c = new Cookie("topsessionid", "abc" + i); _resp.addCookie(c); System.out.println("========================"); // Cookie[] cs = _req.getCookies(); // for (int ii = 0; ii < cs.length; ii++) { // Cookie cc = cs[ii]; // System.out.println("cookie[" + cc.getName() + "]:" + cc.getValue()); // } //_resp.sendRedirect(_req.getContextPath() + "/index.html"); RequestDispatcher rd = _req.getRequestDispatcher("/index.html"); rd.forward(_req, _resp); //_req.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, u); // _resp.sendRedirect(_req.getContextPath()); // _req.getCookies()[0]. } catch (PureException e) { // TODO Auto-generated catch block e.printStackTrace(System.err); } }
From source file:net.duckling.ddl.web.controller.LoginController.java
@WebLog(method = "loginToken") @RequestMapping("/token") public void dealToken(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Oauth o = new Oauth(config); try {//from w ww.j a v a 2s. c o m AccessToken t = o.getAccessTokenByRequest(request); String token = t.getAccessToken(); UserInfo u = t.getUserInfo(); VWBSession vwbsession = VWBSession.findSession(request); LOG.info("token:" + token); if (u == null) { LOG.info("Failed to authenticate user."); vwbsession.setStatus(VWBSession.ANONYMOUS); String failURL = policy.getSavedFailURL(request); if (failURL != null) { response.sendRedirect(failURL); } else { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } else { UserPrincipal user = new UserPrincipal(u.getCstnetId(), getUserName(u.getCstnetId(), u), u.getCstnetId(), u.getType()); List<Principal> set = new ArrayList<Principal>(); set.add(user); vwbsession.setPrincipals(set); updateCurrentUserInformation(request); request.getSession().setAttribute(Attributes.UMT_ACCESS_TOKEN, token); String state = request.getParameter("state"); //?meepo if ("clientcode".equals(state)) { request.setAttribute("accessToken", t); request.getRequestDispatcher("/system/clientcode").forward(request, response); } else if ("clientcode_needteams".equals(state)) { //?? request.setAttribute("accessToken", t); request.getRequestDispatcher("/system/clientcode?need_teams=true").forward(request, response); } else if ("syncclient".equals(state)) { //? request.setAttribute("accessToken", t); request.getRequestDispatcher("/system/syncclient").forward(request, response); } else { String viewUrl = (String) VWBSession.findSession(request) .removeAttribute(Attributes.REQUEST_URL); if (StringUtils.isEmpty(viewUrl)) { viewUrl = state; } LOG.info("Successfully authenticated user:" + u.getCstnetId() + ";access_token:" + token); LOG.info("Redirecting user to " + viewUrl); // Redirect! redirect(request, response, viewUrl); } } } catch (UMTOauthConnectException e) { LOG.error("", e); } catch (OAuthProblemException e) { LOG.error("", e); } }
From source file:com.versatus.jwebshield.filter.SessionCheckFilter.java
/** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */// w w w .j a v a2s . c o m @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpRes = (HttpServletResponse) response; String reqInfo = "J-WebShield Alert: Session check failed! request URL=" + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr(); logger.debug("doFilter: RequestURL=" + httpReq.getRequestURL().toString()); UrlExclusionList exclList = (UrlExclusionList) request.getServletContext() .getAttribute(SecurityConstant.SESSION_CHECK_URL_EXCL_LIST_ATTR_NAME); try { if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) { logger.info("doFilter: request (" + httpReq.getRequestURL().toString() + " matches exclusion pattern, skipping session check"); chain.doFilter(request, response); return; } } catch (Exception e) { logger.error("doFilter", e); } HttpSession session = httpReq.getSession(false); logger.debug("doFilter: session=" + session); logger.debug("doFilter: session attr. " + attributeToCheck + "=" + (session != null ? session.getAttribute(attributeToCheck) : "")); if (session == null || session.getAttribute(attributeToCheck) == null) { if (send401) { // TODO this is not working for regular requests, only for WS // calls httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } else { logger.info(reqInfo + " redirecting to " + redirectPage); RequestDispatcher rd = httpReq.getRequestDispatcher(redirectPage); if (rd != null) { rd.forward(request, response); } return; } } logger.info("doFilter: session check complete"); // pass the request along the filter chain chain.doFilter(request, response); }
From source file:forumbox.ViewPost.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from ww w . j ava2 s . com * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getRequestURI(); String[] urlpost = url.split("/"); String idPost = urlpost[3]; JSONParser passPost = new JSONParser(); JSONObject post; try { if (idPost != null) { Object objPost = passPost.parse(new FileReader( "/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/" + idPost + ".json")); post = (JSONObject) objPost; String postuser = post.get("username").toString(); String posttitle = post.get("title").toString(); String postdescription = post.get("description").toString(); /* JSONArray array = (JSONArray) post.get("comments"); ArrayList<String> list; list = new ArrayList<>(); Iterator<String> iterator = array.iterator(); while (iterator.hasNext()) { list.add(iterator.next()); } int listsz = list.size(); */ /* String[] comments = new String[listsz]; for(int i=0;i<listsz;i++){ comments[i]=list.get(i); }*/ request.setAttribute("title", posttitle); request.setAttribute("description", postdescription); request.setAttribute("username", postuser); // request.setAttribute("comments",comments); request.setAttribute("id", idPost); request.getRequestDispatcher("/post.jsp").forward(request, response); } } catch (Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(e); } }