本章主要讲解Java Web与JSP的入门内容,适合有JSP或Java Web基础的读者学习。
1.Web应用与web.xml文件
(1)Java Web应用程序的结构
Java Web应用基本结构
webapp├── WEB-INF│ ├── web.xml│ ├── classes│ ├── lib│ └── jsp文件、配置文件└──jsp文件、js文件、html文件
webapp:Java Web应用根路径,webapp是Web应用名称,该目录下可直接放JSP文件、html文件、js文件...
WEB-INF:Java Web应用必须存在的路径,该路径访问权限较高,浏览器访问不到,该路径主要存放Web应用配置信息和其依赖的jar文件和class文件
web.xml:Web应用配置文件
classes:Web应用java类编译的class文件
lib:Web应用依赖的jar文件
(2)web.xml文件说明
1.web应用的WEB-INF路径下的web.xml文件被称为配置描述符,在Servlet2.5规范之前,每个Java Web应用都必须包含一个web.xml文件,且必须放在WEB-INF路径下。对于Servlet3.0规范而言,WEB-INF路径下的web.xml文件不再是必须的,但是还是建议保留此文件。
2.在Servlet2.5规范之前,Java Web应用的绝大部分组件是通过web.xml文件来配置管理,Servlet3.0规范可通过Annotation来配置管理Web组件。
3.web.xml文件可以配置如下:配置JSP属性、配置Servlet、配置Listener、配置Filter、配置标签库、配置管理JAAS授权认证、配置和管理资源引用、Web应用首页...等。
4.web.xml文件示例:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID"version="3.0"metadata-complete="false"><display-name>Web-Test</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list></web-app>
注:当metadata-complete值为"false"时,该Web应用将不会加载Annotation配置的Web组件(如:Servlet、Filter、Listener)。
2.JSP原理介绍
(1)JSP基本原理
JSP的本质是Servlet(Servlet是一个特殊的Java类),每个JSP页面就是一个Servlet实例(JSP页面由系统编译成Servlet),对于Tomcat而言,JSP页面生成的Servlet放在work路径对应的Web应用下。例如,如下的JSP文件(Test01.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%><!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><%for (int i = 0; i < 100; i++){%><%="i的当前值:" + i %><br><%}%></body></html>
当启动Tomcat访问此JSP页面之后,可以在Tomcat路径work\Catalina\localhost\JspServlet-Test\org\apache\jsp下看到Test01_jsp.java与Test01_jsp.class文件,web应用名为JspServlet-Test,打开Test01_jsp.java文件如下:
/** Generated by the Jasper component of Apache Tomcat* Version: Apache Tomcat/7.0.62* Generated at: 2015-08-19 13:51:53 UTC* Note: The last modified time of this file was set to* the last modified time of the source file after* generation to assist with modification tracking.*/package org.apache.jsp;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;public final class Test01_jsp extends org.apache.jasper.runtime.HttpJspBaseimplements org.apache.jasper.runtime.JspSourceDependent {private static final javax.servlet.jsp.JspFactory _jspxFactory =javax.servlet.jsp.JspFactory.getDefaultFactory();private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;private javax.el.ExpressionFactory _el_expressionfactory;private org.apache.tomcat.InstanceManager _jsp_instancemanager;public java.util.Map<java.lang.String,java.lang.Long> getDependants() {return _jspx_dependants;}public void _jspInit() {_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());}public void _jspDestroy() {}public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)throws java.io.IOException, javax.servlet.ServletException {final javax.servlet.jsp.PageContext pageContext;javax.servlet.http.HttpSession session = null;final javax.servlet.ServletContext application;final javax.servlet.ServletConfig config;javax.servlet.jsp.JspWriter out = null;final java.lang.Object page = this;javax.servlet.jsp.JspWriter _jspx_out = null;javax.servlet.jsp.PageContext _jspx_page_context = null;try {response.setContentType("text/html; charset=UTF-8");pageContext = _jspxFactory.getPageContext(this, request, response,null, true, 8192, true);_jspx_page_context = pageContext;application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();_jspx_out = out;out.write("\r\n");out.write("\r\n");out.write("\r\n");out.write("\r\n");out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");out.write("<html>\r\n");out.write("<head>\r\n");out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");out.write("<title>Insert title here</title>\r\n");out.write("</head>\r\n");out.write("<body>\r\n");out.write("\t");for (int i = 0; i < 100; i++){out.write("\r\n");out.write("\t\t\t");out.print("i的当前值:" + i );out.write("<br>\r\n");out.write("\t\t\t");}out.write("\r\n");out.write("</body>\r\n");out.write("</html>");} catch (java.lang.Throwable t) {if (!(t instanceof javax.servlet.jsp.SkipPageException)){out = _jspx_out;if (out != null && out.getBufferSize() != 0)try {if (response.isCommitted()) {out.flush();} else {out.clearBuffer();}} catch (java.io.IOException e) {}if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);else throw new ServletException(t);}} finally {_jspxFactory.releasePageContext(_jspx_page_context);}}}
可以看到该Java类主要包含如下三个方法:
_jspInit():初始化JSP/Servlet的方法。
_jspDestroy():销毁JSP/Servlet的方法。
_jspService():对用户请求生成响应的方法。
(2)JSP的特性
根据以上JSP的工作原理,可以总结出一下结论:
1.JSP文件必须在JSP服务器内运行。
2.JSP必须生成Servlet才能运行。
3.每个JSP第一次访问速度会很慢,因为必须等待JSP编译成Servlet。
3.JSP注释
JSP文件中的注释有一下三种:
(1)JSP标准注释
<%-- JSP标准注释 --%>
(2)Java语言注释
<%// Java语言注释/*Java语言注释块**/%>
(3)html注释
<!-- html注释 -->
4.JSP声明
JSP声明的语法如下:<%! // 用于定义全局变量(Servlet成员变量)、方法、内部类 %>
(1)JSP定义全局变量
JSP全局变量就是该JSP编译后Servlet类的成员变量,其定义方式如下:
<%!// 就像在类中定义成员变量一样private static final String YES = "1";private String userName;public int age = 20;%>
注意:JSP页面会编译成一个Servlet类,而该Servlet类在Servlet容器中只有一个实例,所以不同的请求访问同一个JSP页面时,实际上访问的是同一个Servlet实例,此时就需要注意Servlet成员变量的线程安全问题。
(2)JSP定义方法
<%!public static void holle(String msg){System.out.println(msg);}public String info(){return "holle";}%>
在JSP中定义的方法会编译到Servlet中,成为其对应Servlet的方法。在JSP中定义方法,就像在类中定义方法一样。
(3)JSP定义类
<%!public class Person{private String name;private int age;}%>
在JSP中定义的类也会编译到Servlet中,成为其对应Servlet的内部类。
5.JSP输出表达式
JSP输出表达式使用语法如下:<%=表达式 %>,其中的表达式可以是Java的一条语句(如:运算表达式、方法调用...),JSP会把表达式结果的toString()字符输出到Html中。例如:
<%!private int count = 1;public String info(){return "asdfg";}%><%=123 * 3 + 55 %><%=info() %><%="Count值:" + count %>
JSP输出表达式的功能主要是方便数据输出到html页面。
6.JSP脚本
JSP脚本使用语法如下:<% Java代码块 %>,使用示例:
<%for (int i = 0; i < 100; i++){out.println("i的值:" + i);}%>
JSP脚本最终会按顺序编译到Servlet的_jspService()方法中,在JSP脚本中可以使用JSP内置对象。
-------------------------------------------------------------------------------------------------------------------------------
浙公网安备 33010602011771号