首页 > 代码库 > 初识JavaBean、以及解决JavaBean中文乱码问题

初识JavaBean、以及解决JavaBean中文乱码问题

目的:

1.创建一个表单在index.jsp页面中,如图:

技术分享

代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="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>我自己的主页</title>
</head>
<body>

<form action="deal.jsp" method="post" name="student">
姓名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
地址:<input type="text" name="address"><br>
	 <input type="submit" name="submit" value="http://www.mamicode.com/确认"> 
	 </form>
</body>
</html>

  

2.输入姓名、年龄、地址,在deal.jsp页面中通过表格表现出来,如图:

技术分享

代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="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>
<jsp:useBean id="student" class="hello.Student"></jsp:useBean>
<jsp:useBean id="charset" class="hello.CharSet"></jsp:useBean>
<jsp:setProperty property="*" name="student"/>
<table width="200" height="50" border="1" align="center">
<tr> <td width=50%>姓名:</td> <td><%=charset.toString(student.getName())%></td></tr>
<tr> <td width=50%>年龄:</td> <td><%=charset.toString(student.getAge())%></td></tr>
<tr> <td width=50%>地址:</td> <td><%=charset.toString(student.getAddress())%></td> </tr>
</table>
</body>
</html>

  

3.建立Studentl类,遵循JavaBean规则,代码如下:

package hello;

public class Student {
	private String name;
	private String age;
	private String address;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Student() {
		super();
	}

}

  4.建立字符处理类CharSet用来解决中文乱码,同样必须遵循JavaBean规则,代码如下:

package hello;

import java.io.UnsupportedEncodingException;

public class CharSet {
	public CharSet() {
	}

	public String toString(String str){
		String message="";
		if(str!=null && !"".equals(str)){
			try {
				message = new String(str.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return message;
	}
}

5.将项目加入Tomcat服务器并启动,成功解决了中文乱码;

初识JavaBean、以及解决JavaBean中文乱码问题