static { CONTENT_TYPES.put(ContentType.HTTP, Response.HTTP); CONTENT_TYPES.put(ContentType.MULTIPART, Response.MULTIPART); CONTENT_TYPES.put(ContentType.XML, Response.XML); for (final Entry<ContentType, String> entry : CONTENT_TYPES.entrySet()) TYPE_CONTENTS.put(entry.getValue(), entry.getKey()); }
// post方式发送email public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); File file = doAttachment(request); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setName(file.getName()); MultiPartEmail email = new MultiPartEmail(); email.setCharset("UTF-8"); email.setHostName("smtp.sina.com"); email.setAuthentication("T-GWAP", "dangdang"); try { email.addTo(parameters.get("to")); email.setFrom(parameters.get("from")); email.setSubject(parameters.get("subject")); email.setMsg(parameters.get("body")); email.attach(attachment); email.send(); request.setAttribute("sendmail.message", "邮件发送成功!"); } catch (EmailException e) { Logger logger = Logger.getLogger(SendAttachmentMailServlet.class); logger.error("邮件发送不成功", e); request.setAttribute("sendmail.message", "邮件发送不成功!"); } request.getRequestDispatcher("/sendResult.jsp").forward(request, response); }
/** Encode a query string. The input Map contains names indexing Object[]. */ public static String encodeQueryString(Map parameters) { final StringBuilder sb = new StringBuilder(100); boolean first = true; try { for (Object o : parameters.keySet()) { final String name = (String) o; final Object[] values = (Object[]) parameters.get(name); for (final Object currentValue : values) { if (currentValue instanceof String) { if (!first) sb.append('&'); sb.append(URLEncoder.encode(name, NetUtils.STANDARD_PARAMETER_ENCODING)); sb.append('='); sb.append( URLEncoder.encode((String) currentValue, NetUtils.STANDARD_PARAMETER_ENCODING)); first = false; } } } } catch (UnsupportedEncodingException e) { // Should not happen as we are using a required encoding throw new OXFException(e); } return sb.toString(); }
public static Map<String, String> getContentTypeParameters(String contentType) { if (contentType == null) return null; // Check whether there may be parameters final int semicolonIndex = contentType.indexOf(";"); if (semicolonIndex == -1) return null; // Tokenize final StringTokenizer st = new StringTokenizer(contentType, ";"); if (!st.hasMoreTokens()) return null; // should not happen as there should be at least the content type st.nextToken(); // No parameters if (!st.hasMoreTokens()) return null; // Parse parameters final Map<String, String> parameters = new HashMap<String, String>(); while (st.hasMoreTokens()) { final String parameter = st.nextToken().trim(); final int equalIndex = parameter.indexOf('='); if (equalIndex == -1) continue; final String name = parameter.substring(0, equalIndex).trim(); final String value = parameter.substring(equalIndex + 1).trim(); parameters.put(name, value); } return parameters; }
@Override public void parseRequestParameters( final Map<String, String> params, final Map<String, com.bradmcevoy.http.FileItem> files) throws RequestParseException { try { if (isMultiPart()) { parseQueryString(params, req.getQueryString()); @SuppressWarnings("unchecked") final List<FileItem> items = new ServletFileUpload().parseRequest(req); for (final FileItem item : items) { if (item.isFormField()) params.put(item.getFieldName(), item.getString()); else files.put(item.getFieldName(), new FileItemWrapper(item)); } } else { final Enumeration<String> en = req.getParameterNames(); while (en.hasMoreElements()) { final String nm = en.nextElement(); final String val = req.getParameter(nm); params.put(nm, val); } } } catch (final FileUploadException ex) { throw new RequestParseException("FileUploadException", ex); } catch (final Throwable ex) { throw new RequestParseException(ex.getMessage(), ex); } }
@Override public Map<String, String> getHeaders() { final Map<String, String> map = new HashMap<>(); final Enumeration<String> en = req.getHeaderNames(); while (en.hasMoreElements()) { final String name = en.nextElement(); final String val = req.getHeader(name); map.put(name, val); } return map; }
public static Map<String, String> getCharsetHeaderCharsets(String header) { if (header == null) return null; int semicolonIndex = header.indexOf(";"); final String charsets; if (semicolonIndex == -1) charsets = header.trim(); else charsets = header.substring(0, semicolonIndex).trim(); final StringTokenizer st = new StringTokenizer(charsets, ","); final Map<String, String> charsetsMap = new HashMap<String, String>(); while (st.hasMoreTokens()) { charsetsMap.put(st.nextToken(), ""); } return charsetsMap; }
public File doAttachment(HttpServletRequest request) throws ServletException, IOException { File file = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<?> items = upload.parseRequest(request); Iterator<?> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { parameters .put(item.getFieldName(), item.getString("UTF-8")); } else { File tempFile = new File(item.getName()); file = new File(sc.getRealPath("/") + savePath, tempFile .getName()); item.write(file); } } } catch (Exception e) { Logger logger = Logger.getLogger(SendAttachmentMailServlet.class); logger.error("邮件发送出了异常", e); } return file; }
/** Combine a path info and a parameters map to form a path info with a query string. */ public static String pathInfoParametersToPathInfoQueryString(String pathInfo, Map parameters) throws IOException { final StringBuilder redirectURL = new StringBuilder(pathInfo); if (parameters != null) { boolean first = true; for (Object o : parameters.keySet()) { final String name = (String) o; final Object[] values = (Object[]) parameters.get(name); for (final Object currentValue : values) { if (currentValue instanceof String) { redirectURL.append(first ? "?" : "&"); redirectURL.append(URLEncoder.encode(name, NetUtils.STANDARD_PARAMETER_ENCODING)); redirectURL.append("="); redirectURL.append( URLEncoder.encode((String) currentValue, NetUtils.STANDARD_PARAMETER_ENCODING)); first = false; } } } } return redirectURL.toString(); }
/** * Parse the query string. * * @param map parsed key-values will be stored here * @param qs query string */ private static void parseQueryString(final Map<String, String> map, final String qs) { if (qs == null) return; for (final String nv : qs.split("&")) { final String[] parts = nv.split("="); final String key = parts[0]; String val = null; if (parts.length > 1) { val = parts[1]; if (val != null) { try { val = URLDecoder.decode(val, Token.UTF8); } catch (final UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } } map.put(key, val); } }
public static String getContentTypeCharset(String contentType) { final Map<String, String> parameters = getContentTypeParameters(contentType); return (parameters == null) ? null : parameters.get("charset"); }
/** * Request content type. * * @return the content type of the current request */ private ContentType getRequestContentType() { final String s = req.getContentType(); if (s == null) return null; if (s.contains(Response.MULTIPART)) return ContentType.MULTIPART; return TYPE_CONTENTS.get(s); }