今天学习JSP,进行了几个页面的实践,发现了几个要在平常开发中注意以及避免的问题。还有一些小知识点的总结。
1、用小脚本在页面显示一个九九乘法表,并且带上鼠标样式。
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index2.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style>
.red{
background-color:yellow;
color:red;
}
.white{
backgound-color:white;
color:#000000;
}
</style>
</head>
<body>
<table border="1">
<%
//九九乘法表
for(int i=1;i<=9;i++){
%>
<tr>
<%
for(int j=1;j<=i;j++){
%>
<td οnmοuseοver="this.className='red'" οnmοuseοut="this.className='white'">
<%=i%>*<%=j%>=<%=i*j%></td>
<%} %>
</tr>
<%} %>
</table>
</body>
</html>
2、 <%@include file="header.jsp" %>类似如此的叫静态包含,就是包含的java源代码,就是将两个页面的java编译后后再合并到一起,然后编译,缺点就是变量名容易冲突。
3、我们用request传值过来之后需要进行编码转换:request.setCharacterEncoding("UTF-8");
4、获取用户从客户端传过来的值
方法一:单个值我们用request.getParameter("name");
方法二:getParameter 只能取单个参数值,如果一个参数有多个参数值,就要采用 String[]getParameterValues();String[] ins=request.getParameterValues("name");
方法三:以上的方法与前段的页面太耦合,需要name都一样,违背了“高内聚低耦合”的特点,所有采用以下方法得到参数名然后得到参数值的方法
<%
request.setCharacterEncoding("utf-8");
//取出所有的参数的名字
Enumeration<String> parameternames= request.getParameterNames();
while( parameternames.hasMoreElements() ){
String pn=parameternames.nextElement(); //取出每一个参数的名字(键)
if( request.getParameterValues(pn).length>1){
String[] values=request.getParameterValues(pn);
out.println( pn+"=");
for( String s:values){
out.println( s +" ");
}
}else{
String value=request.getParameter(pn);
out.println( pn+"="+value+"<br />");
}
}
%>
5、<%! %> 在声明中只能有全局变量定义,及方法的定义。
6、两种注释:
<!-- html注释: 是会返回到客户端浏览器上去的,即它要消耗流量 , 对静态代码使用注-->
<%-- 服务器注释,只要服务器中有,不会消耗流量 --%>