List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:org.primeframework.mvc.action.result.JSONResultTest.java
@Test(dataProvider = "httpMethod") public void errors(HTTPMethod httpMethod) throws IOException, ServletException { Post action = new Post(); ExpressionEvaluator ee = createStrictMock(ExpressionEvaluator.class); replay(ee);/*w ww . j a v a 2 s . co m*/ MockServletOutputStream sos = new MockServletOutputStream(); HttpServletResponse response = createStrictMock(HttpServletResponse.class); response.setStatus(400); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.setContentLength(359); if (httpMethod == HTTPMethod.GET) { expect(response.getOutputStream()).andReturn(sos); } replay(response); Map<Class<?>, Object> additionalConfiguration = new HashMap<>(); additionalConfiguration.put(JacksonActionConfiguration.class, new JacksonActionConfiguration(null, null, "user")); ActionConfiguration config = new ActionConfiguration(Post.class, null, null, null, null, null, null, null, null, null, null, null, null, additionalConfiguration, null); ActionInvocationStore store = createStrictMock(ActionInvocationStore.class); expect(store.getCurrent()).andReturn(new ActionInvocation(action, new ExecuteMethodConfiguration(httpMethod, null, null), "/foo", "", config)); replay(store); MessageStore messageStore = createStrictMock(MessageStore.class); expect(messageStore.get(MessageScope.REQUEST)).andReturn(asList( new SimpleMessage(MessageType.ERROR, "[invalid]", "Invalid request"), new SimpleMessage(MessageType.ERROR, "[bad]", "Bad request"), new SimpleFieldMessage(MessageType.ERROR, "user.age", "[required]user.age", "Age is required"), new SimpleFieldMessage(MessageType.ERROR, "user.age", "[number]user.age", "Age must be a number"), new SimpleFieldMessage(MessageType.ERROR, "user.favoriteMonth", "[required]user.favoriteMonth", "Favorite month is required"))); replay(messageStore); JSON annotation = new JSONResultTest.JSONImpl("input", 400); JSONResult result = new JSONResult(ee, store, messageStore, objectMapper, response); result.execute(annotation); String expected = "{" + " \"fieldErrors\":{" + " \"user.age\":[{\"code\":\"[required]user.age\",\"message\":\"Age is required\"},{\"code\":\"[number]user.age\",\"message\":\"Age must be a number\"}]," + " \"user.favoriteMonth\":[{\"code\":\"[required]user.favoriteMonth\",\"message\":\"Favorite month is required\"}]" + " }," + " \"generalErrors\":[" + " {\"code\":\"[invalid]\",\"message\":\"Invalid request\"},{\"code\":\"[bad]\",\"message\":\"Bad request\"}" + " ]" + "}"; assertEquals(sos.toString(), httpMethod == HTTPMethod.GET ? expected.replace(" ", "") : ""); // Un-indent verify(ee, messageStore, response); }
From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java
@Override public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {/*from w w w. j a v a 2 s .co m*/ // We always return xhtml in utf-8 response.setContentType("application/xhtml+xml"); response.setCharacterEncoding("utf-8"); // Default filename just in case none is found in form String filename = defaultFilename; // Commons file upload ServletFileUpload upload = new ServletFileUpload(); // Go through upload items FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // Parse form fields String fieldname = item.getFieldName(); if ("chartFilename".equals(fieldname)) { // Ordering is important in client page! We expect filename BEFORE data. Otherwise filename will be default // See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 // "The parts are sent to the processing agent in the same order the // corresponding controls appear in the document stream." filename = Streams.asString(stream, "utf-8"); } else if ("chartDataXML".equals(fieldname)) { log.info("Doing form bounce"); String filenameAscii = formSafeAscii(filename); String fileNameUtf = formSafeUtfName(filename); String cdh = "attachment; filename=\"" + filenameAscii + "\"; filename*=utf-8''" + fileNameUtf; response.setHeader("Content-Disposition", cdh); ServletOutputStream out = response.getOutputStream(); Streams.copy(stream, out, false); out.flush(); // No more processing needed (prevent BOTH form AND upload from happening) return; } } else { // Handle upload log.info("Doing file bounce"); ServletOutputStream out = response.getOutputStream(); Streams.copy(stream, out, false); out.flush(); // No more processing needed (prevent BOTH form AND upload from happening) return; } } } catch (Exception ex) { throw new ServletException(ex); } }
From source file:net.duckling.ddl.web.controller.pan.PanDownloadController.java
/** * /*from w w w. j a v a 2s . co m*/ * @param path * @param size ? xs:32x32, s:64x64, m:128x128, l:640x480, xl:1024x768 * @param request * @param response */ @WebLog(method = "PanThumbnails", params = "path,size") @RequestMapping("/thumbnails") public void thumbnails(@RequestParam("path") String path, @RequestParam("size") String size, HttpServletRequest request, HttpServletResponse response) { OutputStream os = null; try { PanAcl acl = PanAclUtil.getInstance(request); MeePoMeta meta = panService.ls(acl, path, true); response.setCharacterEncoding("utf-8"); String headerValue = ResponseHeaderUtils.buildResponseHeader(request, meta.name, true); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", headerValue); os = response.getOutputStream(); panService.thumbnails(acl, path, size, os); } catch (UnsupportedEncodingException e) { LOG.error("", e); } catch (MeePoException e) { LOG.error("", e); } catch (IOException e) { LOG.error("", e); } catch (Exception e) { LOG.error("", e); } finally { IOUtils.closeQuietly(os); } }
From source file:org.n52.sensorweb.series.policy.editor.ctrl.DownloadController.java
@RequestMapping(value = "/view", method = RequestMethod.GET) public void viewPermissionsXml(HttpServletResponse response) throws IOException { File downloadFile = new File(permissionsXmlPath); FileInputStream inputStream = new FileInputStream(downloadFile); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); }/* ww w . j a va 2 s. c om*/ inputStream.close(); outStream.close(); }
From source file:fi.hoski.web.forms.EventServlet.java
private void sendError(HttpServletResponse response, int statusCode, String htmlMessage) throws IOException { response.setStatus(statusCode);//from ww w. j a v a 2 s .co m response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); response.getWriter().write(htmlMessage); }
From source file:controller.productServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String command = request.getParameter("command"); String proid = request.getParameter("product_id"); String url = ""; try {//from w ww . ja v a2 s . c o m switch (command) { case "delete": if (prod.countProductByBill(Integer.parseInt(proid)) > 0) { out.println("Ban k the xoa san pham nay"); out.flush(); return; } else { fedd.deleteFeedbackByProduct(Integer.parseInt(proid)); prod.deleteProduct(Integer.parseInt(proid)); url = "/java/admin/ql-product.jsp"; } break; } } catch (Exception e) { } response.sendRedirect(url); }
From source file:controller.categoryServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String command = request.getParameter("command"); String catid = request.getParameter("category_id"); String url = ""; try {/*from w w w . j a v a2 s .co m*/ switch (command) { case "delete": CategoryEntity cateen = new CategoryEntity(); if (pro.countProductByCategory(Integer.parseInt(catid)) == 0) { cate.deleteCategory(Integer.parseInt(catid)); url = "/java/admin/ql-category.jsp"; } else { out.println("Khong the xoa danh muc nay"); out.flush(); return; } break; } } catch (Exception e) { } response.sendRedirect(url); }
From source file:hd.controller.AddImageToProjectServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . j a v a2s .co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName; // savedFile = new File(localPath); // item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } //Init Jpa CategoryJpaController categoryJpa = new CategoryJpaController(emf); StyleJpaController styleJpa = new StyleJpaController(emf); ProjectJpaController projectJpa = new ProjectJpaController(emf); IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf); // get Object Category by categoryId int cateId = Integer.parseInt((String) params.get("ddlCategory")); Category cate = categoryJpa.findCategory(cateId); // get Object Style by styleId int styleId = Integer.parseInt((String) params.get("ddlStyle")); Style style = styleJpa.findStyle(styleId); // get Object Project by projectId int projectId = Integer.parseInt((String) params.get("txtProjectId")); Project project = projectJpa.findProject(projectId); project.setStatus(Constant.STATUS_WAIT); projectJpa.edit(project); //Get param String title = (String) params.get("title"); String description = (String) params.get("description"); String url = "images/" + fileName; //Init IdeabookPhoto IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project); photoJpa.create(photo); url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId; //System HDSystem system = new HDSystem(); system.setNotificationProject(request); response.sendRedirect(url); } } catch (Exception e) { log("Error at AddImageToProjectServlet: " + e.getMessage()); } finally { out.close(); } }
From source file:com.sharksharding.util.web.http.QueryViewServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* ? *//*from w w w. j av a2s.c o m*/ request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); /* Ioc */ WebApplicationContext context = WebApplicationContextUtils .getWebApplicationContext(request.getSession().getServletContext()); ShardRule shardRule = (ShardRule) context.getBean("shardRule"); JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate"); if (null != shardRule) { byte[] viewData = null; byte[] responseData = null; /* 1???2??? */ final String TYPE = request.getParameter("type"); if (null == TYPE) { viewData = initView(PATH + "index.html"); if (null != viewData) { write(response, viewData); } } else { switch (Integer.parseInt(TYPE)) { case 1: String page = request.getParameter("page"); if (page.equals("index")) { viewData = initView(PATH + "index.html"); } else if (page.equals("query")) { viewData = initView(PATH + "query.html"); } if (null != viewData) { write(response, viewData); } break; case 2: final String SQL = request.getParameter("sql"); if (null != SQL && 0 < SQL.trim().length()) { JSONObject jsonObj = new JSONObject(); ExecuteSql exeSql = new ExecuteSql(jdbcTemplate); try { Map<String, Object> datas = exeSql.queryData(SQL); if (!datas.isEmpty()) { StringBuffer strBuffer = new StringBuffer(); Set<String> keys = datas.keySet(); for (String key : keys) { strBuffer.append(datas.get(key) + ","); } jsonObj.put("sqlResult", strBuffer.toString()); responseData = jsonObj.toJSONString().getBytes(); } } catch (Exception e) { Writer write = new StringWriter(); e.printStackTrace(new PrintWriter(write)); jsonObj.put("error", write.toString()); responseData = jsonObj.toString().getBytes("utf-8"); } } else { responseData = GetIndexData.getData(shardRule).getBytes("utf-8"); } if (null != responseData) { write(response, responseData); } } } } }
From source file:com.matrimony.controller.ProfileController.java
@RequestMapping(value = "shortUserProfile", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ResponseBody// w w w . j a va2 s . com public String getInfoUserByUserId(HttpServletRequest request, HttpServletResponse response, String id) { System.out.println("Tim id: " + id); try { request.setCharacterEncoding("UTF8"); response.setCharacterEncoding("UTF8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } User user = UserDAO.findById(id); ShortUserProfile sortUserProfile = new ShortUserProfile(); sortUserProfile.setAvatar(user.getAvatarPhoto()); sortUserProfile.setName(user.getName()); sortUserProfile.setUsername(user.getUsername()); String json = Global.gson.toJson(sortUserProfile); return json; }