List of usage examples for javax.servlet.http HttpServletRequest getRequestDispatcher
public RequestDispatcher getRequestDispatcher(String path);
From source file:io.hakbot.controller.servlet.ConsoleControllerServlet.java
private void doRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { final String pathInfo = request.getPathInfo(); final String uuid; // Check to make sure path info was specified if (StringUtils.isEmpty(pathInfo)) { response.sendError(400);/* ww w . j av a 2 s . c o m*/ return; } else { // Path info was specified so strip off the leading / character uuid = StringUtils.stripStart(pathInfo, "/"); } // Check to make sure the uuid is a valid format if (!UuidUtil.isValidUUID(uuid)) { response.sendError(400); return; } final QueryManager qm = new QueryManager(); final Job job = qm.getJob(uuid, new SystemAccount()); qm.close(); if (job == null) { response.sendError(404); return; } final ExpectedClassResolver resolver = new ExpectedClassResolver(); try { final Class pluginClass = resolver.resolveProvider(job); request.setAttribute("job", job); final String pluginPage = "/WEB-INF/plugins/" + pluginClass.getName() + "/index.jsp?uuid=" + uuid; response.setContentType("text/html;charset=UTF-8"); request.getRequestDispatcher(pluginPage).include(request, response); return; } catch (ClassNotFoundException | ExpectedClassResolverException e) { LOGGER.error(e.getMessage()); } response.sendError(404); }
From source file:in.edu.ssn.servlet.RegisterServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//www. jav a 2s . c o m * * @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"); PrintWriter out = response.getWriter(); try { String email = request.getParameter("email"); String password = request.getParameter("password"); // System.out.println(numplate+mobileno); Client client; client = ClientBuilder.newClient(); WebTarget target = client .target("https://api.idolondemand.com/1/api/sync/adduser/v1?store=myparkinglot&email=" + email + "&password=" + password + "&apikey=fa64dd8c-6193-47fd-a4ba-052939805fa4"); String response1 = target.request().get(String.class); org.json.JSONObject jsonObject = new org.json.JSONObject(response1); //JSONArray newJSON = jsonObject.getJSONArray("documents"); String c1n = new String(); //jsonObject = newJSON.getJSONObject(0); c1n = jsonObject.getString("message"); System.out.println(c1n); System.out.println(response); if (c1n != null) { RequestDispatcher rd = request.getRequestDispatcher("/book.html"); rd.forward(request, response); } else { RequestDispatcher rd = request.getRequestDispatcher("/home.html"); rd.include(request, response); } /* TODO output your page here. You may use following sample code. out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet RegisterServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>" + response1 + "</h1>"); out.println("</body>"); out.println("</html>");*/ } finally { out.close(); } }
From source file:com.juicioenlinea.application.servlets.particular.DemandaServlet.java
private void demandasRecibidas(HttpServletRequest request, HttpServletResponse response) { //Integer idParticularDemandante = 1; // Este Id se obtiene de la sesin que est activa HttpSession session = request.getSession(false); Particular demandante = (Particular) session.getAttribute("usuario"); demandante = new ParticularDAO().read(demandante.getIdParticular()); DemandaDAO dedao = new DemandaDAO(); List<Demanda> demandas = dedao.readAllRecibidas(demandante.getIdParticular()); if (demandas.size() < 1) { request.setAttribute("demandasRecibidas", null); } else {/*w w w .j a va 2 s . c o m*/ request.setAttribute("demandasRecibidas", demandas); } try { request.getRequestDispatcher("listaDemandasRecibidas.jsp").forward(request, response); } catch (ServletException | IOException ex) { Logger.getLogger(DemandaServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.focusns.common.web.page.PageFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { ////from w w w .j a v a 2 s . c o m try { String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); if (lookupPath.equals("/") || lookupPath.equals("")) { lookupPath = "/index"; } // PageFilterRequest pageFilterRequest = new PageFilterRequest(request); PageFilterResponse pageFilterResponse = new PageFilterResponse(response); pageFilterRequest.parseMatrixParameters(); // PageConfig pageConfig = pageFactory.find(lookupPath, pageFilterRequest.getParameterMap()); if (pageConfig != null) { // parse matrix parameters pageFilterRequest.setAttribute("pageConfig", pageConfig); pageFilterRequest.getSession().setAttribute("pageConfig", pageConfig); pageEngine.doRender(pageFilterRequest, pageFilterResponse); // if (response.isCommitted()) { return; } String layout = !StringUtils.hasText(pageConfig.getLayout()) ? defaultLayout : pageConfig.getLayout(); request.getRequestDispatcher(layout).forward(pageFilterRequest, pageFilterResponse); // return; } // String widgetId = request.getParameter("widgetId"); if (widgetId != null) { request.setAttribute("widgetId", widgetId); pageEngine.doAction(request, response); // return; } } catch (Exception e) { log.error(e.getMessage(), e); } // filterChain.doFilter(request, response); }
From source file:org.overlord.sramp.server.mvn.services.MavenRepositoryService.java
private void listItemsResponse(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException { if (!url.endsWith("/")) { //$NON-NLS-1$ url = url + "/"; //$NON-NLS-1$ }//from w ww . j a v a 2 s . c o m try { // Gets all the items from the maven url Set<String> items = getItems(url); // If there are items or the request is the root maven folder if ((items != null && items.size() > 0) || (url.equals("/") || url.equals(""))) { //$NON-NLS-1$ //$NON-NLS-2$ // Dispatch the request to the JSP that would display the items RequestDispatcher dispatcher = req.getRequestDispatcher(JSP_LOCATION_LIST_DIR); if (StringUtils.isNotBlank(url) && !url.equals("/")) { //$NON-NLS-1$ String[] urlTokens = url.split("/"); //$NON-NLS-1$ String parentPath = ""; //$NON-NLS-1$ if (urlTokens.length > 1) { for (int i = 0; i < urlTokens.length - 1; i++) { parentPath += urlTokens[i] + "/"; //$NON-NLS-1$ } } parentPath = "/" + parentPath; //$NON-NLS-1$ req.setAttribute("parentPath", parentPath); //$NON-NLS-1$ } else { url = ""; //$NON-NLS-1$ } req.setAttribute("relativePath", url); //$NON-NLS-1$ req.setAttribute("items", items); //$NON-NLS-1$ dispatcher.forward(req, resp); } else { resp.setStatus(HttpStatus.SC_NOT_FOUND); } } catch (MavenRepositoryException e) { resp.sendError(HttpStatus.SC_NOT_FOUND, e.getMessage()); } }
From source file:edu.lternet.pasta.portal.JournalCitationDeleteServlet.java
/** * The doPost method of the servlet. <br> * /* ww w. j av a 2 s. c o m*/ * This method is called when a form has its tag value method equals to post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); String uid = (String) httpSession.getAttribute("uid"); if (uid == null || uid.isEmpty()) uid = "public"; String journalCitationId = request.getParameter("journalcitationid"); String deleteMessage = null; String messageType = null; if (uid.equals("public")) { messageType = "warning"; request.setAttribute("message", LOGIN_WARNING); } else { try { JournalCitationsClient journalCitationsClient = new JournalCitationsClient(uid); journalCitationsClient.deleteByJournalCitationId(journalCitationId); deleteMessage = String.format( "Journal citation entry with identifier '<b>%s</b>' has been deleted.", journalCitationId); messageType = "info"; } catch (Exception e) { handleDataPortalError(logger, e); } } request.setAttribute("deleteMessage", deleteMessage); request.setAttribute("messageType", messageType); RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward); requestDispatcher.forward(request, response); }
From source file:net.incrementalism.tooter.SignUpServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (isBlank(request.getParameter("userName"))) { request.setAttribute("error", "'User Name' must not be empty."); } else if (isBlank(request.getParameter("email"))) { request.setAttribute("error", "'Email Address' must not be empty."); } else if (isBlank(request.getParameter("password"))) { request.setAttribute("error", "'Password' must not be empty."); } else if (isBlank(request.getParameter("passwordConfirm"))) { request.setAttribute("error", "'Confirm Password' must not be empty."); } else if (!request.getParameter("password").equals(request.getParameter("passwordConfirm"))) { request.setAttribute("error", "'Password' and 'Confirm Password' did not match."); } else {// ww w . j a v a 2 s.c om try { setCurrentUser(request, addUser(User.builder().userName(request.getParameter("userName")) .email(request.getParameter("email")).password(request.getParameter("password")).build())); response.sendRedirect("/profile"); return; } catch (DuplicateUserException e) { request.setAttribute("error", "User Name '" + e.getUserName() + "' is already taken."); } } request.getRequestDispatcher("/index.jsp").include(request, response); }
From source file:edu.lternet.pasta.portal.EventTestServlet.java
/** * The doPost method of the servlet. <br> * /*from w w w . j a v a 2 s . c o m*/ * This method is called when a form has its tag value method equals to post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); String xml = null; String uid = (String) httpSession.getAttribute("uid"); if (uid == null || uid.isEmpty()) uid = "public"; String subscriptionId = request.getParameter("subscriptionid"); String message = null; String type = null; if (uid.equals("public")) { message = LOGIN_WARNING; type = "warning"; } else { try { EventSubscriptionClient eventClient = new EventSubscriptionClient(uid); eventClient.testSubscription(subscriptionId); xml = eventClient.readBySid(subscriptionId); message = "Event subscription with identifier '<b>" + subscriptionId + "</b>' has been tested by posting to the Target URL.</strong>"; type = "info"; } catch (Exception e) { handleDataPortalError(logger, e); } } request.setAttribute("testmessage", message); request.setAttribute("type", type); RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward); requestDispatcher.forward(request, response); }
From source file:org.jboss.console.plugins.monitor.ManageSnapshotServlet.java
protected void doit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter("action"); if (action == null) { error("unknown action: ", req, resp); return;/*w ww. jav a2 s. co m*/ } action = action.trim(); MBeanServer mbeanServer = MBeanServerLocator.locateJBoss(); ObjectName monitorObjectName; String attribute = null; try { monitorObjectName = new ObjectName(req.getParameter("monitorObjectName")); attribute = (String) mbeanServer.getAttribute(monitorObjectName, "ObservedAttribute"); } catch (Exception ex) { error("Malformed Monitor ObjectName: " + req.getParameter("monitorObjectName"), req, resp); return; } if (action.equals("Start Snapshot")) { Object[] nullArgs = {}; String[] nullSig = {}; try { mbeanServer.invoke(monitorObjectName, "startSnapshot", nullArgs, nullSig); } catch (Exception ex) { error("Problem invoking startSnapshot: " + ex.toString(), req, resp); return; } req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp); return; } else if (action.equals("Stop Snapshot")) { Object[] nullArgs = {}; String[] nullSig = {}; try { mbeanServer.invoke(monitorObjectName, "endSnapshot", nullArgs, nullSig); } catch (Exception ex) { error("Problem invoking endSnapshot: " + ex.toString(), req, resp); return; } req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp); return; } else if (action.equals("Clear Dataset")) { Object[] nullArgs = {}; String[] nullSig = {}; try { mbeanServer.invoke(monitorObjectName, "clearData", nullArgs, nullSig); } catch (Exception ex) { error("Problem invoking clearData: " + ex.toString(), req, resp); return; } req.setAttribute("error", "Dataset Cleared!"); req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp); return; } else if (action.equals("Remove Snapshot")) { try { log.debug("removing snapshot: " + monitorObjectName.toString()); mbeanServer.unregisterMBean(monitorObjectName); req.getRequestDispatcher("/ServerInfo.jsp").forward(req, resp); } catch (Exception ex) { error("Failed to Remove Monitor: " + ex.toString(), req, resp); } return; } else if (action.equals("Show Dataset")) { ArrayList data = null; long start, end = 0; try { data = (ArrayList) mbeanServer.getAttribute(monitorObjectName, "Data"); start = ((Long) mbeanServer.getAttribute(monitorObjectName, "StartTime")).longValue(); end = ((Long) mbeanServer.getAttribute(monitorObjectName, "EndTime")).longValue(); } catch (Exception ex) { error("Problem invoking getData: " + ex.toString(), req, resp); return; } resp.setContentType("text/html"); PrintWriter writer = resp.getWriter(); writer.println("<html>"); writer.println("<body>"); writer.println("<b>Start Time:</b> " + start + "ms<br>"); writer.println("<b>End Time:</b> " + end + "ms<br>"); writer.println("<b>Total Time:</b> " + (end - start) + "ms<br>"); writer.println("<br><table border=\"0\">"); for (int i = 0; i < data.size(); i++) { writer.println("<tr><td>" + data.get(i) + "</td></tr"); } writer.println("</table></body></html>"); return; } else if (action.equals("Graph Dataset")) { ArrayList data = null; long start, end = 0; try { data = (ArrayList) mbeanServer.getAttribute(monitorObjectName, "Data"); start = ((Long) mbeanServer.getAttribute(monitorObjectName, "StartTime")).longValue(); end = ((Long) mbeanServer.getAttribute(monitorObjectName, "EndTime")).longValue(); } catch (Exception ex) { error("Problem invoking getData: " + ex.toString(), req, resp); return; } XYSeries set = new XYSeries(attribute, false, false); for (int i = 0; i < data.size(); i++) { set.add(new Integer(i), (Number) data.get(i)); } DefaultTableXYDataset dataset = new DefaultTableXYDataset(false); dataset.addSeries(set); JFreeChart chart = ChartFactory.createXYLineChart("JMX Attribute: " + attribute, "count", attribute, dataset, PlotOrientation.VERTICAL, true, true, false); resp.setContentType("image/png"); OutputStream out = resp.getOutputStream(); ChartUtilities.writeChartAsPNG(out, chart, 400, 300); out.close(); return; } error("Unknown Action", req, resp); return; }
From source file:nc.noumea.mairie.organigramme.core.authentification.AuthentificationFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { /* Cast des objets request et response */ HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession hSess = ((HttpServletRequest) request).getSession(); // Hack pour pouvoir rcuprer les images sur la page de connexion if (request.getRequestURI().contains("imgs")) { chain.doFilter(request, response); return;//from w w w .j a v a2s .c om } // on laisse passer pour le rproxy et ainsi permettre de deployer l // application sur le 2e noeud tomcat if (PAGES_STATIQUES.contains(request.getServletPath())) { chain.doFilter(request, response); return; } if (null != hSess.getAttribute("logout")) { if (!request.getRequestURI().contains("zkau") && !request.getRequestURI().contains("login.zul") && !request.getRequestURI().contains("css")) { // dans le cas ou la personne a clique sur ce deconnecte et ne // ferme pas le navigateur LOGGER.debug("User disconnect"); hSess.setAttribute("logout", "logout"); request.getRequestDispatcher("login.zul").forward(request, response); return; } chain.doFilter(request, response); return; } if (null != hSess.getAttribute("currentUser")) { chain.doFilter(request, response); return; } if ((null == request.getHeader("x-krb_remote_user") || "".equals(request.getHeader("x-krb_remote_user").trim()))) { LOGGER.debug("x-krb_remote_user is NULL"); // hSess.invalidate(); // request.logout(); // response.sendError(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, // "You are logged out."); // #15803 hSess.setAttribute("logout", "logout"); request.getRequestDispatcher("login.zul").forward(request, response); return; } String remoteUser = request.getHeader("x-krb_remote_user"); remoteUser = convertRemoteUser(remoteUser); LightUserDto userDto = radiWSConsumer.getAgentCompteADByLogin(remoteUser); if (null == userDto) { LOGGER.debug("User not exist in Radi WS with RemoteUser : " + remoteUser); // request.logout(); hSess.setAttribute("logout", "logout"); request.getRequestDispatcher("login.zul").forward(request, response); return; } if (0 == userDto.getEmployeeNumber()) { LOGGER.debug("User not exist in Radi WS with RemoteUser : " + remoteUser); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Vous n'tes pas un agent de la mairie, vous n'tes pas autoris accder cette application."); return; } ProfilAgentDto profilAgent = recupereProfilAgent(request, userDto.getEmployeeNumber()); if (profilAgent == null) { return; } AccessRightOrganigrammeDto accessRightOrganigrammeDto = recupereAccessRightOrganigramme(request, userDto.getEmployeeNumber()); if (accessRightOrganigrammeDto == null || accessRightOrganigrammeDto.isAucunRole()) { hSess.setAttribute("logout", "logout"); request.getRequestDispatcher("login.zul").forward(request, response); return; } renseigneAccessRightOnUser(profilAgent, accessRightOrganigrammeDto); hSess.setAttribute("currentUser", profilAgent); LOGGER.debug("Authentification du user ok : " + remoteUser); LOGGER.debug("Droits du user ok : " + accessRightOrganigrammeDto); chain.doFilter(request, response); }