javaweb URLEncoder 和 URLDecoder 用法学习

URLEncoder.encode(String s, String enc) 
使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式 

URLDecoder.decode(String s, String enc) 
使用指定的编码机制对 application/x-www-form-urlencoded 字符串解码。

这两个都主要针对于界面交互时,中文乱码的情况。

URLEncoder.encode用于发送请求时进行编码,URLDecoder.decoder用于接收时进行解码,这样能防止中文乱码的情况。

例如写一个自动登录界面(只有部分代码):

if(Constant.IS_AUTO_LOGIN.equals(request.getParameter("autologin"))){
				//创建cookie,注意中文
//				Cookie cookie = new Cookie("autologin",username+"-"+password);
				Cookie cookie = new Cookie("autologin",URLEncoder.encode(username,"utf-8")+"-"+password);
				cookie.setMaxAge(3600);
				cookie.setPath(request.getContextPath()+"/");
				
				response.addCookie(cookie);
				
			}
			
			//判断是否勾选了记住用户名 若勾选了需要将我们的用户名放入我们的cookie中 写回浏览器
			if(Constant.IS_SAVE_NAME.equals(request.getParameter("saveName"))){
				//创建cookie
				Cookie cookie = new Cookie("savename",URLEncoder.encode(username,"utf-8"));
				cookie.setMaxAge(3600);
				cookie.setPath(request.getContextPath()+"/");
				
				response.addCookie(cookie);
if(c!=null){
					String username = URLDecoder.decode(c.getValue().split("-")[0],"utf-8");//接收时用URLDecoder进行解码
//					System.out.println(username);
					String password = c.getValue().split("-")[1];
					
					//调用service
					//user = null;
					try {
						user = new UserService().login(username, password);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(user!=null){
						//将user放入session中
						request.getSession().setAttribute("user", user);
					}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值