@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (exception instanceof CaptchaException) { getRedirectStrategy().sendRedirect(request, response, CODE_ERROR_URL); } else { getRedirectStrategy().sendRedirect(request, response, PASS_ERROR_URL); } }
/** * <p>Dispatches to the target class' <code>unspecified</code> method, if * present, otherwise throws a ServletException. Classes utilizing * <code>EventActionDispatcher</code> should provide an <code>unspecified</code> * method if they wish to provide behavior different than throwing a * ServletException.</p> * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The non-HTTP request we are processing * @param response The non-HTTP response we are creating * @return The forward to which control should be transferred, or * <code>null</code> if the response has been completed. * @throws Exception if the application business logic throws an * exception. */ protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Identify if there is an "unspecified" method to be dispatched to String name = "unspecified"; Method method = null; try { method = getMethod(name); } catch (NoSuchMethodException e) { String message = messages.getMessage("event.parameter", mapping.getPath()); LOG.error(message + " " + mapping.getParameter()); throw new ServletException(message); } return dispatchMethod(mapping, form, request, response, name, method); }
@Test public void testDoGet() { try { sut.doGet(request, response); verify(response, times(1)).setContentType("text/html;charset=UTF-8"); verify(response, times(1)).getWriter(); assertEquals("<html>" + "<img src='images/cat.jpg'>" + "<p>Image by <a href=\"https://flic.kr/p/HPf9R1\">" + "Andy Miccone</a></p>" + "<p>License: <a href=\"https://creativecommons.org/" + "publicdomain/zero/1.0/\">" + "CC0 1.0 Universal (CC0 1.0) \n" + "Public Domain Dedication</a></p>" + "</html>", stringWriter.toString()); verify(pushBuilder, times(2)).push(); } catch (ServletException | IOException e) { fail(); } }
@SuppressWarnings("unchecked") @Override public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter out = response.getWriter(); Map<String, String[]> params = request.getParameterMap(); SortedSet<String> keys = new TreeSet<String>(params.keySet()); for(String key: keys) { out.print(key); out.print(':'); String[] values = params.get(key); if (values.length > 0) { out.print(values[0]); for(int i=1; i < values.length; ++i) { out.print(','); out.print(values[i]); } } out.print('\n'); } out.close(); }
/** * 获取文件列表 * @param req 客户端发送的数据对象 * @param resp 服务器发送的数据对象(大概) */ protected void toFileList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 每页默认显示2条数据 String size = req.getParameter("pageSize"); int pageSize = size == null ? 5 : Integer.parseInt(size); // 查询文件总数 int fileNum = fileService.queryFileNum(); // 计算总页数 int pages; if (fileNum%pageSize != 0) { pages = (fileNum/pageSize) + 1; } else { pages = (fileNum/pageSize); } // 当前页 String pageIndex = req.getParameter("curPage"); int curPage = pageIndex == null ? 1 : Integer.parseInt(pageIndex); List<FileDemo> fileDemos = fileService.queryFile(curPage, pageSize); req.setAttribute("fileDemos", fileDemos); req.setAttribute("curPage",curPage); req.setAttribute("pageSize",pageSize); req.setAttribute("pages",pages); req.getRequestDispatcher("/filemanage/filemanage.jsp").forward(req, resp); }
@Override public int invoke(Request rqst, Response rspns) throws IOException, ServletException { if (!isStarted()) { try { start(); } catch (LifecycleException ex) { throw new ServletException(ex); } } rqst.setNote(CatalinaAdapter.REQUEST_TIME, System.currentTimeMillis()); if (!alreadySetLogbackStatusManager) { alreadySetLogbackStatusManager = true; org.apache.catalina.Context tomcatContext = rqst.getContext(); if (tomcatContext != null) { ServletContext sc = tomcatContext.getServletContext(); if (sc != null) { sc.setAttribute(AccessConstants.LOGBACK_STATUS_MANAGER_KEY, ctx.getStatusManager()); } } } return INVOKE_NEXT; }
@Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { PrintWriter out = res.getWriter(); out.print("<p>" + getInitParameter("foo") + " " + getInitParameter("bar") + "</p>"); }
public void copyFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String newFullPath=req.getParameter("newFullPath"); String oldFullPath=req.getParameter("oldFullPath"); newFullPath=Utils.decodeURL(newFullPath); oldFullPath=Utils.decodeURL(oldFullPath); try{ InputStream inputStream=repositoryService.readFile(oldFullPath, null); String content=IOUtils.toString(inputStream, "utf-8"); inputStream.close(); User user=EnvironmentUtils.getLoginUser(new RequestContext(req,resp)); repositoryService.createFile(newFullPath, content,user); loadProjects(req, resp); }catch(Exception ex){ throw new RuleException(ex); } }
/** * 判断用户session是否存在 不存在则跳转到登录页面 * 重载方法 * @param srequest * @param sresponse * @param chain * @throws IOException * @throws ServletException */ public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) srequest; HttpServletResponse response = (HttpServletResponse) sresponse; HttpSession session = request.getSession(); //获取工程路径 String path = request.getContextPath(); String requestURl = request.getRequestURI(); if(requestURl.contains("/pages") &&null != session.getAttribute("user")) chain.doFilter(request, response); else response.sendRedirect(path + "/logout.jsp"); }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); if (method.equals("requestEmail")) { String selectType = request.getParameter("selectType"); Boolean findByEmail = false; String param = ""; if (selectType.equals("radioEmail")) { findByEmail = true; param = request.getParameter("email"); } else { param = request.getParameter("login"); } handleEmailRequest(findByEmail, param.trim(), response); } else if (method.equals("requestPasswordChange")) { String newPassword = request.getParameter("newPassword"); String key = request.getParameter("key"); handlePasswordChange(newPassword, key, response); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }
private void handleLogon(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); String password = request.getParameter("password"); LoginService loginService = new LoginService(); if (loginService.isValidUser(userName, password)) { // UserBean user=loginService.getUser(); // request.setAttribute("user", user); RequestDispatcher requestDispatcher = request .getRequestDispatcher("useraccounts.jsp"); requestDispatcher.forward(request, response); } else { System.out.println("Wrong Login or Password"); response.sendRedirect("logon.jsp"); } }
/** * when a valid CORS Pre-flight request arrives, with empty * Access-Control-Request-Method * * @throws ServletException * @throws IOException */ @Test public void testCheckPreFlightRequestTypeEmptyACRM() throws ServletException, IOException { TesterHttpServletRequest request = new TesterHttpServletRequest(); request.setHeader(CorsFilter.REQUEST_HEADER_ORIGIN, TesterFilterConfigs.HTTP_TOMCAT_APACHE_ORG); request.setHeader( CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD, ""); request.setMethod("OPTIONS"); CorsFilter corsFilter = new CorsFilter(); corsFilter.init(TesterFilterConfigs .getDefaultFilterConfig()); CorsFilter.CORSRequestType requestType = corsFilter.checkRequestType(request); Assert.assertEquals(CorsFilter.CORSRequestType.INVALID_CORS, requestType); }
@Override protected void doGet( final HttpServletRequest req, final HttpServletResponse resp ) throws ServletException, IOException { for (final StaticResourceResolver resolver : staticResourceResolvers) { final StaticResourceResolver.ResolvedResource resource = resolver.resolve(req.getPathInfo()); if (resource == null) { continue; } resp.setContentType(resource.getContentType()); try { resource.getContent(resp.getOutputStream()); }catch(final IOException e) { LOG.error("I/O error serving static resource", e); resp.setStatus(500); } return; } resp.setStatus(404); }
/** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). Return * an <code>ActionForward</code> instance describing where and how control * should be forwarded, or <code>null</code> if the response has already been * completed. * * @param mapping The ActionMapping used to select this instance * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @param form NOT YET DOCUMENTED * @return NOT YET DOCUMENTED * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ActionErrors errors = new ActionErrors(); UcasProxyForm ucasForm = (UcasProxyForm) form; // Query Args String command = request.getParameter("command"); SchemEditUtils.showRequestParameters(request); try { return getUcasUserInfo(mapping, form, request, response); } catch (Throwable t) { t.printStackTrace(); errors.add("error", new ActionError("generic.error", "System Error: " + t.getMessage())); saveErrors(request, errors); } // Forward control to the specified success URI return (mapping.findForward("error.page")); }
@Override public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { logger.info("I am running!"); response.getWriter().write("Hello World!"); }
private void doForward(String relativeUrlPath) throws ServletException, IOException { // JSP.4.5 If the buffer was flushed, throw IllegalStateException try { out.clear(); } catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; } // Make sure that the response object is not the wrapper for include while (response instanceof ServletResponseWrapperInclude) { response = ((ServletResponseWrapperInclude) response).getResponse(); } final String path = getAbsolutePathRelativeToContext(relativeUrlPath); String includeUri = (String) request .getAttribute(Constants.INC_SERVLET_PATH); if (includeUri != null) request.removeAttribute(Constants.INC_SERVLET_PATH); try { context.getRequestDispatcher(path).forward(request, response); } finally { if (includeUri != null) request.setAttribute(Constants.INC_SERVLET_PATH, includeUri); } }
@Test(expected = ServletException.class) public void testDoFilterRequestNullResponse() throws IOException, ServletException { TesterHttpServletRequest request = new TesterHttpServletRequest(); CorsFilter corsFilter = new CorsFilter(); corsFilter.init(TesterFilterConfigs.getDefaultFilterConfig()); corsFilter.doFilter(request, null, filterChain); }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/SLA.jsp"); dispatcher.forward(request, response); }
@Override protected void doFilterInternal( HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { ServletRequestAttributes attributes = new ServletRequestAttributes(req, res); try { if(1 + 1 == 2) { SecurityContext oldCtx = SecurityContextHolder.getContext(); SecurityContextHolder.setContext(null); // try { super.doFilter(req, res, chain); } finally { SecurityContextHolder.setContext(oldCtx); } } else { super.doFilter(req, res, chain); } } finally { attributes.requestCompleted(); } }
@Override public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException { ((HttpServletResponse) response).addHeader( "Access-Control-Allow-Origin", "*" ); chain.doFilter(request, response); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{ String id = req.getParameter("code"); String check = req.getParameter("action"); if(check.equals("supprimer"))//pour mettre un peu de securite... uService.supprimerUtilisateur(id); // doGet(req, resp); resp.sendRedirect(req.getContextPath() + "/admin/users/list"); }
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { try { userAuditService.saveUserAuthEvent(AuthEventHelper.buildSucceedAuthEvent(request)); } catch (Throwable e) { //do nothing } response.setStatus(HttpServletResponse.SC_OK); response.getWriter().append("{\"succeed\":true}"); response.flushBuffer(); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, Object> pageVariables = new HashMap<>(); pageVariables.put(REFRESH_VARIABLE_NAME, String.valueOf(PERIOD_MS)); pageVariables.put(TIME_VARIABLE_NAME, getTime()); response.getWriter().println(TemplateProcessor.instance().getPage(TIMER_PAGE_TEMPLATE, pageVariables)); response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String PATH = request.getPathInfo(); if (PATH.equals("/favicon.ico")) { this.sendFavicon(response); } else if (PATH.equals("/ui/log")) { this.sendLog(response); } else if (PATH.equals("/ui/json")) { this.sendJsonState(response); } else if (PATH.equals("/ui/")) { this.sendMainPage(response); } else if (PATH.equals("/validate-captcha")) { this.sendCaptchaValidation(request, response); } else if (PATH.equals("/captcha.png")) { this.getCaptchaImage(request, response); } else if (PATH.equals("/")) { response.sendRedirect("/ui/"); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
/** * Process a GET request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = StringManager.getManager( Constants.Package, request.getLocales()); // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null) command = request.getServletPath(); String name = request.getParameter("name"); // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=" + Constants.CHARSET); PrintWriter writer = response.getWriter(); // Process the requested command if (command == null) { writer.println(sm.getString("hostManagerServlet.noCommand")); } else if (command.equals("/add")) { add(request, writer, name, false, smClient); } else if (command.equals("/remove")) { remove(writer, name, smClient); } else if (command.equals("/list")) { list(writer, smClient); } else if (command.equals("/start")) { start(writer, name, smClient); } else if (command.equals("/stop")) { stop(writer, name, smClient); } else { writer.println(sm.getString("hostManagerServlet.unknownCommand", command)); } // Finish up the response writer.flush(); writer.close(); }
@Test public void sessionIdShouldBeLoggedIfTheSessionExists() throws IOException, ServletException { HttpServletRequest request = requestWithSessionId("some-session-id"); filter.doFilter(request, response, (req, resp) -> { assertThat(MdcFields.getSessionId()).isEqualTo("some-session-id"); }); assertThat(MdcFields.getSessionId()).isNull(); }
/** * Handle GET requests. * * @param req Input request. * @param resp Resulting response. * @exception IOException I/O error * @exception ServletException servlet error */ public void doGet( HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Set up output writer. PrintWriter respwtr = resp.getWriter(); respwtr.print(" doGet() "); respwtr.close(); }
/** * Prepare the request based on the filter configuration. * @param request The servlet request we are processing * @param response The servlet response we are creating * @param state The RD state * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ private void processRequest(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { DispatcherType disInt = (DispatcherType) request.getAttribute(Globals.DISPATCHER_TYPE_ATTR); if (disInt != null) { boolean doInvoke = true; if (context.getFireRequestListenersOnForwards() && !context.fireRequestInitEvent(request)) { doInvoke = false; } if (doInvoke) { if (disInt != DispatcherType.ERROR) { state.outerRequest.setAttribute( Globals.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); state.outerRequest.setAttribute( Globals.DISPATCHER_TYPE_ATTR, DispatcherType.FORWARD); invoke(state.outerRequest, response, state); } else { invoke(state.outerRequest, response, state); } if (context.getFireRequestListenersOnForwards()) { context.fireRequestDestroyEvent(request); } } } }
private void handleHome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher requestDispatcher = request .getRequestDispatcher("bankhomepage.jsp"); requestDispatcher.forward(request, response); }
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Compatibility method: equivalent method using the regular connection model response.setContentType("text/html; charset=" + CHARSET); PrintWriter writer = response.getWriter(); writer.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); writer.println("<html><head><title>JSP Chat</title></head><body bgcolor=\"#FFFFFF\">"); writer.println("Chat example only supports Comet processing. "); writer.println("Configure a connector that supports Comet and try again."); writer.println("</body></html>"); }
public void init() throws ServletException { super.init(); try { ConsoleManager.initial(); } catch (Exception e) { throw new ServletException(e); } }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS,GET"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "accept,x-requested-with,Content-Type"); if("OPTIONS".equals(request.getMethod())){ //状态码204表示响应成功,但是没有返回响应信息 response.setStatus(204); return; } chain.doFilter(req, res); }
@Test(expected = ServletException.class) public void testDoFilterNullRequestResponse() throws IOException, ServletException { TesterHttpServletResponse response = new TesterHttpServletResponse(); CorsFilter corsFilter = new CorsFilter(); corsFilter.init(TesterFilterConfigs.getDefaultFilterConfig()); corsFilter.doFilter(null, response, filterChain); }
/** * OPTIONS Method. * * @param req The request * @param resp The response * @throws ServletException If an error occurs * @throws IOException If an IO error occurs */ @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("DAV", "1,2"); StringBuilder methodsAllowed = determineMethodsAllowed(resources, req); resp.addHeader("Allow", methodsAllowed.toString()); resp.addHeader("MS-Author-Via", "DAV"); }
protected final void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/xml; charset=iso-8859-1"); PrintWriter pw = resp.getWriter(); StringBuffer errCode = new StringBuffer(); long mtdeb = System.currentTimeMillis(); boolean serviceStatus = getServiceStatus(req, errCode); long tt = System.currentTimeMillis() - mtdeb; String xmlRes = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"; xmlRes = xmlRes + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xdt=\"http://www.w3.org/2004/07/xpath-datatypes\" xmlns:fn=\"http://www.w3.org/2004/07/xpath-functions\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soapenv:Body><checkserviceResponse xmlns=\"http://publigroupe.com/checkservice\"><checkserviceReturn xmlns=\"\">"; xmlRes = xmlRes + "<name xsi:type=\"xsd:string\">"; xmlRes = xmlRes + getServiceName(); xmlRes = xmlRes + "</name>"; xmlRes = xmlRes + "<status xsi:type=\"xsd:string\">"; xmlRes = xmlRes + (serviceStatus ? "ok" : "nok"); xmlRes = xmlRes + "</status>"; xmlRes = xmlRes + "<returnCode xsi:type=\"xsd:string\">"; xmlRes = xmlRes + errCode.toString(); xmlRes = xmlRes + "</returnCode>"; xmlRes = xmlRes + "<time_ms xsi:type=\"xsd:string\">"; xmlRes = xmlRes + String.valueOf(tt); xmlRes = xmlRes + "</time_ms>"; xmlRes = xmlRes + "</checkserviceReturn></checkserviceResponse></soapenv:Body></soapenv:Envelope>"; pw.print(xmlRes); info(getServiceName(), serviceStatus, errCode.toString(), tt); }
/** * Verify that we can unit test a servlet that makes calls to * <code>getServletConfig()</code>, <code>getServletContext()</code>, * <code>log()</code>, ... (i.e. methods inherited from * <code>GenericServlet</code>). */ public void testServletConfig() throws ServletException { SampleServletConfig servlet = new SampleServletConfig(); // VERY IMPORTANT : Call the init() method in order to initialize the // Servlet ServletConfig object. servlet.init(config); assertEquals("value1 used for testing", servlet.getConfigData()); }
/** * Only interested in the request headers from a GET request */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Just echo the header value back as plain text resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); processHeaders(invalidHeaderName, req, out); processHeaders("X-Bug51557", req, out); }
@Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { Servlet s; if (createServlet) { s = ctx.createServlet(servlet.getClass()); } else { s = servlet; } ServletRegistration.Dynamic r = ctx.addServlet("servlet", s); r.addMapping("/"); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(true); session.invalidate(); req.getSession(true); }