Java Code Examples for javax.servlet.http.HttpServletRequest.setCharacterEncoding()

The following are Jave code examples for showing how to use setCharacterEncoding() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: EasyController   File: ActionDispatcherFilter.java   View Source Code Vote up 9 votes
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    request.setCharacterEncoding(encoding);
    response.setCharacterEncoding(encoding);

    String target = request.getRequestURI();
    if (contextPathLength != 0) {
        target = target.substring(contextPathLength);
    }

    boolean handle = actionHandler.handle(target, request, response);

    if (!handle) {// 没有处理则放行
        chain.doFilter(request, response);
    }
}
 
Example 2
Project: Registration   File: UserServlet.java   View Source Code Vote up 6 votes
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
	response.setContentType("text/html;charset=UTF-8");
	String method = request.getParameter("method");
	if ("check".equals(method)) {
		toCehck(request, response);
	}
	if ("query".equals(method)) {
		toGetAll(request, response);
	}
	if ("nosignin".equals(method)) {
		toGetNoSignin(request, response);
	}
}
 
Example 3
Project: GameProject-V1.0Beta   File: AdminLogoutServlet.java   View Source Code Vote up 6 votes
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	// TODO Auto-generated method stub
	request.setCharacterEncoding("UTF-8");
   	response.setContentType("text/html;charset=utf-8;");
   	
   	String adminLogout = request.getParameter("adminLogout");
   	JSONObject js = new JSONObject();
   	
   	if(null != adminLogout && "adminLogout".equals(adminLogout)) {
   		if(null != request.getSession().getAttribute("loginedAdmin"))
   			request.getSession().removeAttribute("loginedAdmin");
   		
   		js.put("logout", "success");
   		response.getWriter().print(js);
   	} else {
   		js.put("logout", "fail");
   		response.getWriter().print(js);
   	}
   	
}
 
Example 4
Project: SimpleController   File: RequestDispatcher.java   View Source Code Vote up 6 votes
public void dispatch(ControllerContext controllerContext)
        throws ServletException, IOException, NoResourceException {
    HttpServletRequest request=controllerContext.getRequest();
    HttpServletResponse response=controllerContext.getResponse();
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    String URI=request.getRequestURI();
    System.out.println(URI);
    String actionString=URI.substring(URI.lastIndexOf("/")+1, URI.indexOf("."));
    System.out.println(actionString);
    ActionDescriptor matchedActionDescriptor = actionConfiguration.findMatchedAction(actionString);
    controllerContext.setActionDescriptor(matchedActionDescriptor);
    String resultString="";
    if(matchedActionDescriptor ==null){//didn't find this action in configuration file
        throw new NoResourceException("matched ActionDescriptor is null.");
    }else {
        resultString = useProxy(controllerContext);
    }
    if(controllerContext.getResultDescriptor()==null)
        controllerContext.setResultDescriptor(resultString);
}
 
Example 5
Project: apache-tomcat-7.0.73-with-comment   File: TestRequest.java   View Source Code Vote up 6 votes
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");

    if (req.getRequestURI().endsWith("parseParametersBeforeParseParts")) {
        req.getParameterNames();
    }

    req.getPart("part");

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");

    resp.getWriter().println("Part " + req.getParameter("part"));
}
 
Example 6
Project: GameProject-V1.0Beta   File: GameUserLogoutServlet.java   View Source Code Vote up 6 votes
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	// TODO Auto-generated method stub
	request.setCharacterEncoding("UTF-8");
   	response.setContentType("text/html;charset=utf-8;");
   	
   	String gameUserLogout = request.getParameter("gameUserLogout");
   	JSONObject js = new JSONObject();
   	
   	if(null != gameUserLogout && "gameUserLogout".equals(gameUserLogout)) {
   		if(null != request.getSession().getAttribute("loginedGameUser"))
   			request.getSession().removeAttribute("loginedGameUser");
   		
   		js.put("logout", "success");
   		response.getWriter().print(js);
   	} else {
   		js.put("logout", "fail");
   		response.getWriter().print(js);
   	}
   	
}
 
Example 7
Project: ImageClassify   File: AdminInterceptor.java   View Source Code Vote up 6 votes
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8"); 
	HttpSession session = request.getSession();
	if (!"".equals(session.getAttribute(Constant.USERNAME))&& session.getAttribute(Constant.USERNAME)!=null && !"".equals(session.getAttribute(Constant.TOKEN)) && session.getAttribute(Constant.TOKEN)!=null ) {
		return true; 
	} else {
		PrintWriter out;  
		out = response.getWriter();
		String json;
		Gson gson = new Gson();
		Message<String> message = new Message<String>("-200","管理员未登录,请重新登录","");//初始化message对象
           json = gson.toJson(message, Message.class); //使用gson将Message对象转化为字符串
		out.print(json);  
		return false;
	}
		
}
 
Example 8
Project: TestDemo1-github   File: searchAjax.java   View Source Code Vote up 6 votes
@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//�����ַ�����ʽ
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		//���Ȼ�ÿͻ��˷����������(keyword)
		String keyword1 = req.getParameter("keyword");
		String keyword = Escape.unescape(keyword1);
		//��ùؼ���֮����д��?�õ��������
		List<String> listData = getData(keyword);
		
//		System.out.println(JSONArray.fromObject(listData));
//		JSONArray.fromObject(listData);
		//����json��ʽ
		resp.getWriter().write(JSONArray.fromObject(listData).toString());
	}
 
Example 9
Project: PCloud_Server_v3   File: BaseServletAction.java   View Source Code Vote up 6 votes
/**
 * 请求委托
 * @param request
 * @param response
 * @param httpServlet
 */
public void entrust(HttpServletRequest request, HttpServletResponse response, HttpServlet httpServlet){
	method = request.getMethod();
	this.request = request;
	response.setCharacterEncoding(encode);
	
	//设置POST请求的字符编码
	if(method.equals("POST")){
		try {
			request.setCharacterEncoding(encode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	//设置Content-Type
	response.setHeader("Content-Type", "text/html;charset=" + encode);
	
	execute(request, response, httpServlet);
}
 
Example 10
Project: ImageClassify   File: AdminController.java   View Source Code Vote up 5 votes
/**
 * 历史导出列表
 * 
 * @param response
 * @param request
 * @throws IOException
 */
@RequestMapping(value = "/admin/getdownloadimageshistory", method = RequestMethod.POST)
public void getDownloadImagesHistory(HttpServletResponse response, @RequestParam("start") String start,
		@RequestParam("page_num") String page_size, HttpServletRequest request) throws IOException {

	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8"); // 设置响应responce编码为utf-8
	PrintWriter out = response.getWriter();
	SplitObject<ExportHistoryLabel> splitObject = new SplitObject<ExportHistoryLabel>();
	String json;
	Gson gson = new Gson();
	// 获取所有历史列表
	List<ExportHistoryLabel> exportHistoryLabels = exportService.gExportHistoryLabels(Integer.parseInt(start),
			Integer.parseInt(page_size));

	// 获取历史列表数量
	int num = new Long(exportService.exportHistoryLabelsNum()).intValue();

	splitObject.setList(exportHistoryLabels);
	if (num % Constant.DEVI_NUM == 0) {
		splitObject.setPages_num(num / Constant.DEVI_NUM);
	} else {
		splitObject.setPages_num((num / Constant.DEVI_NUM + 1));
	}
	Message<SplitObject<ExportHistoryLabel>> message = new Message<SplitObject<ExportHistoryLabel>>("200", "",
			splitObject);// 初始化message对象
	json = gson.toJson(message, Message.class); // 使用gson将Message对象转化为字符串
	out.print(json);
}
 
Example 11
Project: dswork   File: CharacterEncodingFilter.java   View Source Code Vote up 5 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
	HttpServletRequest req = (HttpServletRequest) request;
	HttpServletResponse res = (HttpServletResponse) response;
	req.setCharacterEncoding(this.encoding);
	if (this.forceEncoding) {
		res.setCharacterEncoding(this.encoding);
	}
	chain.doFilter(req, res);
}
 
Example 12
Project: Webhook_server   File: ApiServlet.java   View Source Code Vote up 5 votes
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setCharacterEncoding("UTF-8");
    req.setCharacterEncoding("UTF-8");
    getHeadersInfo(req);
    routeByHeader(req);
    String retJson = "hello i'm running... server time: " + TimeUtil.msec2date(System.currentTimeMillis()) + " ,version " + Params.versionName;
    PrintWriter writer = resp.getWriter();
    writer.write(retJson);
    writer.flush();
    writer.close();
}
 
Example 13
Project: java-course   File: HomepageServlet.java   View Source Code Vote up 5 votes
/**
 * Process current get or post request.
 * 
 * @param req Http servlet request.
 * @param resp Http servlet response.
 * @throws ServletException If the request could not be handled.
 * @throws IOException If an input or output error is detected.
 */
private void processAction(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    req.getSession().setAttribute("register", Boolean.FALSE);
    if (req.getParameter("action") != null) {
        checkLoginParameters(req);
    } else {
        req.getSession().setAttribute("error", false);
    }

    List<BlogUser> users = DAOProvider.getDAO().getAllUsers();
    req.setAttribute("users", users);
    req.getRequestDispatcher("/WEB-INF/pages/Index.jsp").forward(req, resp);
}
 
Example 14
Project: GameProject-V1.0Beta   File: GameUserRegistServlet.java   View Source Code Vote up 5 votes
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// TODO Auto-generated method stub
	//设置request和response的编码格式
	request.setCharacterEncoding("UTF-8");
	response.setContentType("text/html;charset=utf-8;");
			
	String userName = request.getParameter("username");
	String userId = request.getParameter("id");
	String userPhone = request.getParameter("phone");
	String userEmail = request.getParameter("email");
	String userPassword = request.getParameter("pwd");
	String serverId = request.getParameter("area");
	
	System.out.println("{" + userName + ";"+ userId + ";"+ userPhone +";" + userEmail + ";"+ serverId +"}");
	
	// 得到验证码输入框中的验证码的值
	String chkCode = request.getParameter("chkcode");
	
	// 获得session对象
	HttpSession session = request.getSession();

	// 得到session中验证码的值
	String tmpCode = (String) session.getAttribute("checkcode");

	System.out.println("老子的注册servlet被调戏了QAQ");
	
	//验证码的比较结果
	boolean flag = tmpCode.equals(new String(chkCode).toLowerCase());
	
	if(!flag){
		response.sendRedirect("/GameProject/jsp/regist.jsp?time=" + new java.util.Date().getTime());
	}
	
	//注册失败,跳转到registFailed页面
	boolean flag1 = guDao.gameUserRegist(userName, userId, userPhone, userEmail, userPassword, serverId);
	if(!flag1) {
		response.sendRedirect("/GameProject/userjsp/registFailed.jsp");
	}
	
	//注册成功,利用session代理该对象的数据
	GameUser gu = new GameUser();
	gu.setServerId(serverId);
	gu.setUserName(userName);
	gu.setUserPassword(userPassword);
	
	if(null == session.getAttribute("loginedGameUser") &&
			null == session.getAttribute("autoLogin"))//session为空时,说明时第一次登陆,将数据加入session代理
		session.setAttribute("loginedGameUser", gu);//session代理该gameuser对象
		session.setAttribute("autoLogin", "no");//注册成功默认是不自动登录
	
	//注册成功,跳转到registSuccess页面
	response.sendRedirect("/GameProject/userjsp/registSuccess.jsp");
}
 
Example 15
Project: DrugStoreManagement   File: ClearServlet.java   View Source Code Vote up 5 votes
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
	response.setContentType("text/html;charset=UTF-8");
	request.setCharacterEncoding("UTF-8");
	HttpSession s = request.getSession();
	s.removeValue("user_id");   
       s.invalidate();   
	response.sendRedirect("login.jsp");
}
 
Example 16
Project: GameProject-V1.0Beta   File: CheckAdminIsExistServlet.java   View Source Code Vote up 5 votes
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	// TODO Auto-generated method stub
	request.setCharacterEncoding("UTF-8");
   	response.setContentType("text/html;charset=utf-8;");
   	
   	String adminName = request.getParameter("adminName");
   	String adminPassword = request.getParameter("adminPassword");
   	String pwd = null;
   	JSONObject js = new JSONObject();
   	
   	HttpSession session = request.getSession();
   	
   	pwd = new AdminDao().getPasswordByQueryAdmin(adminName);
   	if(null != pwd && pwd.equals(adminPassword)) {
   		
		js.put("adminIsExist" , "exist");
		
		Admin admin = new Admin();
		admin.setAdminName(adminName);
		admin.setAdminPassword(pwd);
	if(null == session.getAttribute("loginedAdmin"))
		session.setAttribute("loginedAdmin", admin);
		response.getWriter().print(js);
   	} else if(null != pwd && !pwd.equals(adminPassword)) {
   		js.put("adminIsExist" , "existButpwdErr");
   		response.getWriter().print(js);
   	} else if(null == pwd) {
   		js.put("adminIsExist" , "no-exist");
   		response.getWriter().print(js);
   	} 
}
 
Example 17
Project: hotelbook-JavaWeb   File: AuthInfoServlet.java   View Source Code Vote up 4 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        int page = Integer.parseInt(request.getParameter("page")); // 当前页码
        int limit = Integer.parseInt(request.getParameter("limit")); // 每页的数据量
        int make = Integer.parseInt(request.getParameter("make"));

        // 调用service
        AuthService service = new AuthServiceImpl();

        // 默认输出信息
        String code = "0"; //状态码
        String msg = "数据查询正常"; //状态信息
        String count = ""; //数据总数
        ArrayList<AuthInfo> list = new ArrayList<>(); //数据内容

        //单个全局属性
        int authId;                  //权限ID
        String authItem = "";        //权限名称
        String isRead;               //可读
        String isWrite;              //可写
        String isChange;             //可改
        String isDelete;             //可删
        AuthInfo authInfo = null;

        try {

            // 状态标志 make 0重载 1新增 2修改 3搜索 4删除
            if (make == 2) {
                authId = Integer.parseInt(request.getParameter("authId"));
                authItem = request.getParameter("authItem");
                isRead = request.getParameter("isRead");
                isWrite = request.getParameter("isWrite");
                isChange = request.getParameter("isChange");
                isDelete = request.getParameter("isDelete");
                authInfo = new AuthInfo(authId, authItem, isRead, isWrite, isChange, isDelete);
            } else if (make == 3) {
                authItem = request.getParameter("authItem");
            }

            switch (make) {
                case 2:
                    service.updateAuthInfo(authInfo);
                    break;
                case 3:
                    authInfo = service.query(authItem);
                    list.clear();
                    list.add(authInfo);
                    break;
            }
            if (make != 3) {
                list = service.query(page, limit);
                count = String.valueOf(service.queryAuthInfoNum());
            } else {
                if (authInfo.getAuthId() == 0) {
                    count = "0";
                } else {
                    count = "1";
                }
            }
        } catch (SQLException e) {
            code = "1";
            msg = "数据查询出现异常";
            e.printStackTrace();
        } finally {
            PojotoGson pojotoGson = new PojotoGson(code, msg, count, list);
            Gson gson = new Gson();
            out.print(gson.toJson(pojotoGson));
        }
    }
 
Example 18
Project: LojaDeInstrumentosMusicais   File: CadastrarClienteServlet.java   View Source Code Vote up 4 votes
/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String nome = request.getParameter("name").toLowerCase();
    String sobrenome = request.getParameter("sobrenome").toLowerCase();
    String sexo = request.getParameter("sexo");
    String dataNasc = request.getParameter("dataNasc");
    System.out.println(request.getParameter("dataNasc"));
    String cpf = request.getParameter("cpf");
    String rg = request.getParameter("rg");
    String tel1 = request.getParameter("tel1");
    String tel2 = request.getParameter("tel2");
    String email = request.getParameter("email").toLowerCase();
    String numCasa = request.getParameter("numCasa");
    String complemento = request.getParameter("complemento").toLowerCase();
    String end = request.getParameter("endereco").toLowerCase();
    String cidade = request.getParameter("cidade").toLowerCase();
    String cep = request.getParameter("cep");
    String estado = request.getParameter("estados");
    String empresa = request.getParameter("empresa");
    
    Cliente novoCliente = new Cliente();
    Cliente clienteexiste = new Cliente();
    ServicoCliente sc = new ServicoCliente();
    HttpSession sessao = request.getSession();
    
    try {
        clienteexiste = sc.obterClientePorCpf(cpf, Integer.parseInt(empresa));
    } catch (Exception e) {
    }
    
    if(clienteexiste.getCpf() != null){
        sessao.setAttribute("cpfexiste", "CPF já cadastrado!");
    }else{
        int s = Integer.parseInt(sexo);
        if(s == 1){
            novoCliente.setSexo("Masculino");  
        }else{
            novoCliente.setSexo("Feminino");
        }
     
    
        novoCliente.setNome(nome);
        novoCliente.setSobrenome(sobrenome);
        novoCliente.setCpf(cpf);
        novoCliente.setIdade(dataNasc);
        novoCliente.setRg(rg);
        novoCliente.setTelefone(tel1);
        novoCliente.setTelefone2(tel2);
        novoCliente.setEmail(email);
        novoCliente.setNumero(numCasa);
        novoCliente.setEndereco(end);
        novoCliente.setComplemento(complemento);
        novoCliente.setCidade(cidade);
        novoCliente.setCep(cep);
        novoCliente.setEstado(estado);
        novoCliente.setEmpresa(Integer.parseInt(empresa));
    
        ClienteDAO clientedao = new ClienteDAO();
        clientedao.inserirCliente(novoCliente);
    
        sessao.removeAttribute("cpfexiste");
        sessao.setAttribute("cliente", novoCliente);
    }
     
     
    
    response.sendRedirect(request.getContextPath() + "/cadastrar-cliente");
    
}
 
Example 19
Project: tomcat7   File: TestApplicationHttpRequest.java   View Source Code Vote up 4 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter w = resp.getWriter();
    Map<String,String[]> actual = req.getParameterMap();

    boolean ok = true;
    for (Entry<String,String[]> entry : actual.entrySet()) {
        String[] expectedValue = expected.get(entry.getKey());
        if (expectedValue == null ||
                expectedValue.length != entry.getValue().length) {
            ok = false;
            break;
        }
        for (int i = 0; i < expectedValue.length; i++) {
            if (!expectedValue[i].equals(entry.getValue()[i])) {
                ok = false;
                break;
            }
        }
        if (!ok) {
            break;
        }
    }

    if (ok) {
        w.print("OK");
        return;
    }
    boolean firstParam = true;
    for (Entry<String,String[]> param : actual.entrySet()) {
        if (firstParam) {
            firstParam = false;
        } else {
            w.print(';');
        }
        w.print(param.getKey());
        w.print(':');
        boolean firstValue = true;
        for (String value : param.getValue()) {
            if (firstValue) {
                firstValue = false;
            } else {
                w.print(',');
            }
            w.print('(');
            w.print(value);
            w.print(')');
        }
    }
}
 
Example 20
Project: DrugStoreManagement   File: PersonnelFileUpload.java   View Source Code Vote up 4 votes
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
	// TODO Auto-generated method stub
	response.setContentType("text/html;charset=UTF-8");
	response.setCharacterEncoding("UTF-8");
	request.setCharacterEncoding("UTF-8");
	//HttpSession session = request.getSession();
	//String ID = (String)session.getAttribute("user_id");
	String ID = "00000001";
	if(!ID.startsWith("0") && !ID.startsWith("2"))
	{
		request.getRequestDispatcher("ErrorJsp.jsp").forward(request, response);
		return;
	}
	String method = null;
	FileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload sfu = new ServletFileUpload(factory);
	List<FileItem> list = null;
	try
	{
		list = sfu.parseRequest(request);
		for(FileItem fileItem : list)
		{
			if(fileItem.isFormField())
			{
				if("method".equals(fileItem.getFieldName()))
				{
					method = fileItem.getString();
					break;
				}
			}
		}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	if("addStoreManager".equals(method))
	{
		addStoreManager(list);
	}
	else if("addWarehouseManager".equals(method))
	{
		addWarehouseManager(list);
	}
	else if("addSalesman".equals(method))
	{
		addSalesman(list);
	}
	else if("modifyStoreManager".endsWith(method))
	{
		modifyStoreManager(list);
	}
	request.getRequestDispatcher("/personnel/personnel.jsp").forward(request,response);
}