jsp 解决乱码问题

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="form1" action="register" method="post">
    用户名<input type="text" name="uname">
    密码<input type="password" name="pwd">
     城市:<select name="city">
        <optgroup label="城市">
        <option value="北京">北京</option>
        <option value="2">上海</option>
        <option value="3">深圳</option>
        <option value="4">广州</option>
        <option value="5">西安</option>
    </optgroup>
    <input type="submit"  value="提交">
</form>
</body>
<%

request.setCharacterEncoding ("utf-8");
response.setCharacterEncoding("utf-8");//放到最上面
    if (request.getParameter("uname")==null) {
        out.println("您没有输入姓名");
    }else{
        out.println(request.getCharacterEncoding()+"encoding");
        response.setHeader("contentType", "text/html; charset=UTF-8");
        out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
        //out.println("您输入的姓名为:"+codeToString(request.getParameter("uname")));
        out.println("您输入的姓名为:"+request.getParameter("uname"));
    }
%>
<%--   
    <% %><%! %>是有区别的,在jsp中,<% %>用于写java代码,<%! %>用于声明方法和变量,你上面的那两个都是方法,需要用<%! %>        

    p页面会翻译成.java文件,<%! %>用于声明方法和变量,会翻译到public void _jspService方法的外面,供全局使用,
    <% %>里面包含的所有内容都会翻译public void _jspService这个方法中。
            如果在jsp页面中写方法,不定义为全局方法的话,就会出现方法中写入方法,当然会报错啦!

--%>
<%!
    public String codeToString(String str) {//中文编码转换
        String s=str;
        try{
            byte tempB[]=s.getBytes("utf-8");
            s=new String (tempB,"utf-8");
            return s;
        }catch (Exception e){
            return s;
        }
    }
%>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值