JSP表达式<%=表达式%>
scriptlet<% java code%>
1. jsp 方法和变量:
<%! 方法或者域%>
//定义的是全局的方法和成员变量;如:
<%! private int a=9;
private String fun1(){
return ("<H2>HAHA<H2>");
}
%>
在编译的.java文件中为:全局变量和方法
private int x=8;
private String fun1(){
return ("<H2>haha<H2>");
}
而<% int x = 8;%>//这种声明的是局部变量,被插入到_jspservice方法中.
2. 使用预定义变量:
在servlet中 doGet()方法:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
HttpSession session = req.getSession();
out.println("seesion is new: "+session.isNew()+"<br>");
out.println("sessionID :"+session.getId()+"<br>");
session.setAttribute("addr", "上海市。黄浦区");
);
}
servlet API告诉doGet参数类型,可以获取会话对象和输出所需的方法,而JSP将方法名从doGet改为了_JSPService,并使用JspWrite替代PrintWriter 。
_JSPService中自定义了8个局部变量(可用变量:requst,response,out,session,application,config,pagecontext,page),称为“隐含对象”。因此,如果你编写的代码不属于_JSPService,则不能使用这些变量。还要一个附加变量exception仅仅在错误页面中才可以用。