For IntelliJ IDEA,
Android Studio or Eclipse



private void myMethod () {ServletException s =
Throwable rootCause;new ServletException(rootCause)
new ServletException()
String message;new ServletException(message)
- Smart code suggestions by Codota
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<Product> products = productService.list(); // Obtain all products. request.setAttribute("products", products); // Store products in request scope. request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table. } catch (SQLException e) { throw new ServletException("Retrieving products failed!", e); } }
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Action action = ActionFactory.getAction(request); String view = action.execute(request, response); if (view.equals(request.getPathInfo().substring(1)) { request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response); } else { response.sendRedirect(view); } } catch (Exception e) { throw new ServletException("Executing action failed.", e); } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { throw new ServletException("ResourceUrlEncodingFilter just supports HTTP requests"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; filterChain.doFilter(httpRequest, new ResourceUrlEncodingResponseWrapper(httpRequest, httpResponse)); }
@Override public void init() throws ServletException { pipeline = new StanfordCoreNLP(); String xslPath = getServletContext(). getRealPath("/WEB-INF/data/CoreNLP-to-HTML.xsl"); try { Builder builder = new Builder(); Document stylesheet = builder.build(new File(xslPath)); corenlpTransformer = new XSLTransform(stylesheet); } catch (Exception e) { throw new ServletException(e); } }
public void loadConfiguration(ServletConfig sc) throws ServletException { if (!autoDetectHandlers) return; try { URL url = sc.getServletContext().getResource(handlersPath); URLClassLoader urlC = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader()); loadAtmosphereDotXml(sc.getServletContext(). getResourceAsStream(atmosphereDotXmlPath), urlC); if (atmosphereHandlers.isEmpty()) { autoDetectAtmosphereHandlers(sc.getServletContext(), urlC); if (atmosphereHandlers.isEmpty()) { detectSupportedFramework(sc); } } autoDetectWebSocketHandler(sc.getServletContext(), urlC); } catch (Throwable t) { throw new ServletException(t); } }
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest) req; response = (HttpServletResponse) res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } if (redirectInfo.doLocal(request.getRequestURI())) { chain.doFilter(request, response); } else { URL url = redirectInfo.getRedirectURL(request.getQueryString(), request.getRequestURI()); log.debug("Forwarding request to [%s]", url); if (url == null) { // We apparently have nothing to redirect to, so let's do a Service Unavailable response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setHeader("Location", url.toString()); } }
@Override public void init(ServletConfig config) throws ServletException { super.init(config); final ServletContext context = config.getServletContext(); if (null == registry) { final Object registryAttr = context.getAttribute(METRICS_REGISTRY); if (registryAttr instanceof MetricRegistry) { this.registry = (MetricRegistry) registryAttr; } else { throw new ServletException("Couldn't find a MetricRegistry instance."); } } final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), TimeUnit.SECONDS); final TimeUnit durationUnit = parseTimeUnit(context.getInitParameter(DURATION_UNIT), TimeUnit.SECONDS); final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); if (filter == null) { filter = MetricFilter.ALL; } this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit, durationUnit, showSamples, filter)); this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); }
String imageName = request.getPathInfo().substring(1); // Returns "foo.png". if (resultSet.next()) { byte[] content = resultSet.getBytes("content"); response.setContentType(getServletContext().getMimeType(imageName)); response.setContentLength(content.length); response.getOutputStream().write(content); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. throw new ServletException("Something failed at SQL/DB level.", e);
@Override public void init(ServletConfig config) throws ServletException { super.init(config); final ServletContext context = config.getServletContext(); if (null == registry) { final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); if (registryAttr instanceof HealthCheckRegistry) { this.registry = (HealthCheckRegistry) registryAttr; } else { throw new ServletException("Couldn't find a HealthCheckRegistry instance."); } } final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); if (executorAttr instanceof ExecutorService) { this.executorService = (ExecutorService) executorAttr; } final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); if (filterAttr instanceof HealthCheckFilter) { filter = (HealthCheckFilter) filterAttr; } if (filter == null) { filter = HealthCheckFilter.ALL; } this.mapper = new ObjectMapper().registerModule(new HealthCheckModule()); }
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ServletContext servletContext = getServletContext(); Assert.state(servletContext != null, "No ServletContext"); RequestDispatcher rd = servletContext.getNamedDispatcher(this.servletName); if (rd == null) { throw new ServletException("No servlet with name '" + this.servletName + "' defined in web.xml"); } // If already included, include again, else forward. if (useInclude(request, response)) { rd.include(request, response); if (logger.isDebugEnabled()) { logger.debug("Included servlet [" + this.servletName + "] in ServletForwardingController '" + this.beanName + "'"); } } else { rd.forward(request, response); if (logger.isDebugEnabled()) { logger.debug("Forwarded to servlet [" + this.servletName + "] in ServletForwardingController '" + this.beanName + "'"); } } return null; }
throw new ServletException(re); String fullParameter = request.getParameter("full"); boolean minimalOutput = fullParameter != null && !Boolean.parseBoolean(fullParameter); if (minimalOutput) { response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); try (Writer out = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) { for (Result result : results) { out.write(result.getText()); request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
/** * Prepare for rendering, and determine the request dispatcher path * to forward to (or to include). * <p>This implementation simply returns the configured URL. * Subclasses can override this to determine a resource to render, * typically interpreting the URL in a different manner. * @param request current HTTP request * @param response current HTTP response * @return the request dispatcher path to use * @throws Exception if preparations failed * @see #getUrl() */ protected String prepareForRendering(HttpServletRequest request, HttpServletResponse response) throws Exception { String path = getUrl(); Assert.state(path != null, "'url' not set"); if (this.preventDispatchLoop) { String uri = request.getRequestURI(); if (path.startsWith("/") ? uri.equals(path) : uri.equals(StringUtils.applyRelativePath(uri, path))) { throw new ServletException("Circular view path [" + path + "]: would dispatch back " + "to the current handler URL [" + uri + "] again. Check your ViewResolver setup! " + "(Hint: This may be the result of an unspecified view, due to default view name generation.)"); } } return path; }
final String token = tokenExtractor.getToken(httpRequest); if (shouldSkipAuthentication(httpRequest, token)) { filterChain.doFilter(request, response); return; final HttpSession session = httpRequest.getSession(); Subject subject = (Subject) session.getAttribute("che_subject"); if (subject == null || !subject.getToken().equals(token)) { Jwt jwtToken = (Jwt) httpRequest.getAttribute("token"); if (jwtToken == null) { throw new ServletException("Cannot detect or instantiate user."); new AuthorizedSubject( new SubjectImpl(user.getName(), user.getId(), token, false), permissionChecker); session.setAttribute("che_subject", subject); } catch (ServerException | ConflictException e) { throw new ServletException( "Unable to identify user " + claims.getSubject() + " in Che database", e); filterChain.doFilter(addUserInRequest(httpRequest, subject), response); } finally { EnvironmentContext.reset();
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String maxRequests = req.getParameter("maxRequests"); int max; try { max = 3; String id = req.getParameter("id"); int requestNo = increment(id); String servlet = req.getParameter("servlet"); String io = req.getParameter("io"); String error = req.getParameter("500"); res.setHeader("Success-On-Attempt", "" + requestNo); res.setHeader("id", id); if (servlet != null && servlet.trim().length() > 0) res.setHeader("type", "servlet"); if (error != null && error.trim().length() > 0) res.setHeader("type", "500"); throw new ServletException("Servlet Exception");
response.getWriter().write(String.valueOf(html)); throw new ServletException("Failed to render script template", new StandardScriptEvalException(ex));
throw new ServletException("OncePerRequestFilter just supports HTTP requests"); filterChain.doFilter(request, response);
/** * Create new ServletConfigPropertyValues. * @param config ServletConfig we'll use to take PropertyValues from * @param requiredProperties set of property names we need, where * we can't accept default values * @throws ServletException if any required properties are missing */ public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties) throws ServletException { Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ? new HashSet<>(requiredProperties) : null); Enumeration<String> paramNames = config.getInitParameterNames(); while (paramNames.hasMoreElements()) { String property = paramNames.nextElement(); Object value = config.getInitParameter(property); addPropertyValue(new PropertyValue(property, value)); if (missingProps != null) { missingProps.remove(property); } } // Fail if we are still missing properties. if (!CollectionUtils.isEmpty(missingProps)) { throw new ServletException( "Initialization from ServletConfig for servlet '" + config.getServletName() + "' failed; the following required properties were missing: " + StringUtils.collectionToDelimitedString(missingProps, ", ")); } } }
@Override public void init() throws ServletException { format = getServletConfig().getInitParameter("outputFormat"); if (format == null || format.trim().isEmpty()) { throw new ServletException("Invalid outputFormat setting."); String spacingStr = getServletConfig().getInitParameter("preserveSpacing"); if (spacingStr == null || spacingStr.trim().isEmpty()) { throw new ServletException("Invalid preserveSpacing setting."); spacing = "true".equals(spacingStr); String path = getServletContext().getRealPath("/WEB-INF/data/models"); for (String classifier : new File(path).list()) { classifiers.add(classifier); CRFClassifier model = null; String filename = "/WEB-INF/data/models/" + classifier; InputStream is = getServletConfig().getServletContext().getResourceAsStream(filename); throw new ServletException("File not found. Filename = " + filename); throw new ServletException("IO problem reading classifier."); } catch (ClassCastException e) { throw new ServletException("Classifier class casting problem."); } catch (ClassNotFoundException e) { throw new ServletException("Classifier class not found problem."); } finally { IOUtils.closeIgnoringExceptions(is);
for (Enumeration<String> en = request.getAttributeNames(); en.hasMoreElements();) { String attribute = en.nextElement(); if (model.containsKey(attribute) && !this.allowRequestOverride) { throw new ServletException("Cannot expose request attribute '" + attribute + "' because of an existing model object of the same name"); Object attributeValue = request.getAttribute(attribute); if (logger.isDebugEnabled()) { logger.debug("Exposing request attribute '" + attribute + HttpSession session = request.getSession(false); if (session != null) { for (Enumeration<String> en = session.getAttributeNames(); en.hasMoreElements();) { String attribute = en.nextElement(); if (model.containsKey(attribute) && !this.allowSessionOverride) { throw new ServletException("Cannot expose session attribute '" + attribute + "' because of an existing model object of the same name"); Object attributeValue = session.getAttribute(attribute); if (logger.isDebugEnabled()) { logger.debug("Exposing session attribute '" + attribute + throw new ServletException( "Cannot expose bind macro helper '" + SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE + "' because of an existing model object of the same name");
throw e; } catch (Throwable e) { throw new ServletException("Throwable", e); servlet.service(request, response); } else { RequestDispatcher rd = configImpl.getServletContext().getNamedDispatcher("default"); if (rd == null) { throw new ServletException("No Servlet Found"); rd.forward(request, response); throw e; } catch (Throwable e) { throw new ServletException("Throwable", e);