protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); User user = userService.find(username, password); if (user != null) { request.getSession().setAttribute("user", user); // Login user. response.sendRedirect("home"); // Redirect to home page. } else { request.setAttribute("message", "Unknown username/password. Please retry."); // Store error message in request scope. request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to JSP page to redisplay login form with error. } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String description = request.getParameter("description"); // Retrieves <input type="text" name="description"> Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file"> String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix. InputStream fileContent = filePart.getInputStream(); // ... (do your job here) }
public class ExampleServlet extends HttpServlet { private Object thisIsNOTThreadSafe; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object thisIsThreadSafe; thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests! thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe. } }
/** * Invoked to send a server error. Sets the status to 500 and also sets the * request attribute "javax.servlet.error.exception" to the Exception. */ protected void sendServerError(Exception ex, HttpServletRequest request, HttpServletResponse response) throws IOException { request.setAttribute("javax.servlet.error.exception", ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); }
@Override protected boolean shouldNotFilter(HttpServletRequest request) { for (String headerName : FORWARDED_HEADER_NAMES) { if (request.getHeader(headerName) != null) { return false; } } return true; }
/** * Lazily initialize the target Writer. */ protected PrintWriter getTargetWriter() throws IOException { if (this.targetWriter == null) { this.targetWriter = this.response.getWriter(); } return this.targetWriter; }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { request.setAttribute(RESOURCE_URL_PROVIDER_ATTR, this.resourceUrlProvider); return true; }
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); } }
@SuppressWarnings("unchecked") private Map<String, String> getUriTemplateVariables(HttpServletRequest request) { String attrName = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; return (Map<String, String>) request.getAttribute(attrName); }
@Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException { res.sendRedirect(location); } };
/** * Prevents the response from being cached, through setting corresponding * HTTP {@code Cache-Control: no-store} header. * @param response current HTTP response */ protected void preventCaching(HttpServletResponse response) { response.addHeader(HEADER_CACHE_CONTROL, "no-store"); }
@Override public InputStream getBody() throws IOException { return request.getInputStream(); } };
@Override public void sessionDestroyed(HttpSessionEvent event) { event.getSession().removeAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ... List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true"> for (Part filePart : fileParts) { String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix. InputStream fileContent = filePart.getInputStream(); // ... (do your job here) } }
@SuppressWarnings("deprecation") @Override public void setStatus(int sc, String sm) { super.setStatus(sc, sm); this.statusCode = sc; }
@Override public String getCharacterEncoding() { String enc = super.getCharacterEncoding(); return (enc != null ? enc : WebUtils.DEFAULT_CHARACTER_ENCODING); }
/** * Expose the path within the current mapping as request attribute. * @param pathWithinMapping the path within the current mapping * @param request the request to expose the path to * @see #PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE */ protected void exposePathWithinMapping(String bestMatchingPattern, String pathWithinMapping, HttpServletRequest request) { request.setAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE, bestMatchingPattern); request.setAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, pathWithinMapping); }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.sendRedirect("/login"); } }
@Override public void setStatus(int sc) { super.setStatus(sc); this.statusCode = sc; }
/** * Invoked when a matching mapping is found. * @param mapping the matching mapping * @param lookupPath mapping lookup path within the current servlet mapping * @param request the current request */ protected void handleMatch(T mapping, String lookupPath, HttpServletRequest request) { request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, lookupPath); }