----------------------------------- JSP的scriptlet-------------------------------
JSP的scriptlet
从单词上分析script是脚本:let在JAVA中表示的小程序,scriptlet表示脚本小程序。
JSP中的Java代码块就是最常见的动态信息。它分为三种:
- <%...%>:java代码片段
代码片段会原模原样的出现在真身中,不会有变动。正常的Java代码都可以在代码片段中出现;
- <%=…%>:表达式在页面上打印数据
表达式会在“真身”中输出,例如:<%=a%>,对应真身中的out.print(a)。只能出现常量、变量,以及有返回值的方法调用,而且不能出现分号!即在out.println()的合法参数都可以!
- <%=a%>对应out.println(a);
- <%=”a”%>对应out.println(“a”);
- <%=fun()%>对应out.println(fun());
- <%=a;%>对应out.println(a;),所以出错;
- <%=System.out.println(“hello”)%>对应out.println(System.out.println(“hello”)),所以出错。
- <%!...%>:声明
声明对应“真身”中的属性和方法!
Index.jsp代码:
<%@ 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 'index.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"> --> </head>
<body> <%! // 定义jsp全局常量 public static final String DRIVER = "com.mysql.jdbc.Driver"; //定义方法 public int add(int i){ return i; } %> <% String name = "likunpeng"; //局部变量%> <%=name %> <%=DRIVER %> <%=add(10) %>
<form actin="/jsp_demo/index.jsp" method="post"> row:<input type="text" name="row"><br> col:<input type="text" name="col"><br> <input type="submit" value="print"> </form> <hr> <% //接收变淡提交的参数 String row = request.getParameter("row"); String col = request.getParameter("col"); Integer rowInt = 1; Integer colInt = 1; if(row != null){ rowInt=new Integer(row); }
if(col != null){ colInt=new Integer(col); } %> <table border="1px;"> <!-- 使用表单提交的参数打印对应的行和列 --> <% for(int i = 1; i <= rowInt;i++){ %> <tr> <% for(int j = 1;j <= colInt; j++){ %> <td> <% out.print(i*j); %> <br> <!-- %= 相当于out.print(); --> <%=i*j %><br> <%="李昆鹏" %><br> <%="abcd" %><br> </td> <% } %> </tr> <% } %> </table> </body> </html> |