setCharacterEncoding()源码实例Demo

javax.servlet.http.HttpServletResponse#setCharacterEncoding()源码实例Demo

下面列出了javax.servlet.http.HttpServletResponse#setCharacterEncoding() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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();
        }
    };
}
 
源代码2 项目: seed   文件: WeixinHelperController.java
/**
 * 获取微信二维码图片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();
}
 
源代码3 项目: olat   文件: ExcelMediaResource.java
/**
*/
  @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");
  }
 
源代码4 项目: Tomcat8-Source-Read   文件: TestRequest.java
/**
 * 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]);
        }
    }
}
 
源代码5 项目: java-docs-samples   文件: ProjectionServlet.java
@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);
}
 
@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);
	}
}
 
源代码7 项目: uflo   文件: UfloServlet.java
@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);				
	}
}
 
源代码8 项目: Project   文件: CityServlet.java
@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);


}
 
源代码9 项目: bot-sdk-java   文件: TaxAction.java
/**
 * 重写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());
    }
}
 
源代码10 项目: mall-tiny   文件: RestfulAccessDeniedHandler.java
@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();
}
 
源代码11 项目: OnlineFriend   文件: HandleShowLoginedMember.java
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);
}
 
源代码12 项目: pre   文件: SecurityUtil.java
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();
}
 
源代码13 项目: tomcatsrc   文件: TestAbstractAjpProcessor.java
@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');
    }
}
 
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>");
	}
}
 
源代码15 项目: gocd   文件: SparkPreFilter.java
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.");
}
 
源代码16 项目: jeewx   文件: CkeUploadController.java
/**
    * 上传附件
    * @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";
	
}
 
@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);
	}
}
 
@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);
	}
}
 
源代码19 项目: BotLibre   文件: TrainingServlet.java
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");
}
 
源代码20 项目: universal-resolver   文件: PropertiesServlet.java
@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);
}