JSP培训笔记

来源:互联网 发布:2017java的就业前景 编辑:程序博客网 时间:2024/06/04 18:54
JSP:QQ:C/S结构的应用程序Javascript是运行在客户端的。JSP是运行在服务器端的。B/S:浏览器端/服务器 它是基于Internet的产物在B/S结构下,应用程序被部署在服务器。客户端只需要一个浏览器  不许要安装任何其它文件便可以访问每个在internet中的应用JSP它是运行在服务器端的,而html是在客户端解析的。WebRoot:Web应用的根目录Tomcat:它是一个开源的web服务器Tomcat中的目录结构: bin:一些可执行文件,比如:tomcat服务器的启动和停止文件 conf:当前服务器的一些配置文件。 lib:当前服务器运行时所需要依赖的一些库文件 logs:当前服务器运行时记录的一些日志文件。 temp:一些临时文件 webapps:存放部署在服务器中的所有web应用程序 work:存放webapp中jsp页面所对应的java文件eclipse中的工程名和web服务器中的应用名之间的区别访问服务器:http://localhost:8080/应用程序名服务器中的web应用程序对应着web工程的WebRoot这个目录。其中WEB-INF这个目录中存放classes,lib,web.xml文件classes:部署在服务器中的java源文件的字节码文件lib:当前应用程序运行时可能依赖的库文件web.xml:当前应用程序的初始化配置文件在访问web资源的时,常见的错误有: 404:访问资源未找到。 500:一般是访问的页面中存在错误代码 200:表示成功http协议: 超文本传输协议,它是一个无状态协议。用于在internet中发送和响应信息。默认端口80。JSP:Java Server Page(java服务器页面)它是运行在服务器端的。Jsp执行过程: 1、转译:.jsp-->>>.java 2、编译:.java -->>>.class 3、执行:.classJsp的组成部分: 1、静态内容 2、指令 <%@ %> 3、小脚本  <% java代码 %> 主要写java代码  --service方法中 4、表达式 <%= %>  主要用来输出数据 等价于out.print();   --service方法中 5、声明<%! %> 主要用于申明变量和方法  //申明中的变量和方法其实是对应类中的成员变量和方法 6、标准动作 以“<jsp: 动作名 ” 开始,以“</jsp:动作名>  ” 结束,比如:<jsp:include page=" Filename" /> 7、注释    <!-- 这是html注释,但客户端可以查看到 --> 会被转译,会占用宽带    <%-- 这也是jsp注释,但客户端不能查看到 --%> 不会被转译的    以及脚本注释://   /*……*/===================================JSP内置对象==========================JSP九大内置对象:page request session application : 表示变量存储范围 从小到大pageContext responseout config exceptionrequest对象常用的方法:String getParameter(String name)   根据页面表单组件名称获取请求页面提交数据String[ ] getParameterValues (String name)   获取页面请求中一个表单组件对应多个值时的用户的请求数据void setCharacterEncoding(java.lang.String env)   设置请求内容的字符编码String getMethod()  获取请求方式request对象其它方法Cookie[] getCookies()String getHeader(String name)Enumeration getHeaderNames()String getRequestURI()HttpSession getSession()response 对象常用方法void setContentType (String name)设置作为响应生成的内容的类型和字符编码void sendRedirect (String name)发送一个响应给浏览器,指示其应请求另一个URLString encodeURL(java.lang.String url)构建一个包含会话信息的URL地址void sendError(int sc)post提交:(request本身不支持中文)1、void request.setCharactorEncoding("utf-8");get/post支持中文                                            终极解决方法:new String重新大包字符串username = new String(username.getBytes("iso8859-1"),"utf-8")页面的跳转方式:重定向:response.sendRedirect()转发:request.getRequestDispatcher().forward();重定向url地址发生改变,但转发不发生改变重定向请求对象发生改变,但转发时请求对象不变======================================================邱:-------1.request对象:input.jsp,test.jsp2.解决get/post 请求中文乱码问题  几种编码格式的解释:  英文编码:iso8859-1  中文编码:gb2312<gbk<gb18030  一个汉字2个字节  国际编号:utf-8(unicode编号,一个汉字3个字节)  post提交   2种方式:request.setCharacterEncoding("utf-8");         new String()  get提交:new String()3:get/post的区别和联系  get请求:1、通过url传值2、大小限制在0-255个字节之间3、不能传递敏感信息,比如:帐号,密码  post请求:1、不通过url传值2、理论上没有限制3、能够传递敏感信息4个作用域(重点):pageContext request session applicationpageContext:表示存放在该作用域下的值只在当前页面有效,书信该页面也没有效request:表示存放在该作用域下的值在一个请求和相应范围内有效session:表示存在在该作用域下的值在一个会话范围内有效(可以是多个请求和相应)当浏览器关闭该session才终止application:表示存放在该作用域下的值在整个应用程序范围(服务器未关闭或重启)内有效4个作用域范围有小到大pageContext<request<session<application建议:能用request对象尽量用,不行考虑session,然后再是application案例:scope.jsp作用域相关方法:void setAttribute(String name,Object value);Object getAttribute(String name);void removeAttribute(String name);5:(重点)test.jsp ---->test1.jsp 逻辑:test1.jsp只做逻辑处理,将相关处理结果交给单独的jsp页面显示 jsp的两大功能 A:逻辑处理:相当于一个java类(servlet),由于其不许要承担显示的任务,所以其html代码可以删除 B:显示页面:相当于html(display.jsp) 转发的作用域是request【只能相对路径】, 重定向的作用域是session【可以用绝对路径也可以是姓对路径】6:(重点)转发和重定向的联系和区别 A:转发:request.getRequestDispatcher().forward();特点: 1、可以保存request或以上作用域内的值 2、url路径只能是相对路径:(webRoot后的路径) 3、浏览器地址栏的url没有发生改变 B:重定向:response.sendRedirect();特点: 1、可以保存session或移上作用域内的值 2、url路径可以是相对路径也可以是绝对路径 3、浏览器地址栏的url发生改变建议:能用转发尽量用,不行再考虑重定向7:其它内置对象 page page.jsp //String str = ((HttpJspPage)page).getServletInfo(); exception exception.jsp  //当前夜要是个错误页 isErrorPage="true"8:设置和保存cookie   setCookies.jsp//创建6gecookie对象for(int i=0;i<3;i++){    //创建cookie对象    Cookie cookie = new Cookie("cookie-n-"+i,"cookie-v-"+i);    //保存cookie    response.addCookie(cookie);    //创建一个有时效限制的cookie    cookie = new Cookie("cookie-p-"+i,"cookie-pv-"+i);    //设置时效为1小时    cookie.setMaxAge(3600);    //保存cookie    response.addCookie(cookie);} 读取和显示cookie:showCookies.jsp//将浏览器中所有的cookie读取出来Cookie[] cookies =request.getCookies();Cookie cookie = null;for(int i=0;i<cookies.length;i++){    cookie = cookies[i];    out.print("cookie的名字="+cookie.getName()+"<br/>");    out.print("cookie的值="+cookie.getValue()+"<br/>");}9:控制访问实现:login.jsp test2.jsp success.jsp10.包含页面:include.jsp,包含login.jsp中登录表单<%@ include file="login.jsp" %>同一个浏览器,同一个session<meta http-equiv="refresh" content="2"/> //2秒自动刷新一次===========================================1:jsp的标准动作 useBean   实例化对象 setProperty  set方法 getProperty  get方法 forward     request转发 include     includ指令 param参数<!-- 实例化MyBean对象 --><jsp:useBean id="bean" class="com.itany.MyBean" scope="page"/> <!-- 给bean对象属性赋值 --><jsp:setProperty property="name" name="bean" value="mike"/><!-- 取值并且输出 --><jsp:getProperty property="name" name="bean"/> <jsp:forward page="test1.jsp"></jsp:forward><jsp:include page="test1.jsp"/>---------------------------------test5.jsp<%=request.getParameter("username")%>test4.jsp<% request.setCharacterEncoding("utf-8");%><jsp:include page="test5.jsp"><jsp:param value="mike" name="username"/></jsp:include>=====================================================EL表达式:expression language1、使用EL,不需要加载任何jar包,内嵌在jsp中的,只要容器(tomcat)   实现了j2ee1.4/servlet2.4/jsp2.0的规则即可  (tomcat5.0即可)2、基本表达式 test.jsp\${true }${true || false } true${true && false } false${true or false } true${not true } false${"helloword" }${'welcome' }${'${ '} true or false }:${true or false }  //${'${ '} true or false }:true${'${ '} !true }:${not true }禁用EL局部禁用: \  只禁用后面一个EL表达式全局禁用: isELIgnored="true"4、文字常量:test3.jsp${1+2 }${10 div 5 } 2.0${2.323e3 }  2323.0${'hello' }${"" }${null }   运算符:${1+2 }${10 div 5 } 2.0${2.323e3 }  2323.0${'hello' }${"" }${null }${1 lt 2 }${2 > 1 }${2 le 2 }56==43->>${56 == 43 }56≥43${56 ge 43 }56≤43${56 <= 43 }${empty "" } ${empty 'aa' } 5、作用域:test4.jsppageScope--->pageContextrequestScope--->requestsessionScope--->sessionapplicationScope--->application<% //设置背景色pageContext.setAttribute("color","#00ff00");pageContext.setAttribute("text","EL表达式");pageContext.setAttribute("num1",12);pageContext.setAttribute("num2",12);%><body bgcolor="${pageScope.color}">${pageScope.text }${pageScope.num1 } * ${pageScope.num2 } = ${pageScope.num1 *pageScope.num2 }//作用域对象可以不写,规制:从page一直到application往上找 ${num1 } * ${num2 } = ${num1 *num2 } </body>-----------获取javaBean中的值<% Bean bean = new Bean();bean.setUsername("xwq");bean.setAge(21);//建立子beanSubBean subBean = new SubBean();//建立子bean和主bean的关联bean.setSubBean(subBean);   //获取子bean的关键地方//EL表达式中的对象是存储在莫个作用域下的对象,否则为null,页面显示为空pageContext.setAttribute("bean",bean);%>${bean.username }${bean.age }${bean.hello }${bean.subBean.str }EL:隐式对象  pageContext================================================================JSTL:1、核心标签库:通用标签:set remove out catch条件标签:if choose(when otherwise)迭代标签:forEach forTokensURL标签:url import2、国际化和格式化标签:国际化标签:I18N(Internationalization)采用taglib指令绝对定位:<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>------------1、JSTL标签的配置和使用配置:A:加载jar包 jstl.jar ,standard.jar使用:A:采用taglib指令引入标签库1:采用绝对定位:<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>2:采用相对定位:<%@  taglib uri="WEB-INF/c.tld" prefix="c" %>---------通用标签:---------out标签:<c:out value="< "></c:out><c:out value="${name}" default="中国"></c:out><br><c:out value="${name}" default="<font color='red'>中国</font>"  escapeXml="false"></c:out>set标签:<c:set var="a" value="root" scope="request"></c:set>${a }<br><c:out value="${a}"></c:out>remove标签:<h2>C:remove</h2><c:remove var="a" scope="session"/>c:remove--->${a }catch标签:<c:catch var="msg"><%Integer.parseInt("abc");%></c:catch>${msg }-------条件标签-------if标签:<form action="" name="form1" method="post">用户名:<input type="text" name="username" value="${param.username }"><br><input type="submit" value="提交"></form><c:if test="${param.username eq 'admin' }">success</c:if>choose标签:<c:choose><c:when test="${flag }">success</c:when><c:otherwise> not success </c:otherwise></c:choose>---------迭代标签:---------forEach标签:<c:forEach var="i" begin="1" end="9"><c:forEach var="j" begin="1" end="${i}">${j }* ${i } = ${i*j }</c:forEach><br></c:forEach><%List list = new ArrayList();list.add("a");list.add("b");list.add("c");request.setAttribute("ls",list);%><c:forEach items="${ls }" var="a" varStatus="status">${a } ${status.index }  ${status.count }  ${status.first }<br></c:forEach>forTokens标签:<h2>C:forTokens</h2><c:set var="names" value="a;b,c;d,e"></c:set><c:forTokens items="${names }" delims=",;" var="name">${name }<br></c:forTokens>---------url标签---------import标签:<c:import url="test.jsp"></c:import>子标签<c:param name=“…” value=“…”>用于向被包含页面传递参数url标签:用于产生一个URL<c:url value="test.jsp"><c:param name="username" value="xwq"></c:param><c:param name="age" value="23"></c:param></c:url>子标签<c:param name=“…” value=“…”>用于产生Query String//test.jsp?username=xwq&age=23 2、I18N(Internationalization)国际化标签A:将相关属性文件拷贝到src路径下面,项目经部署后,自动拷贝到classes路径下。B:创建页面jstl_I18N.jsp1、加头文件<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <%@ taglib uri="WEB-INF/fmt.tld" prefix="fmt" %>例子:<!-- 设置当前字符 --><fmt:setLocale value="${param.rdo}"/><!-- 找到头文件 --><fmt:setBundle basename="labels" var="src"/><form action="" method="post" name="form1"><c:set var="check" value="${param.rdo}"></c:set><c:choose><c:when test="${check eq 'ch'}"><input type="radio" name="rdo" value="zh" checked></c:when><c:otherwise><input type="radio" name="rdo" value="zh"></c:otherwise></c:choose><fmt:message key="chinese" bundle="${src }"/><br><c:set var="check" value="${param.rdo}"></c:set><c:choose><c:when test="${check eq 'ch'}"><input type="radio" name="rdo" value="en" checked></c:when><c:otherwise><input type="radio" name="rdo" value="en"></c:otherwise></c:choose><fmt:message key="english" bundle="${src }"/><br><c:set var="check" value="${param.rdo}"></c:set><c:choose><c:when test="${check eq 'ch'}"><input type="radio" name="rdo" value="de" checked></c:when><c:otherwise><input type="radio" name="rdo" value="de"></c:otherwise></c:choose><fmt:message key="german" bundle="${src }"/><br><c:choose><c:when test="${check eq 'sv'}"><input type="radio" name="rdo" value="sv" checked></c:when><c:otherwise><input type="radio" name="rdo" value="sv"></c:otherwise></c:choose><fmt:message key="swedish" bundle="${src }"/><br><input type="submit" value="<fmt:message key='submit' bundle='${src }' />"/></form>3、格式化标签:formatNumber<h2>格式化标签:formatNumber(大于0.5才进位)</h2><fmt:formatNumber value="123.451" type="number" maxFractionDigits="1" /><h2>formatNumber(截取小数)</h2><fmt:formatNumber value="${123.51-0.49}" type="number" maxFractionDigits="0"/><h2>formatNumber(截取小数)</h2><!-- 原理:先得到余数,将余数减去,再整除 --><fmt:formatNumber value="${(5-(5%6))/6}" type="number" maxFractionDigits="0" /><h2>currency</h2><fmt:formatNumber value="123.4567"  type="currency" currencySymbol="$" minFractionDigits="1" /><h2>percent</h2><fmt:formatNumber value="123.4567" type="percent" minFractionDigits="2" groupingUsed="false" var="a"/>${a }------------------------parseNumber标签(和formatNumber相反)------------------------<h2>parseNumber</h2><h3>number</h3><fmt:parseNumber value="123.456" type="number" /><h3>currency</h3><fmt:parseNumber value="¥123.456" type="currency" parseLocale="zh_CN"/><fmt:parseNumber value="$123.456" type="currency" parseLocale="en_US" integerOnly="true"/><h3>percent</h3><fmt:parseNumber value="12%" type="percent" var="a"/>${a }-------------formatDate标签-------------<%Date date = new Date();request.setAttribute("myDate",date);%><fmt:formatDate value="${myDate}" type="date" dateStyle="full" /><br><fmt:formatDate value="${myDate}" type="time" timeStyle="long" /><br><fmt:formatDate value="${myDate}" type="both" dateStyle="full" timeStyle="long" var="a" /><br>${a }-------------parseDate标签-------------<fmt:parseDate value="2012-10-10" type="date"/><br><fmt:parseDate value="12:12:12" type="time"/><br><fmt:parseDate value="2012-10-10 12:12:12" type="both"/><br>3、函数标签 jstl_fn.jspA:加一个标签头<h2>length</h2>${fn:length("abc") }<br><%List list = new ArrayList();list.add("a");list.add("b");list.add("c");request.setAttribute("list",list);%>${fn:length(list) }<h2>contains</h2>${fn:contains(list,"b") }${fn:containsIgnoreCase("abc","A") }<h2>startsWith endsWith</h2>${fn:startsWith("abc","ab") }<br>${fn:endsWith("abc","bc") }<br><h2>indexOf</h2>${fn:indexOf("abcdefg","d") } <!-- 没有找到返回-1 --><h2>substring</h2>${fn:substring("hello world",2,8) }<br>${fn:substringAfter("hello world","lo") }<br>${fn:substringBefore("hello world","w") }<br><!-- 将“<”当作<输出 而不是标签的"<" -->${fn:escapeXml("<") }<br>1${fn:trim(" abcde ") }${fn:toLowerCase("ABCd") }${fn:toUpperCase("ABCd") }<c:set var="str" value="a,b,c" /><c:forEach items="${fn:split(str,',') }" var="ele" varStatus="start">arr[${start.index } ]= ${ele }</c:forEach><br><c:set var="arr" value="${fn:split(str,',') }" />${fn:join(arr,'$') }<!-- 替换所有出现的字符 -->${fn:replace("abca","a","xwq") }

原创粉丝点击