JSP页面处理和输出
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
<%@page contentType="text/html;charset=GBK"%>
<%@page import="java.util.HashMap" %>
<%! private HashMap sexMap;
private HashMap favorMap;
public void jspInit() {
sexMap = new HashMap();
sexMap.put("male", "男");
sexMap.put("female", "女");
favorMap = new HashMap();
favorMap.put("sport", "运动");
favorMap.put("sleep", "睡觉");
favorMap.put("art", "艺术");
favorMap.put("others", "其他");
}
private String escapeHtml(String str) {
int len = str.length();
StringBuffer sb = new StringBuffer(len);
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
switch (c) {
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case ' ':
sb.append(" ");
break;
case '"':
sb.append(""");
break;
case '&':
sb.append("&");
break;
case '\n':
sb.append("<br>");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
private String transString(String str, String error) {
String result;
if (str == null || (str = str.trim()).length() == 0) {
result = "<font color='red'>" + error + "</font>";
} else {
result = escapeHtml(str);
}
return result;
}
%>
<%
request.setCharacterEncoding("GBK");
String nameDesc = request.getParameter("name");
nameDesc = transString(nameDesc, "你未提供名字");
String sexDesc = request.getParameter("sex");
sexDesc = (String)sexMap.get(sexDesc);
String[] favors = request.getParameterValues("favor");
String favorDesc = "";
if(favors!=null){
for (int i = 0; i < favors.length; i++) {
favorDesc += " " + (String)favorMap.get(favors[i]);
}
}
favorDesc = transString(favorDesc, "你未选择爱好");
String introDesc = request.getParameter("intro");
introDesc = transString(introDesc, "你未填写简介");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>JSP Page</title>
</head>
<body>
<b>你填写的信息是:</b><br>
<b>名字:</b><%=nameDesc%><br>
<b>性别:</b><%=sexDesc%><br>
<b>爱好:</b><%=favorDesc%><br>
<b>简介:</b><br>
<div style="background: #ffffdd">
<%=introDesc%>
</div>
</body>
</html>
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
</head>
<body>
<form action="proc.jsp" method="post">
姓名:<input type="text" name="name"><br>
<fieldset>
<legend>性别</legend>
<input type="radio" name="sex" value="male" checked>男
<input type="radio" name="sex" value="female">女
</fieldset>
<fieldset>
<legend>爱好</legend>
<input type="checkbox" name="favor" value="sport">运动
<input type="checkbox" name="favor" value="sleep">睡觉
<input type="checkbox" name="favor" value="art">艺术
<input type="checkbox" name="favor" value="others">其他
</fieldset>
简介:<br>
<textarea cols="30" row="4" name="intro"></textarea>
<br>
<input type="submit" value="提交">
<input type="reset" value="重写">
</form>
</body>
</html>