Java Code Examples for javax.servlet.http.HttpServletResponse#setCharacterEncoding()
The following examples show how to use
javax.servlet.http.HttpServletResponse#setCharacterEncoding() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResourceServerConfiguration.java From spring-security with Apache License 2.0 | 8 votes |
@Bean public AuthenticationEntryPoint authenticationEntryPoint(){ return (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) ->{ Map<String, Object> map = new HashMap<>(); map.put("code", 401); map.put("msg", "非法访问资源,访问此资源需要完全身份验证"); map.put("path", request.getServletPath()); map.put("timestamp", System.currentTimeMillis()); response.setContentType("application/json"); response.setCharacterEncoding(CharsetUtil.UTF_8); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getOutputStream(), map); } catch (Exception e) { throw new ServletException(); } }; }
Example 2
Source File: ExcelMediaResource.java From olat with Apache License 2.0 | 6 votes |
/** */ @Override public void prepare(HttpServletResponse hres) { // anything hres.setCharacterEncoding("utf-8"); String name; if (optionalFilename == null) { long random = System.currentTimeMillis(); // needed so IE does not cache name = "file" + random; } else { name = optionalFilename; } /* * try { //String test = "aüa\u0395\u0159a\u0641bcd\u0395a\u03BA\u03C4\u03B5a\u0410\u0432\u0442b\u0159c"; String output = null; byte[] b = test.getBytes("utf-8"); * output = new String(b, "iso-8859-1"); String res = sb.toString(); //output = res; } catch (UnsupportedEncodingException e) { } */ // boolean isIE = false; // ie and konqueror and safari: true, only iso-8859-1 // hres.setHeader("Content-Disposition", "attachment; filename=" + (isIE?test:output) + ".xls"); hres.setHeader("Content-Disposition", "attachment; filename=" + name + ".xls"); hres.setHeader("Content-Description", "OLAT Generated data"); }
Example 3
Source File: WeixinHelperController.java From seed with Apache License 2.0 | 6 votes |
/** * 获取微信二维码图片URL * @param type 二维码类型,0--临时二维码,1--永久二维码,2--永久字符串二维码 * @param expireSeconds 二维码临时有效的时间,单位为秒,最大不超过2592000s,即30天,不填则默认有效期为30s * @param sceneId 二维码参数场景值ID,临时二维码时为32位非0整型,永久二维码时值为1--100000 * @param sceneStr 二维码参数场景值ID,字符串形式的ID,字符串类型,长度限制为1到64,仅永久二维码支持此字段 */ @RequestMapping(value="/getQrcodeURL") public void getQrcodeURL(String appid, int type, String expireSeconds, String sceneId, String sceneStr, HttpServletResponse response) throws IOException{ if(StringUtils.isBlank(expireSeconds)){ expireSeconds = "2"; } if(StringUtils.isBlank(sceneId)){ sceneId = "2"; } String ticket = WeixinHelper.createQrcodeTicket(WeixinTokenHolder.getWeixinAccessToken(appid), type, Integer.parseInt(expireSeconds), Long.parseLong(sceneId), sceneStr); String qrcodeURL = WeixinConstants.URL_WEIXIN_GET_QRCODE.replace(WeixinConstants.URL_PLACEHOLDER_QRCODE_TICKET, ticket); response.setCharacterEncoding(SeedConstants.DEFAULT_CHARSET); response.setContentType("text/plain; charset=" + SeedConstants.DEFAULT_CHARSET); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); PrintWriter out = response.getWriter(); out.print(qrcodeURL); out.flush(); out.close(); }
Example 4
Source File: TestAbstractAjpProcessor.java From tomcatsrc with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setBufferSize(bufferSize); resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); resp.setContentLength(responseSize); PrintWriter pw = resp.getWriter(); for (int i = 0; i < responseSize; i++) { pw.append('X'); } }
Example 5
Source File: TestRequest.java From Tomcat8-Source-Read with MIT License | 5 votes |
/** * Only interested in the parameters and values for requests. * Note: echos parameters in alphabetical order. */ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Just echo the parameters and values back as plain text resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); TreeMap<String,String[]> parameters = new TreeMap<>(req.getParameterMap()); boolean first = true; for(String name: parameters.keySet()) { String[] values = req.getParameterValues(name); java.util.Arrays.sort(values); for(int i=0; i<values.length; ++i) { if(first) first = false; else out.print(","); out.print(name + "=" + values[i]); } } }
Example 6
Source File: ProjectionServlet.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); out.printf("Latest entries from guestbook: \n"); Key guestbookKey = KeyFactory.createKey("Guestbook", GUESTBOOK_ID); Query query = new Query("Greeting", guestbookKey); addGuestbookProjections(query); printGuestbookEntries(datastore, query, out); }
Example 7
Source File: AspectsDataServlet.java From document-management-software with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServiceUtil.validateSession(request); response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); // Avoid resource caching response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); List<String> aspects = RunLevel.getAspects(); PrintWriter writer = response.getWriter(); writer.write("<list>"); for (String aspect : aspects) { writer.print("<aspect>"); writer.print("<id>" + aspect + "</id>"); writer.print("<default>" + RunLevel.DEFAULT.aspectEnabled(aspect) + "</default>"); writer.print("<bulkload>" + RunLevel.BULKLOAD.aspectEnabled(aspect) + "</bulkload>"); writer.print("<devel>" + RunLevel.DEVEL.aspectEnabled(aspect) + "</devel>"); writer.print("<devel>" + RunLevel.SLAVE.aspectEnabled(aspect) + "</devel>"); writer.print("<demo>" + RunLevel.DEMO.aspectEnabled(aspect) + "</demo>"); writer.print("</aspect>"); } writer.write("</list>"); } catch (Throwable e) { log.error(e.getMessage(), e); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else throw new ServletException(e.getMessage(), e); } }
Example 8
Source File: UfloServlet.java From uflo with Apache License 2.0 | 5 votes |
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try{ String path=req.getContextPath()+URL; String uri=req.getRequestURI(); String targetUrl=uri.substring(path.length()); if(targetUrl.length()<1){ resp.sendRedirect(req.getContextPath()+"/uflo/todo"); return; } int slashPos=targetUrl.indexOf("/",1); if(slashPos>-1){ targetUrl=targetUrl.substring(0,slashPos); } ServletHandler targetHandler=handlerMap.get(targetUrl); if(targetHandler==null){ outContent(resp,"Handler ["+targetUrl+"] not exist."); return; } targetHandler.execute(req, resp); }catch(Exception ex){ Throwable e=getCause(ex); resp.setCharacterEncoding("UTF-8"); PrintWriter pw=resp.getWriter(); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String errorMsg = e.getMessage(); if(StringUtils.isBlank(errorMsg)){ errorMsg=e.getClass().getName(); } pw.write(errorMsg); pw.close(); throw new ServletException(ex); } }
Example 9
Source File: CityServlet.java From Project with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.获取前端传递过来的选中的省的值 String s1value = req.getParameter("s1value"); // 2.根据省组装市 // 如果没有数据库,将js里面的判断语句挪到这里即可; // 使用json传递数据 ArrayList<City> cities = new ArrayList<>(); if (s1value == "北京"){ cities.add(new City(1, "东城")); cities.add(new City(2, "西城")); } if (s1value == "江苏"){ cities.add(new City(1, "南京")); cities.add(new City(2, "宿迁")); cities.add(new City(3, "连云港")); cities.add(new City(4, "徐州")); } if (s1value == "上海"){ cities.add(new City(1, "黄浦")); cities.add(new City(2, "浦东")); } // 3.最后将市的数据传递给前端 String toJSONString = JSON.toJSONString(cities); System.out.println(toJSONString); resp.setCharacterEncoding("UTF-8"); resp.getWriter().print(toJSONString); }
Example 10
Source File: TaxAction.java From bot-sdk-java with Apache License 2.0 | 5 votes |
/** * 重写doPost方法,处理POST请求 * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 根据request创建Bot TaxBot bot; try { bot = new TaxBot(request); // 线下调试时,可以关闭签名验证 // bot.enableVerify(); bot.disableVerify(); // 调用bot的run方法 String responseJson = bot.run(); // 设置response的编码UTF-8 response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); // 返回response response.getWriter().append(responseJson); // 打开签名验证 // bot.enableVerify(); } catch (Exception e) { e.printStackTrace(); response.getWriter().append(e.toString()); } }
Example 11
Source File: RestfulAccessDeniedHandler.java From mall-tiny with Apache License 2.0 | 5 votes |
@Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage()))); response.getWriter().flush(); }
Example 12
Source File: HandleShowLoginedMember.java From OnlineFriend with Apache License 2.0 | 5 votes |
private void continueDoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); HttpSession session = request.getSession(true); Login loginBean = (Login) session.getAttribute("login"); String id = loginBean.getId(); MemberInform memberInformBean = new MemberInform(); request.setAttribute("loginedInform", memberInformBean); Connection connection = DbConn.getConnection(); try { PreparedStatement preparedStatement = connection.prepareStatement("select id,email,phone,message,pic from member where id=?"); preparedStatement.setString(1, id); ResultSet resultSet = preparedStatement.executeQuery(); if(resultSet.next()){ memberInformBean.setBackNews("个人信息:"); memberInformBean.setSelectOk(true); memberInformBean.setId(resultSet.getString(1)); memberInformBean.setEmail(resultSet.getString(2)); memberInformBean.setPhone(resultSet.getString(3)); memberInformBean.setMessage(resultSet.getString(4)); memberInformBean.setPic(resultSet.getString(5)); } else memberInformBean.setBackNews("未查到任何信息。。。"); preparedStatement.close(); connection.close(); } catch (Exception e) { memberInformBean.setBackNews("未查到任何信息。。。"); } RequestDispatcher dispatcher = request.getRequestDispatcher("member/index.jsp"); dispatcher.forward(request, response); }
Example 13
Source File: SecurityUtil.java From pre with GNU General Public License v3.0 | 5 votes |
public void writeJavaScript(R r, HttpServletResponse response) throws IOException { response.setStatus(200); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter printWriter = response.getWriter(); printWriter.write(JSON.toJSONString(r)); printWriter.flush(); }
Example 14
Source File: AttributeSetsDataServlet.java From document-management-software with GNU Lesser General Public License v3.0 | 4 votes |
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Session session = ServiceUtil.validateSession(request); Integer type = null; if (request.getParameter("type") != null) type = Integer.parseInt(request.getParameter("type")); response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); // Avoid resource caching response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); PrintWriter writer = response.getWriter(); writer.write("<list>"); if ("true".equals(request.getParameter("withempty"))) { writer.print("<attributeset>"); writer.print("<id></id>"); writer.print("<name> </name>"); writer.print("<readonly>false</readonly>"); writer.print("</attributeset>"); } AttributeSetDAO dao = (AttributeSetDAO) Context.get().getBean(AttributeSetDAO.class); List<AttributeSet> sets = null; if (type != null) sets = dao.findByType(type, session.getTenantId()); else sets = dao.findAll(session.getTenantId()); /* * Iterate over the collection of templates */ for (AttributeSet set : sets) { writer.print("<attributeset>"); writer.print("<id>" + set.getId() + "</id>"); writer.print("<name><![CDATA[" + set.getName() + "]]></name>"); writer.print("<description><![CDATA[" + set.getDescription() + "]]></description>"); writer.print("<readonly>" + Boolean.toString(set.getReadonly() == 1) + "</readonly>"); writer.print("<type>" + set.getType() + "</type>"); writer.print("</attributeset>"); } writer.write("</list>"); } catch (Throwable e) { log.error(e.getMessage(), e); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else throw new ServletException(e.getMessage(), e); } }
Example 15
Source File: TrainingServlet.java From BotLibre with Eclipse Public License 1.0 | 4 votes |
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PageStats.page(request); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); LoginBean loginBean = (LoginBean)request.getSession().getAttribute("loginBean"); if (loginBean == null) { response.sendRedirect("index.jsp"); return; } BotBean botBean = loginBean.getBotBean(); TrainingBean trainingBean = loginBean.getBean(TrainingBean.class); String newResponse = (String)request.getParameter("newResponse"); String addDefaultResponse = (String)request.getParameter("addDefaultResponse"); String removeDefaultResponse = (String)request.getParameter("removeDefaultResponse"); String selectedResponse = (String)request.getParameter("defaultResponses"); String newGreeting = (String)request.getParameter("newGreeting"); String addGreeting = (String)request.getParameter("addGreeting"); String removeGreeting = (String)request.getParameter("removeGreeting"); String selectedGreeting = (String)request.getParameter("greetings"); String question = (String)request.getParameter("question"); String questionResponse = (String)request.getParameter("response"); String addResponse = (String)request.getParameter("addResponse"); try { String postToken = (String)request.getParameter("postToken"); loginBean.verifyPostToken(postToken); String instance = (String)request.getParameter("instance"); if (instance != null) { if (botBean.getInstance() == null || !String.valueOf(botBean.getInstanceId()).equals(instance)) { botBean.validateInstance(instance); } } if (!botBean.isConnected()) { response.sendRedirect("training.jsp"); return; } botBean.checkAdmin(); if (addDefaultResponse != null) { trainingBean.addDefaultResponses(newResponse); } else if (removeDefaultResponse != null) { trainingBean.removeDefaultResponses(selectedResponse); } else if (addResponse != null) { trainingBean.addQuestionResponses(question, questionResponse); } else if (addGreeting != null) { trainingBean.addGreeting(newGreeting); } else if (removeGreeting != null) { trainingBean.removeGreeting(selectedGreeting); } } catch (Throwable failed) { loginBean.error(failed); } response.sendRedirect("training.jsp"); }
Example 16
Source File: TokenFiltersDataServlet.java From document-management-software with GNU Lesser General Public License v3.0 | 4 votes |
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServiceUtil.validateSession(request); response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); // Avoid resource caching response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); String filter = request.getParameter("filter"); ContextProperties config = Context.get().getProperties(); PrintWriter writer = response.getWriter(); writer.print("<list>"); if (StringUtils.isNotEmpty(filter)) { // We have to iterate over the configs of a specific filter String prefix = "index.tokenfilter." + filter + "."; Map<String, String> settings = config.getProperties(prefix); for (String setting : settings.keySet()) { if (setting.equals("position")) continue; writer.print("<filter>"); writer.print("<name><![CDATA[" + setting + "]]></name>"); writer.print("<value><![CDATA[" + settings.get(setting) + "]]></value>"); writer.print("</filter>"); } } else { // We have to iterate over the filters List<String> filters = FilteredAnalyzer.getTokenFilterNames(false); for (String filterName : filters) { writer.print("<filter>"); writer.print("<name><![CDATA[" + filterName + "]]></name>"); if ("enabled".equals(config.getProperty("index.tokenfilter." + filterName))) writer.print("<eenabled>0</eenabled>"); else writer.print("<eenabled>2</eenabled>"); writer.print("</filter>"); } } writer.print("</list>"); } catch (Throwable e) { log.error(e.getMessage(), e); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else throw new ServletException(e.getMessage(), e); } }
Example 17
Source File: CkeUploadController.java From jeewx with Apache License 2.0 | 4 votes |
/** * 上传附件 * @param request * @param response * @return */ @RequestMapping(params = "upload") public String upload(HttpServletRequest request, HttpServletResponse response) { // 设置字符编码为UTF-8, 这样支持汉字显示 response.setCharacterEncoding("UTF-8"); // MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; // String day = DateUtils.date2SStr(); // String path = mRequest.getSession().getServletContext() .getRealPath("/"); String base_save_path = "upload" + sep + day + sep; // String url_base_path = "upload/" + day + "/"; // String save_path = path + base_save_path; File save_folder = new File(save_path); if (!save_folder.exists()) { save_folder.mkdirs(); } // UUID uuid = UUID.randomUUID(); String callback = request.getParameter("CKEditorFuncNum"); String save_script = "<script type=\"text/javascript\">"; // Map<String, MultipartFile> fileMap = mRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile mf = entity.getValue();// 获取上传文件对象 // try { // 取原文件名 String file_name = mf.getOriginalFilename().trim(); // file_name = file_name.toLowerCase(); String save_file_name = uuid.toString().replaceAll("-", "") + file_name.substring(file_name.lastIndexOf(".")); // String savePath = save_path + save_file_name; // save_script += "window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + url_base_path + save_file_name + "','');"; // File savefile = new File(savePath); // FileCopyUtils.copy(mf.getBytes(), savefile); // savefile = null; } catch (Exception e) { logger.error(ExceptionUtil.getExceptionMessage(e)); } } save_script += "</script>"; // request.setAttribute("list", save_script); // return "weixin/guanjia/api/string"; }
Example 18
Source File: SparkPreFilter.java From gocd with Apache License 2.0 | 4 votes |
private void render404(HttpServletResponse response) throws IOException { response.setStatus(404); response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); response.getOutputStream().println("The url you are trying to reach appears to be incorrect."); }
Example 19
Source File: LibrarianReturnBook.java From Online-Library-System with GNU General Public License v2.0 | 4 votes |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); int bookId = Integer.parseInt(request.getParameter("bookId")); HttpSession session = request.getSession(); Librarian librarian = (Librarian) session.getAttribute("librarianEntity"); BorrowItemDAO d = new BorrowItemDAO(); // 获取读者信息 Reader reader = d.getReaderInBorrowItemByBookID(bookId); if (reader == null) { out.print("<script language='javascript'>" + "alert('No Reader borrowed this book or reader information are loss!');" + "window.location.href='librarianReturnBook.jsp';" + "</script>"); } BookDAO bDAO = new BookDAO(); // 获取book信息 Book book = bDAO.searchByID(bookId); if (book != null) { request.setAttribute("borrowerEntity", reader); request.setAttribute("bookEntity", book); request.getRequestDispatcher("librarianReturnBook.jsp").forward(request, response); // if (dao.returnBook(bookId, librarian.getId())) { // request.setAttribute("borrowerEntity", reader); // request.setAttribute("borrowerEntity", book); // request.getRequestDispatcher("librarianReturnBook.jsp").forward(request, // response); // } else { // out.print("<script language='javascript'>" + "alert('This Book is // not borrowed!');" // + "window.location.href='librarianReturnBook.jsp';" + // "</script>"); // } } else { out.print("<script language='javascript'>" + "alert('Error Book ID! There is no book ID= '" + bookId + "!);" + "window.location.href='librarianReturnBook.jsp';" + "</script>"); } }
Example 20
Source File: PropertiesServlet.java From universal-resolver with Apache License 2.0 | 3 votes |
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // read request request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); if (log.isInfoEnabled()) log.info("Incoming request."); // get properties Map<String, Object> properties; String propertiesString; try { properties = InitServlet.getDriver() == null ? null : InitServlet.getDriver().properties(); propertiesString = properties == null ? null : objectMapper.writeValueAsString(properties); } catch (Exception ex) { if (log.isWarnEnabled()) log.warn("Properties problem: " + ex.getMessage(), ex); sendResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, "Properties problem: " + ex.getMessage()); return; } if (log.isInfoEnabled()) log.info("Properties: " + properties); // no properties? if (properties == null) { sendResponse(response, HttpServletResponse.SC_NOT_FOUND, null, "No properties."); return; } // write properties sendResponse(response, HttpServletResponse.SC_OK, Driver.PROPERTIES_MIME_TYPE, propertiesString); }