@SuppressWarnings("squid:S00112") @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // create response wrapper to capture the output stream from further down the filter chain ResponseWrapper respWrap = new ResponseWrapper((HttpServletResponse) servletResponse); filterChain.doFilter(servletRequest, respWrap); HttpServletRequest req = (HttpServletRequest) servletRequest; // Print out info from request & response wrapper LOG.info("URI: {}", req.getRequestURI()); LOG.info("Status: {}", respWrap.getStatus()); LOG.info("resp Header 'Content-Type: {}", respWrap.getHeader("Content-Type")); String content = respWrap.getContent(); LOG.info("Content Body: '{}'", content); // verify that the content is not empty. This fails in repose but works in tomcat if (content.isEmpty()) { throw new RuntimeException("Content is empty"); } // writer content to the actual servletResponse & append additional content servletResponse .getWriter() .write( content + "<extra> Added by TestFilter, should also see the rest of the content </extra>"); servletResponse.getWriter().flush(); }
private void generateAPIResponse(ServletRequest request, ServletResponse response) { try { HttpServletRequest httpRequest = (HttpServletRequest) request; String message = "Server is under maintenance mode, please try later."; if (requestIsOfType(JSON, httpRequest)) { response.setContentType("application/json"); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("message", message); response.getWriter().print(jsonObject); } else if (requestIsOfType(XML, httpRequest)) { response.setContentType("application/xml"); String xml = String.format("<message> %s </message>", message); response.getWriter().print(xml); } else { generateHTMLResponse(response); } } catch (IOException e) { LOGGER.error(String.format("General IOException: %s", e.getMessage())); } ((HttpServletResponse) response).setStatus(503); }
/* ------------------------------------------------------------ */ private void commitResponse(ServletResponse response, Request baseRequest) throws IOException { if (baseRequest.getResponse().isWriting()) { try { response.getWriter().close(); } catch (IllegalStateException e) { response.getOutputStream().close(); } } else { try { response.getOutputStream().close(); } catch (IllegalStateException e) { response.getWriter().close(); } } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse rpo = (HttpServletResponse) response; javax.servlet.http.HttpSession session = req.getSession(); try { req.setCharacterEncoding("utf-8"); } catch (Exception e1) { e1.printStackTrace(); } String userId = (String) session.getAttribute("username"); if (userId != null) { try { chain.doFilter(request, response); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print("{'success':false,'msg':'未登录或登录失效'}"); out.flush(); out.close(); // rpo.sendRedirect("/login.jsp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println("<h1>hello Servlet</h1>"); }
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { int a = Integer.parseInt(request.getParameter("a")); int b = Integer.parseInt(request.getParameter("b")); String op = request.getParameter("op"); int result = 0; switch (op) { case "+": result = a + b; break; case "-": result = a - b; break; case "*": result = a * b; break; case "/": result = a / b; break; } response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>" + a + " " + op + " " + b + " = " + result + "</p>"); out.println("</body>"); out.println("</html>"); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { PrintWriter out = response.getWriter(); out.print(getClass().getName()); chain.doFilter(request, response); }
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println("service"); // 최초로 파라미터 값을 꺼내기 전에 클라이언트가 보낸 문자의 코드를 먼저 설정해야 한다. // 단, POST 방식에만 해당! // GET? 서블릿 컨테이너 마다 달라요! // 톰캣은? 구글링! request.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); char c; for (int i = 0; i < name.length(); i++) { c = name.charAt(i); System.out.println(Integer.toHexString(c)); } response.setContentType("text/plain;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("안녕하세요!"); out.println("이름: " + name); out.println("나이: " + age); }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { PrintWriter w = res.getWriter(); w.write(foo != null ? foo.peek() : "foo was null for peek"); filterChain.doFilter(req, res); w.write(foo != null ? foo.poke() : "foo was null for poke"); }
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { int no = Integer.parseInt(request.getParameter("no")); productDao.delete(no); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<mete http-equiv='Refresh' content='5;url=list'>"); out.println("<link rel='stylesheet' "); out.println("href='../../css/bootstrap.min.css'>"); out.println("<link rel='stylesheet' "); out.println("href='../../css/bootstrap-theme.min.css'>"); out.println("<link rel='stylesheet' href='../../css/common.css'>"); out.println("</head>"); out.println("<body>"); out.println("<div class='container'>"); out.println("<h1>삭제 결과</h1>"); out.println("<p>삭제하였습니다.</p>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); }
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println("from service"); PrintWriter out = response.getWriter(); out.println("Hello.Roses are red."); out.print("Violets are blue."); }
/** Executes the JSP Page */ public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; _caucho_init(req, res); if (_hasSession) { req.getSession(); res.setHeader("Cache-Control", "private"); } // res.setContentLength(_contentLength); TempCharBuffer buf = TempCharBuffer.allocate(); char[] cBuf = buf.getBuffer(); int len; PrintWriter out = response.getWriter(); ReadStream rs = _cacheEntry.openRead(); rs.setEncoding("UTF-8"); try { while ((len = rs.read(cBuf, 0, cBuf.length)) > 0) { out.write(cBuf, 0, len); } } finally { rs.close(); } TempCharBuffer.free(buf); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { response.setContentType("text/plain"); response.getWriter().print("Filter"); chain.doFilter(request, response); }
public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { visits.recordVisit(); List<Visit> recordedVisits = visits.getVisits(); res.getWriter().write(recordedVisits.toString()); }
/** * CSV output contains one recommendation per line, and each line is of the form {@code * itemID,strength}, like {@code "ABC",0.53}. Strength is an opaque indicator of the relative * quality of the recommendation. */ final void output(ServletResponse response, Iterable<IDValue> items) throws IOException { Writer writer = response.getWriter(); for (IDValue item : items) { writer.write(DelimitedDataUtils.encode(item.getID(), Float.toString(item.getValue()))); writer.write('\n'); } }
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // ServletConfig conf=getServletConfig(); PrintWriter out = response.getWriter(); ServletContext ctx = getServletContext(); String place = ctx.getInitParameter("pl"); String email = ctx.getInitParameter("em"); String name = ctx.getInitParameter("nm"); Student s = new Student(); s.id = 12; s.name = "raju"; ctx.setAttribute("stu", s); String[] frtArr = {"mango", "orange", "grapes"}; ctx.setAttribute("arr", frtArr); out.println( "<html><body bgcolor='yellow'>" + "<h1>ONE</h1>" + "<p>" + place + "<br>" + email + "<br>" + name + "</p>" + "<a href='TwoServ'>two</a>" + "</body></html>"); out.close(); }
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { m_logger.info("PublisherFilter doFilter"); HttpServletRequest httpReq = (HttpServletRequest) req; String remoteReq = httpReq.getRequestURL().toString(); int idx = remoteReq.lastIndexOf('/'); String res = null; try { String id = req.getParameter("id"); if (remoteReq.substring(idx).startsWith("/info")) { res = m_helper.getInfo(id); m_logger.debug(" Pub id=" + id + " " + res); if (res == null) { req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e200"); } else { resp.setContentType("text/json"); PrintWriter pm = resp.getWriter(); pm.write(res); pm.close(); } } } catch (PaperMinerException ex) { req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e201"); } filterChain.doFilter(req, resp); return; }
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { /** * We get the content length using getContentLength and we read from the input stream. if the no * of chars read matches the no returned by getContentLength we pass the test */ PrintWriter out = response.getWriter(); // get the content length int contentLength = request.getContentLength(); int len = 0; // getting input stream ServletInputStream sin = request.getInputStream(); // read from the stream while (sin.read() != -1) { len++; } // did we get what we wrote if ((contentLength == len) || (contentLength == -1)) { out.println("GetContentLengthTest test PASSED"); } else { out.println("GetContentLengthTest test FAILED <BR> "); out.println(" ServletRequest.getContentLength() method FAILED <BR> "); out.println(" Expected Value returned ->" + contentLength + " <BR> "); out.println(" Actual Value returned -> " + len); } }
@Override public void onError(AsyncEvent event) throws IOException { ServletResponse resp = event.getAsyncContext().getResponse(); resp.getWriter().write("onError-"); resp.flushBuffer(); if (completeOnError) { event.getAsyncContext().complete(); } }
@RequestMapping("{productId}") public void jsonProduct(@PathVariable Integer productId, ServletResponse resp) { try { resp.getWriter().print("{id='" + productId + "', name='vodor'}"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { System.out.println("\n\n-----Service called----\n"); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.print("<html><body>"); out.print("<b>hello simple servlet</b>"); out.print("</body></html>"); }
private void generateResponseForIsBackupFinishedAPI(ServletResponse response) { response.setContentType("application/json"); JsonObject json = new JsonObject(); json.addProperty("is_backing_up", backupService.isBackingUp()); try { response.getWriter().print(json); } catch (IOException e) { LOGGER.error(String.format("General IOException: %s", e.getMessage())); } }
/** {@inheritDoc} */ @Override public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { try { templateEngine.process("index", createContext(request, response), response.getWriter()); } catch (Exception e) { throw new ServletException(e); } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // if a book has been reserved then it cannot be reserved again, cannot be edited and cannot be // removed // if a book has been returned then it cannot be returned again boolean canProceed = false; boolean tryingToReturnBook = (request.getParameter("returningBook") != null); EntityManager em = PersistenceAdapter.getEntityManager(); String title = request.getParameter("bookName").trim(); String author = request.getParameter("authorName").trim(); Book book = (Book) em.createNamedQuery("bookByTitleAndAuthor") .setParameter("bookName", title) .setParameter("authorName", author) .getSingleResult(); try { em.createNamedQuery("lendingByBook").setParameter("lendedBook", book).getSingleResult(); // if the user is trying to return a book and the book has been borrowed then we can proceed if (tryingToReturnBook) { canProceed = true; } else { canProceed = false; } } catch (NoResultException exc) { // if the book has not been borrowed and the user is trying to return it, then we cannot // proceed if (tryingToReturnBook) { canProceed = false; } else { canProceed = true; } } if (canProceed) { chain.doFilter(request, response); } else { JsonObject object = new JsonObject(); object.addProperty("canProceed", false); response.getWriter().print(new Gson().toJson(object)); ((HttpServletResponse) response).setStatus(400); return; } }
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println( "<h1>company " + conf.getInitParameter("company") + " @ " + conf.getInitParameter("location") + "</h1>"); }
public String execute() throws IOException { ArrayList<MeetingRoom> tran; ServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); DeleteMeetingRoomService show = new DeleteMeetingRoomService(); tran = show.Showlist(); JSONArray jsonArray = JSONArray.fromObject(tran); out.print(jsonArray); return null; }
/** * 输出JSON * * @param response * @param json * @throws IOException */ public static void writeJsonToResponse(ServletResponse response, JSONObject json) throws IOException { response.setContentType("text/html;charset=utf-8"); /*//放开下面注释的代码就可以支持跨域 if (response instanceof javax.servlet.http.HttpServletResponse) { //"*"表明允许任何地址的跨域调用,正式部署时应替换为正式地址 ((javax.servlet.http.HttpServletResponse)response).addHeader("Access-Control-Allow-Origin", "*"); }*/ response.getWriter().write(json.toJSONString()); }
/** * Services this request in the same way as it would be serviced if configured as a Servlet. Does * not invoke any filters further down the chain. See the class-level comment for the reason why * this servlet might be configured as a filter. */ @Override public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (Math.random() > 0.7d) { // response.setStatus(404); response.getWriter().println("The chaos monkey strikes again!"); response.flushBuffer(); } else { super.doFilter(request, response, chain); } }
@Override public void onTimeout(AsyncEvent event) throws IOException { ServletResponse resp = event.getAsyncContext().getResponse(); resp.getWriter().write("onTimeout-"); resp.flushBuffer(); if (completeOnTimeout) { if (dispatchUrl == null) { event.getAsyncContext().complete(); } else { event.getAsyncContext().dispatch(dispatchUrl); } } }
private void generateHTMLResponse(ServletResponse response) { String path = "backup_in_progress.html"; InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(path); response.setContentType("text/html"); try { String content = FileUtil.readToEnd(resourceAsStream); content = replaceStringLiterals(content); response.getWriter().print(content); resourceAsStream.close(); } catch (IOException e) { LOGGER.error(String.format("General IOException: %s", e.getMessage())); } }