创建两个jsp页面:reg.jsp 和 request.jsp
reg.jsp:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="java.text.*" %>
<%
String path = request.getContextPath();
%>
<!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>
<h1>用户注册</h1>
<form action="request.jsp" name="loginForm" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>爱好:</td>
<td>
<input type="checkbox" name="favorite" value="read"/>读书
<input type="checkbox" name="favorite" value="yujia"/>瑜伽
<input type="checkbox" name="favorite" value="fadai"/>发呆
</td>
</tr>
<tr>
<td>显示:</td>
<td colspan="2"><input type="submit" name="提交"/></td>
</tr>
</table>
</form>
</body>
</html>
request.jsp:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"
%>
<%@ page import="java.text.*" %>
<%
String path = request.getContextPath();
%>
<!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>
<h1>request内置对象</h1>
<%
request.setCharacterEncoding("utf-8");//解决中文乱码问题
%>
<!--用户名返回的是一个值,用gerParameter,爱好返回的是一个字符串数组,用getParameterValues -->
用户名:<%=request.getParameter("username")%>
爱好:<%
String[] favorites = request.getParameterValues("favorite");
for(int i=0;i<favorites.length;i++)
{
out.println(favorites[i]+" ");
}
%>
</body>
</html>
运行结果:
中间出了一点小差错:
(1)Tomcat工程被我closed掉了,所以启动报错,open project 即可
(2)将reg.jsp的<form action="request.jsp" name="loginForm" method="post">后面加了个</form>所以下面的代码失效,狂点提交按钮没有反应,最后是用火狐调试发现的,继续加油。
在reg.jsp中添加URL地址,查看链接
<body>
<h1>用户注册</h1>
<form action="request.jsp" name="loginForm" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>爱好:</td>
<td>
<input type="checkbox" name="favorite" value="read"/>读书
<input type="checkbox" name="favorite" value="yujia"/>瑜伽
<input type="checkbox" name="favorite" value="fadai"/>发呆
</td>
</tr>
<tr>
<td>显示:</td>
<td colspan="2"><input type="submit" name="提交"/></td>
</tr>
</table>
</form>
<a href="request.jsp?username=张张">测试张张账号</a> <!-- 添加URL -->
</body>
当username是英文的时候正常显示,当是中文时,显示乱码,因此可以得出 request.jsp 中的脚本(如下文),无法解决URL传递中文出现的乱码问题
<%
request.setCharacterEncoding("utf-8");//解决中文乱码问题
%>
解决如下:
修改Tomcat 配置文件 server.xml,地址:D:\Program Files\eclipse\apache-tomcat-7.0.69\conf ,添加属性: URIEcoding="utf-8",重启Tomcat 服务器,才能生效
另外,因为添加了URL,URL中只有用户名,没有爱好,通过URL传递参数只有用户名,没有爱好,所以在获取爱好时报空指针异常,所以在做遍历输出爱好时要加上判断(不等于空继续执行代码,等于空则不输出),request.jsp 输出爱好部分代码变更:
爱好:<%
if(request.getParameterValues("favorite")!=null){ //加上判断
String[] favorites = request.getParameterValues("favorite");
for(int i=0;i<favorites.length;i++)
{
out.println(favorites[i]+" ");
}
}