Javaweb、javaEE学习笔记基础知识



Html
1、属性
 align:对齐方式
 bgcolor:背景颜色
target:
_blank在新窗口打开 _self默认,在相同的框架打开
_parent在父框架集中打开 _top在整个窗口打开
framename在指定的窗口打开

2、注释
 <!-- 注释 -->

3、文件路径
 同一目录下:文件名
 上级目录:../
 下级目录: 从目标文件开始的文件目录

4、表格
 tr行、td列、th表头
<table border="1" align="center" width="80%" bordercolor="green" cellspacing="0"  cellpadding="10pt"><!—cellpadding代表文字和行之间的距离-->
<caption>学生成绩表</caption>
<tr><th>姓名</th><th>年龄</th><th>成绩</th></tr>
<tr><td>张三</td><td rowspan="2">21</td><td>34</td></tr>
<tr><td>李四</td><td>56</td></tr>
<tr><td colspan="3">王五</td></tr><!—colspan代表列合并,rowspan代表行合并 -->
</table>

5、表单form
表单域input
 type:text文本框、password密码、radio单选按钮、checkbox:复选框
     是否需要在本书再版时立即通知您:
     <input type="radio" checked="true">是
     <input type="radio">否
     submit提交按钮、reset重置按钮、button普通按钮
     <input type="submit" value="提交">
     hidden隐藏域(用来传送数据,不安全)
file:文件上传(两个条件:method=”post”、enctype=”multipart/form-data”)
 name:表单域的名字
 value:表单域的初始值
 size:表单元素的长度,只适用于text、password
 maxlength:表单元素中可以输入的最大字符数,只适用于text、password
 checked:boolean属性,指定按钮是否是被选中的,只适用于radio、checkbox
 readonly:只读的,只适用于text,数据能提交到后台
 disabled:表示表单域不能用,数据不能提交到后台
多行文本textarea
 <textarea cols=”20” rows=”5”></textarea>//表示可以输入5行20列
下拉列表框select
 <select name=”city” multiple>//可以选中多项
 <option value=”beijing”>北京</option>
 <option value=”shanghai”>上海</option>
 <option value=”qingdao” selected=”true”>青岛</option>//默认选中
</select>
域容器fieldset
 <fieldset style=”width:200”>
  <legend align=”left”>小标题</legend>
  用户名:<input type=”text”>
  密码:<input type=”password”>
</fieldset>

6、框架frame
 frameset:分割窗口
rows分割行cols分割列
  frameborder:是否显示框架,0不显示、1显示,默认为1
  framespacing:框架间的间距
 frame:框架
  src:指定框架显示的HTML文件的位置
  noresize:设置不可以调整窗口的大小
  bordercolor:框架边框的颜色
<frameset rows=”10%,80%,*”>
 <frame src=”header.html” noresize>
 <frameset cols=”20%,*”>
  <frame src=”left.html” noresize>
  <frame src=”table.html” noresize name=”right”>
 </frameset>
 <frame src=”footer.html” noresize>
</frameset>
<noframes>
 <body>浏览器版本较低,请升级后访问</body>
</noframes>
  marginwidth:窗口内的内容与窗口左右边缘的距离
  marginheigth:窗口内的内容与窗口上下边缘的距离
  scrolling:是否显示滚动条,no-不显示、yes-显示、auto-默认 自动设置
 noframes不支持框架的浏览器
  注意:<body></body>标签与<frameset></frameset>标签不能同时使用,不过,如果添加包含一段文本的
   <noframes>标签,就必须将这一段文字嵌套于<body></body>标签内

  

 JavaScript
1、增强代码可读性
<--  JavaScript代码 //-->

2、语法结构
 1)大小写敏感
 2)一句话结束最好加;
 3)注释 //  /**/
 4)弱类型

3、变量命名
 1)以字母、下划线_或美元符号$开头
 2)余下的字符可以是字母、下划线_或美元符号$、数字
 3)最长为255个字符
 4)不能有空格、大小写敏感
 5)不能使用JavaScript中的关键字或者保留字命名

4、JS变量类型
 Undefined:未定义的类型、String、Boolean、Null、Number五种
 可以使用typeof(object)来获取变量类型

5、声明 var 变量名[=初始值]
 var i = 10;
 var j;
 alert(typeof(i));//判断i的类型 number
 docement.write(123);

6、类型转换
 字符串>数值>布尔值 低级与高级相加,强制转换成高级的
 字符串数值
 parseInt()、parseFloat()、Number()

7、运算符
 算术运算符 +、-、*、/、%、++、--(前置先自增再运算、后置先运算后自增)
 比较运算符 ==、>、>=、<、<=、!=
 逻辑运算符 &&、||、!非
 赋值运算符 =、+=、-=、*=、/=

8、try{}catch(){}
 try{var a=c}catch(e){alert(e);}

9、Array数组
 var arr = new Array();//大小不固定
 var arr1 = new Array(5);//大小固定
 var arr2 = new Array(“abc”,12,23,”aaa”);//直接赋值
 
 //数组遍历for循环
 for(var i=0;i<arr2.length;i++){
  document.write(arr2[i]);
 }
 //数组遍历for each循环(注意:i代表的是索引,不是数值)
for(var i in arr2){
  document.write(arr2[i]);
}
数组方法:
1) concat()拼接数组
2) reverse()反转数组
3) join(间隔符) 返回字符串,由间隔符将所有元素连接到一起
4) pop()移除数组中的最后一个元素,并返回这个最后元素
5) shift()移除数组中的第一个元素,并返回这个元素
6) push()给数组添加新元素,并返回数组的新长度
7) slice()截取数组,返回一个新数组
8) sort()返回一个排序后的新数组//先排数组再排字母,先排十位再排个位
9) toString()返回逗号分隔的字符串
代码示例:
document.write(arr3.join(":"));// 56:32:10:4:bbb:aaa:3
document.write(arr3.push("zzz"));//8
document.write(arr3.sort().toString());//10,3,32,4,56,aaa,bbb,zzz

10、Date日期,月份是0-11
 var date = new Date();//创建当前日期对象
 var date = new Date(1970,6,12);//1970年7月12日
 var date = new Date(1970,6,12,15,3,23);//1970年7月12日15时3分23秒
 var date = new Date(‘1970/6/12’);//1970年6月12日

 日期方法:
1) toLocaleString()//将时间格式转换成字符串Monday, March 13, 2017 14:28:35


2) toLocaleDateString()//将时间格式转换成字符串,返回日期Monday, March 13, 2017
3) toLocaleTimeString()//将时间格式转换成字符串,返回时间14:28:35
4) toGMTString()//使用GMT标准时间将Date转换成字符串Mon, 13 Mar 2017 06:28:35 GMT
5) getTime()//返回毫秒数
6) getMonth()//返回当月号数,比实际小1
7) getDate()//返回当日号数
8) getDay()//返回星期几
9) getHours()、getMinutes()、getSeconds()//返回小时、分钟、秒数
10)setYear()、setMonth()...//设置时间
11) Date.parse("2014/12/12")//用日期字符串表示自1970年1月1日以来的毫秒数
12)Date.UTC(1995,11,12,11,23,24)//返回自1970年1月1日以来的毫秒数

11、Math
 1)Math.round()//四舍五入
 2)Math.ceil()//向上取整
 3)Math.floor()//向下取整
 4)Math.sqrt()//取平方根
 5)Math.random()//[0,1)之间的随机小数
 6)with(Math){document.write(round(2.5))};//在with语句体内,任何对变量的引用

12、String字符串
 var sname = “string of text”;
 var sname = new String(“stirng of text”);
 
 字符串方法:
1) length;//返回字符串长度,不是length()和java不一样
2) charAt(i);//返回指定索引处的字符
3) concat(str);//连接字符串
4) indexOf(str);//返回String对象内第一次出现字符串的字符位置lastIndexOf();
5) replace(str1,str2);//将str1替换成str2
6) slice(start,end);//返回字符串中起始位置为start,结束位置为end(不包括end)的字符串
7) split(separator,limit);//将字符串以separator作为分隔符切割,返回一个数组,有limit参数,则返回数组的limit个元素
8) substr(start,length);//返回一个从指定位置开始的指定长度的字符串
9) substring(start,end);//返回一个指定位置之间的字符串,不包括end
10) toUpperCase();//转换成大写字母

13、window对象
 window.moveBy(20,20);//将窗口向右向下移动20像素
 window.moveTo(0,0);//将窗口移动到左上角
 window.resizeBy(15,20);//将窗口相对增大15,20
 window.resizeTo(450,350);//将窗口大小改为450*350
 
window.open(url,新窗口名字,特性字符串);//打开新窗口
特性字符串:height、width、location=no没有地址栏、status=no状态栏
  var winObj = open(“house,jpg”,”house_1”,”width=500,height=300,scrollbars=no”);

14、弹出对话框
1) confirm(“确认删除吗?”);确认对话框,返回布尔值
2) alert();提示框
3) prompt(“请输入您的名字”,“admin初始值”);输入信息对话框,返回值为输入的字符串

15、定时执行
 1)setTimeout(函数名,时间间隔,重复次数),多用于递归调用
  var timeld = setTimeout(“hello()”,2000);
  clearTimeout(timeld);//清除设置的setTimeout函数
 2)setInterval(函数名,时间间隔)
  var timeld = setInterval(“hello()”,2000);
  clearInterval(timeld);

16、history对象
 1)history.go(-3);//向后返回三个访问过的页面
 2)back();//与history.go(-1)功能相同
 3)forward();//与history.go(1)功能相同

17、location对象
 location.href = “about:blank”;//清空页面

18、navigator对象
 提供用户使用的浏览器及操作系统等信息
 navigator.mimeTypes[n].type

19、screen对象获取用户屏幕信息
 width、availWidth可用宽度、colorDepth当前颜色设置所用的位数

20、document对象
 forms页面中所有表单的集合
  document.forms[0].name.value;//获取值
 images页面中所有图像的集合
 links页面中所有链接的集合
 anchors页面中所有锚的集合

 document.getElementById(Id)//获得指定Id对象
 document.getElementsByName(Name)//获得指定Name对象的集合

21、事件处理
 onBlur 当前元素失去焦点时触发
 onFouse 当某个元素获得焦点时触发
 onClick 鼠标点击时触发
 onDbClick 鼠标双击时触发
 onMouseDown 按下鼠标时触发
 onMouseMove 鼠标移动时触发
 onMouseOut 鼠标离开某对象范围时触发
 onMouseOver 鼠标移到某对象范围的上方时触发
 onKeyPress 键盘上的某个键被按下并且释放时触发
  <input type="button" onclick="myfunction('Hello')" value="Call function">
  <script language="javascript">
function myfunction(txt){
alert(txt);
}
</script>

22、表单元素
 通用属性:
  – form属性----获取该表单域所属的表单
– name属性----获取或设置表单域的名称
– type属性----获取表单域的类型
– value属性----获取和设置表单域的值
通用方法:
 – focus方法----让表单域获得焦点
– blur方法----让表单域失去焦点
 通用事件:
onfocus,onblur,onclick,onkeydown,onkeyup,onkeypress,onmouseover,onmouseout,onmousedown,onmouseup,onchange

23、表单元素checkbox应用
 <input type="checkbox" name="che1" onclick="checkall(this)">全选
<input type="checkbox" name="che2" onclick="unckeck()">反选</br>
 <input type="checkbox" name="hobby">看书
<input type="checkbox" name="hobby">运动
 <input type="checkbox" name="hobby">旅游
<input type="checkbox" name="hobby">发呆

function checkall(cha){
 var hobby = document.getElementsByName("hobby");
 for(var i=0;i<hobby.length;i++){
  hobby[i].checked = cha.checked;
 }
}
function unckeck(){
 var hobby = document.getElementsByName("hobby");
 for(var i=0;i<hobby.length;i++){
  if(hobby[i].checked==true){
   hobby[i].checked = false;
  }else{
   hobby[i].checked = true;
  }
 }
}

24、表单验证
<form name="form1" action="for.html" method="post"  onsubmit="return ckeckForm()">
密码:<input type="password" name="password"  onblur="password()"/><span id="p"></span><br/>
</form>

function password()
{
 var password=document.forms[0].password.value;
 var p=document.getElementById("p");
 if(password==""|| password.length==0){
  p.innerHTML="<font color=red>密码不能为空</font>";
  return false;
 }
 if(password.length<6 || password.length>12){
  p.innerHTML="<font color=red>密码必须在6---12位之间</font>";
  document.forms[0].password.value="";
  return false;
 }
  p.innerHTML="";
  return true;
}

25、正则表达式/^    $/
 *:0次或者多次
 ?:0次或者1次
 +:1次或者多次
 {}:集合[a-z]
 |:或者
 \d:数字
 \w:字母加数字
 举例:
验证电子邮箱地址:/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
验证固定电话:/^\d{3}-\d{8}|d{4}-\d{7}$/
验证身份证号码:/^\d{15}$|^\d{18}$|^\d{17}[xX]$/
 验证方式:
search():若找不到返回-1.如果能找到,返回下标索引
  email.search(正则表达式)
test():返回布尔值
正则表达式.test(email)
 if(/^\d{15}$|^\d{18}$|^\d{17}[xX]$/.test(email)==false){
  alert("身份证号码格式不正确,请重新输入");
  document.forms[0].email.value="";
  return false;
 }


servlet在服务器端运行的java程序

1、servlet的生命周期(工作原理)
 单实例多线程

1) new :当页面第一次被请求,调用构造方法,产生本Servlet唯一的实例
2) init():初始化Servlet的数据,只调用一次
3) servicer():处理请求并响应,每次请求每次调用,在生命周期调用多次
4) destroy():服务器关机重启,或者项目重新发布,只调用一次

2、Servlet步骤:
 1)编写一个Servlet
  <servlet>
      <servlet-name>helloservlet1</servlet-name>
      <servlet-class>servletTest.helloservlet1</servlet-class>//通过servlet找到字节码文件位置
   </servlet>
  <servlet-mapping>
      <servlet-name>helloservlet1</servlet-name>//服务器端通过用户访问路径得到servlet的名字
      <url-pattern>/helloservlet1</url-pattern>//用户的访问路径,可以任意写如/aaa
  </servlet-mapping>
 2)发布到Tomcat服务器
  右击servers—Add and Remove—将工程添加
 3)用户访问
  访问Servlet的URL:http://ip:port/web工程名字/<url-pattern>的值
  访问HTML或者JSP页面的URL:http://ip:port/web工程名字/WebContent下的子目录的路径

3、Servlet和CGI的区别:
 Servlet:多线程,数据不安全,进程间切换比较快,效率比较高
 CGI:多进程,数据安全,进程间切换比较慢,效率比较低

4、HttpServletRequest:

 1)获取表单参数
  getParameter(表单域的名字),返回表单中value值,String
   PrintWriter out=response.getWriter();
   String name=request.getParameter("username"); 
   out.println("Welcome "+name);
  getParameterValues(表单域的名字)String[]
  当表单参数数据不完整:非空判断
   String[] hobby=request.getParameterValues("hobby");
   if(hobby==null){
    out.println("NO HOBBY");
   }else{
    for(String h:hobby){
     out.println(h+"<br/>");
   }
 2)获取报头Header信息(了解)
  Enumeration  getHeaderNames()
     String        getHeader(报头名字)
     int           getIntHeader(报头名字)
    long         getDateHeader(报头名字)
    Enumeration  getHeaders(报头名字)

5、HttpServletResponse(用字节流)
 1)浏览器读取文件

response.setContentType(“application/pdf;charset=utf-8”);//浏览器打开文件的方式在tomcat-conf-web.xml中找
 FileInputStream fin = new FileInputStream(“C:\\Web\\HTML.pdf”);//浏览器读取文件的路径
 ServletOutputStream sos = response.getOutputStream();
 byte[] bt = new byte[1024];
 int len = 0;
 while((len = fin.read(bt))!=-1){
  sos.write(bs,0,count);
  sos.flush();
}
fin.close();
sos.close();
2)中英文乱码问题
中文格式:
UTF-8(推荐)、GB2312、GBK、GB18030
post方式提交:
request.setCharacterEncoding(“UTF-8”);//写在输出流之前,请求时
response.setContentType(“text/html;charset=utf-8”);//响应时
   
 get方式提交:
  //第一种方法:重新构造字符串(推荐)
  name = new String(name.getBytes(“ISO-8859-1”),”UTF-8”);
  //第二种方法:修改Tomcat-conf-server.xml文件,查找8080
  <Connector port=”8888” protocol=”HTTP/1.1” connectionTimeout=”20000”
  redirectPort=”8443” URIEncoding=”utf-8”/>
3)设置报头信息
 setIntHeader();
  response.setIntHeader("Refresh", 2);//页面每2秒钟刷新一次
 setHeader();
  response.setHeader("Refresh", "2;url=http://www.baidu.com");//页面两秒钟后跳转到百度首页
 setDataHeader();
   页面无缓存:
             response.setHeader("Pragma", "No-cache");//http1.0
   response.setHeader("Cache-Control", "no-cache");//http1.1
   response.setDateHeader("Expires", 0);//ie
   

 4)页面跳转(重定向和转发的区别)
  重定向:多次不同请求,地址栏发生变化,可以跳转到任意web应用下
   response.sendRedirect("http://www.baidu.com");//跳转到百度首页
   response.sendRedirect("Img");//跳转到相对路径下的Servlet页面
  转发:同一请求,地址栏不发生变化,只能在本web应用下跳转
  //方式一
  RequestDispatcher rd=request.getRequestDispatcher("Img");
  rd.forward(request, response);
  //方式二,相对于java工程的路径
this.getServletContext().getRequestDispatcher("/Img").forward(request,response);
  //方式三
  this.getServletContext().getNamedDispatcher("Img").forward(request, response);

6、格式良好的web应用:
WEB-INF:客户端禁止访问,服务器端可以访问,禁止通过URL访问
class目录:字节码文件
lib目录:第三方的jar包
web.xml文件:配置信息

可以转发访问放在WEB-INF下的文件,不可以重定向访问,因为重定向访问经过地址栏,相当于客户端的访问,放在
 WEB-INF下的文件只能通过服务器端访问,不能通过客户端访问
RequestDispatcher rd = request.getRequestDispatcher(“WEB-INF/hello.html”);
rd.forward(request,response);

7、配置文件web.xml
 <servlet></servlet>中的语句
 <load-on-startup>10</load-on-startup>//servlet加载的顺序,数值越小越先加载
  举例:
<servlet>
      <servlet-name>HelloWordservlet1</servlet-name>
      <servlet-class>servletTest.helloservlet1</servlet-class>//通过servlet找到字节码文件位置
   <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
      <servlet-name>Helloservlet1</servlet-name>
      <servlet-class>servletTest.helloservlet1</servlet-class>//通过servlet找到字节码文件位置
    <load-on-startup>2</load-on-startup>
 </servlet>
 servlet-name:Servlet名字
 servlet-class:Servlet的完整路径名
 url-pattern:用户访问路径
<url-pattern>*.do</url-pattern>//访问路径可以自己设置,说明任意路径+.do及可以访问页面
 init-param:初始化参数(了解写在一个<servlet></servlet>中),只能在本Servlet中使用,只能在init方法中调用,通过ServletConfig的getInitParameter()方法获取参数的值
 context-param(了解与<servlet></servlet>并列):所有的Servlet均可以使用,任何方法中都可以调用,通过ServletContext的getInitParameter()方法获取参数的值,一般放数据库的参数;
<context-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</context-param>
protected void doGet(HttpServletRequest request, HttpServletResponse response){
 String driver=this.getServletContext().getInitParameter("driver");
 System.out.println("driver:"+driver);
}

 错误信息友好页面的处理
  <error-page>
  <error-code>404</error-code>//错误码404路径错误、500空指针错误
  <location>/404.jsp</location>
  </error-page>
  <error-page>
  <exception-type>java.lang.ArithmeticException</exception-type>//错误信息的处理
  <location>/exception.jsp</location>
  </error-page>

 exception.jsp文件中写
  <body>
<h1>
Error!&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </h1>
  </body>

8、打包 .war包
 jar –cvf 包名.war*

9、过滤器Filter
 过滤器的生命周期
1) new Tomcat服务器一启动的时候产生过滤器对象
2) init()初始化参数数据,只调用一次
3) doFilter()每次请求每次调用
4) destroy()只调用一次,服务器关机重启等之前
过滤器的实现步骤(与在web.xml中的书写顺序有关,请求时123,响应时321)
 <filter>
     <filter-name>MyFilter</filter-name>
     <filter-class>WebXml.Servlet.MyFilter</filter-class>//过滤器路径
  </filter>
   <filter-mapping>
      <filter-name>MyFilter</filter-name>
     <url-pattern>/*</url-pattern>//过滤的文件类型,过滤所有文件,*.html过滤所有html文件
</filter-mapping>
chain方法必须在doFilter方法中实现
  System.out.println("doFilter2...");//请求时执行
  chain.doFilter(request, response);//调用下一个过滤器或者资源
 System.out.println(2);//响应时执行
过滤器的应用(中英文乱码问题)
  在doFilter方法中写下方代码即可
  HttpServletRequest  request=(HttpServletRequest)req;//转换格式
  HttpServletResponse  response=(HttpServletResponse)res;
  request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
  chain.doFilter(request, response);
Servlet要是安全的,实现SingleThreadModel接口,该接口已过时,面试时会问

10、Servlet状态管理:
 http协议:无状态
 客户端状态管理:数据不安全,减轻了服务器的负担
  Cookie:最多4kb
   永久性cookie:setMaxAge(int seconds)
   暂时性cookie(默认):浏览器关闭就消失
  隐藏域hidden
  查询字符串:get方式提交 ? &
  PrintWriter out = response.getWriter();
  Cookie[] cooks = request.getCookies();

  if(cooks==null){
   for(int i=0;i<5;i++){
    Cookie cookie = new Cookie("cookieName:"+i,"cookieValue"+i);
    cookie.setMaxAge(24*3600);
    response.addCookie(cookie);
   }
   out.println("<h1>Set Cookies OK</h1>");
  }else{
   out.println("<table border=\"1\" align=\"center\" width=\"80%\" cellspacing=\"0\">");
   out.println("<tr><th>cookieName</th><th>cookieValue</th></tr>");
   for(int i=0;i<5;i++){   out.println("<tr><td>"+cooks[i].getName()+"</td><td>"+cooks[i].getValue()+"</td></tr>");
   }
   out.println("</table>");
 服务器端状态管理:数据安全,加重了服务器的负担
  HttpServletRequest:同一请求范围内有效,转发可以读取,重定向不可以,因为重定向不是同一个request对象
   setAttribute(String name,Object obj);//存储数据
   getAttribute(String name);//读取数据
   removeAttribute(String name);//删除数据
 getAttributeNames(String name);
 代码举例:
   request.setAttribute("username", "admin");//<==>String username="admin" ;
 request.getRequestDispatcher("ShowRequestAttribute").forward(request, response);
 ShowRequestAttribute文件代码
   PrintWriter out = response.getWriter();
   String username = (String) request.getAttribute("username");
 out.println("<font color=\"pink\">username:"+username+"</font>");
HttpSession同一会话范围内有效
Session工作原理:
客户端发送请求,服务器端为客户创建一个session对象,服务器通过cookie返回一个sessionId给客户端,以后客户端再次发送请求带着sessionId,服务器端根据发送过来的sessionId返回session对象

getSession()与getSession(boolean)的区别:
1)getSession();与getSession(true)相同,如果现在已有session对象,使用已有的session对象,如果没有session对象,则新建一个
2)getSession(boolean); getSession(false) 如果现在已有session对象,使用已有的session对象,如果没有session对象,则返回null
 一般通过暂时性cookie将sessionId送到客户端,但是客户端浏览器禁止cookie,则需要通过URL重写
 Servlet线程安全:实现SingleThreadModel接口
  encodeURL(String url);
  encodeRedirectURL(String url);//重定向的重写
  PrintWriter out = response.getWriter();
  HttpSession session = request.getSession();
  out.println("<h1>Session Info</h1>");
  out.println("isNew:"+session.isNew()+"<br/>");
  out.println("SessionId:"+session.getId()+"<br/>");
  out.println("CreateTime:"+session.getCreationTime()+"<br/>");
  out.println("CreateTime:"+new Date(session.getCreationTime())+"<br/>");
  out.println("LastAccessedTime:"+new Date(session.getLastAccessedTime())+"<br/>");
  out.println("<br/>");
  out.println("<h1>Request Sessioninfo</h1>");
  out.println("SessionId:"+request.getRequestedSessionId()+"<br/>");
  out.println("FromCookie:"+request.isRequestedSessionIdFromCookie()+"<br/>");
  out.println("FromURL:"+request.isRequestedSessionIdFromURL()+"<br/>");
  out.println("isValid:"+request.isRequestedSessionIdValid()+"<br/>");
  out.println("<a href="+request.getRequestURI()+">test</a><br/>");
out.println("<a href="+response.encodeURL(request.getRequestURI())+">URL</a><br/>");
   session的会话时长:
1) setMaxInactiveInterval(int interval)//秒
2) tomcat服务器的web.xml
<session-config>
  <session-timeout>30</session-timeout>//分钟
</session-config>
   session对象的销毁
1) 会话自然过期
2) invalidate()立即销毁session对象;注销时能用到
3) 关闭浏览器,sessionId马上销毁,但是session对象仍然会在服务器端存活一段时间
session中存储的数据:同一个会话范围内有效
SetAttribute(String name,Object obj);存储数据
getAttribute(String name);读取数据
removeAttribute(String name);删除数据
getAttributeNames();
ServletContext:所有用户共享,并且与web应用有相同的生命周期,做在线人数统计
  response.setContentType("text/html;charset=utf-8");
  PrintWriter out=response.getWriter();
  ServletContext application=this.getServletContext();
  Integer count=(Integer)application.getAttribute("count");
  if(count==null){
   application.setAttribute("count", 1);
  }else{
   count++;
   application.setAttribute("count", count);
  }
  out.println("在线人数为:"+application.getAttribute("count"));

JSP(java Server page)Java服务器页面
1、 Servlet:看做是嵌入HTML标签的类(数据的控制)

JSP:看做是嵌入Java代码的HTML(数据的显示)

2、 JSP的工作原理:
当页面第一次被请求时,把Java代码转换成Servlet,然后响应回去,之后请求,如果页面没有变化,直接响应就可以,如果Servlet发生变化,再请求时,重新转换成Servlet,然后再响应

3、 JSP转换将文件放在Tomcat的work文件下

4、 JSP的经典语法:
注释:<%-- --%>浏览器不可见
  <!-- -->查看源文件,浏览器可见
声明:<%! %>声明方法和成员变量
脚本段:<% %>句子和局部变量,如if循环语句
表达式:<%= score %>输出到浏览器,等价于<%out.println();%>
指令:<%@ %>
迭代语句:跨脚本段 遇到Java代码跳入脚本段,遇到HTML标签跳出脚本段
普通语句
<%
int score=12;
if(score==100){
  out.println("<h1><font color=\"red\">去公园玩</font></h1>");
}else{
  out.println("<h1><font color=\"blue\">在家反省</font></h1>");
}
%>
迭代语句
<%
int score=100;
if(score==100){
%>
<h1><font color="red">去公园玩</font></h1>
<%
}
else{
%>
<h1><font color="blue">在家反省</font></h1>
<%} %>

5、page指令  设置当前页面的信息
language:语言
contentType:设置当前页面的编码格式,默认为ISO-8859-1
pageEncoding:设置当前页面的编码格式,默认为ISO-8859-1
import:导包 可以出现多次,如果写在一个import中,中间用逗号间隔
session:当前页面是否有session对象,默认为true
extends:JSP页面生成的Servlet类的父类
buffer:表示缓冲器大小,默认8kb
autoFlush:默认为true是否自动刷新缓冲区
isThreadSafe:是否是线程安全的,默认为true
isELIgnored:默认为false不忽略,是否忽略EL表达式
isErrorPage:默认为false,页面是否为错误页面
errorPage:后面跟错误页面的URL路径
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" buffer="1kb" import="java.sql.Connection" autoFlush="false" isELIgnored="false"%>

6、include指令
  include指令(静态包含)与include动作(动态包含)的区别
  include指令:只转换成一个Servlet,转换成Servlet时就包含进来,不可以使用表达式
  <%@include file=”header.jsp”%>
  include动作:转换成多个Servlet,响应时包含进来,可以使用表达式
  <jsp:include page=”<%=header.jsp%>”></jsp:include>

7、taglib指令JSP三个指令:page、include、taglib

8、JNDI:数据库连接池
在web应用下的META-INF下新建context.xml配置文件
<?xml version=”1.0” encoding=”UTF-8”?>//告诉我们是一个xml文件
<Context>
<Resourse  name=”jdbc/mysourse”     
auth=”Container” 
   type=”javax.sql.DataSourse”
   driverClassName=”oracle.jdbc.driver.OracleDriver”
   url=” jdbc:oracle:thin:@YLMF123-3131857:1521:orcl”
   username=”scott”
   password=”tiger”
   maxActive=”30”
   maxIdle=”5”
   maxWait=”10000”
 />
</Context>
//name表示Resourse资源的JNDI的名字
//auth表示这个资源的管理者Application(web应用创建和管理Resourse)、Container(容器创建和管理Resourse)
//type表示Resourse所属的Java类
//maxActive数据库在此服务器上打开的最大连接数
//maxIdle数据库在此服务器上打开的最小连接数
//maxWait最大的等待时间,毫秒
使用:
Context context=new InitialContext();
DataSource ds=(DataSource)context.lookup("java:comp/env/jdbc/mysource");
conn=ds.getConnection();

9、jsp下的转发
<jsp:forword></ jsp:forword>

10、jsp的9个内置对象
 1)request       HttpServletRequest
 request.getAttribute(“”);
 request.getParameter(“”);
 2)response      HttpServletResponse
 response.sendRedirect(“”);
 response.encodeURL(“”);
 response.getWriter();
 3)session       HttpSession
  session.setAttribute(“”);
 4)application  ServletContext
  application.setAttribute(“”,””);
  application.getAttribute(“”);
 5)config        ServletConfig
  config.getInitParameter(“”);
 6)out 默认值为null         JspWriter
 7)page 默认值为this,指的是当前Servlet       Object    
  8)exception    Throwable是一个类,与exception是继承关系
  9)pageContext PageContext
   pageContext:
1) 产生其他内置对象
2) 存储page作用域范围内的数据,以及其他作用域(request、session、application)范围内的数据
10、JSP四个领域范围(作用域范围)
 1)page:当前页面有效
 2)request:同一请求范围内有效
 3)session:同一会话范围内有效
 4)application:web应用范围内有效

11、JavaBean:是一种规范,是一种可移植的组件

12、成为JavaBean的规范

 1)必须是公开类
 2)必须是无参的构造方法
 3)属性xxx必须是getXxx或者SetXxx命名
 4)实现Serializable接口
 5)该bean放在某个包中(前三个条件必须满足)
 程序如下:
 public class Users implements Serializable{
private int id;
private String username123;
private String password;
public int getId() {
 return id;
}
public void setId(int id) {
 this.id = id;
}
public String getUsername() {
 return username123;
}
public void setUsername(String username) {
 this.username123 = username;
}
public String getPassword() {
 return password;
}
public void setPassword(String password) {
 this.password = password;
}
 }

13、用jsp对bean进行赋值和输出
<jsp:useBean>相当于new一个对象
<jsp:setProperty>赋值
<jsp:getProperty>取值
程序如下:
<body>
<jsp:useBean id="u" class="com.neusoft.bean.Users" scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="u" />
//属性的名字应与表单域中的name相同,可以用*通配符
//否则用以下代码
<jsp:setProperty property="id" name="u" param="id"/>//相当于u.setId(12);
<jsp:setProperty property="username" name="u"  param="name"/>
<jsp:setProperty property="password" name="u"  param="pwd"/>
Id:<jsp:getProperty property="id" name="u"/><br/><!-- u.getId() -->
Name:<jsp:getProperty property="username" name="u"/><br>
Password:<jsp:getProperty property="password" name="u"/>
</body>

14、EL表达式:通常与JSTL一起使用
1)语法:${} 花括号里面可以使用.或者[]
 如:${requestScope.user.id }
2)有些情况必须使用[]:数组、List集合、Map集合、变量中有特殊字符(如na$me需要用[“na$me”])
数组:${requestScope.arr[1] }<br>
List集合:${requestScope.list[0].username }<br>
Map集合:${requestScope.map["m2"].password}
3)el的隐含语法:
 <%=request.getParameter("name") %>//取表单域的值
${param.name }//取表单域的值
${header.host }//获得报头信息,主机名字
${cookie }//获得cookie
4)运算符:+、-、*、/(div)、%(mod)
 ${18 div 10} //输出1
 ${2==4} //false  
 ${2<4 && 5>3} //true

15、JSTL(JSP Standard Tag Library)标签库
1)导包:

 在WEB-INF的lib导入standard-1.1.2.jar包(现成的)
在jar包下的META-INF的c.tld找到uid路径,复制粘贴到
<%@taglib uri=”复制” prefix=”c”%>
2)out 标签 输出
<body>
<jsp:useBean id="user" class="com.neusoft.el.User" scope="request"></jsp:useBean>
<jsp:setProperty property="id" name="user" value="12"/>
<jsp:setProperty property="username" name="user" value="abc"/>
<jsp:setProperty property="password" name="user" value="123"/>
<!-- out标签 -->
<c:out value="admin"></c:out>
EL表达式:${requestScope.user.password }
out标签:<c:out value="${requestScope.user.password }"></c:out>
default属性:<c:out value="${name}" default="qqq"></c:out>
//value对象存在,即输出,不存在即返回default设置的默认值
<%
String str="<address>";//xml标签
request.setAttribute("str", str);
%>
//是否屏蔽xml标签,默认值为true,即屏蔽
escapeXml标签:<c:out value="${str }"   escapeXml="false"></c:out>
</body>
3)set标签 声明变量
 <c:set var=”u” value=”guest” scope=”session”></c:set>
 Set标签:${sessionScope.u}//输出guest
 //针对JavaBean的属性,target指的是JavaBean的id
 <c:set target=”${user}” property=”username” value=”John”></c:set>
 ${user.username}
4)remove标签 删除
 <c:remove var=”u”>
5)if标签 判断,只能放一条if语句
 <c:set var=”age” value=”2300” scope=”request”></c:set>
 <c:if test=”{${age<0 || age>200}”>年龄不合法</c:if>
6)choose标签 多条件判断
 <c:choose>
 <c:when test=”${age<0 || age>250}”>年龄不合法</c:when>
 <c:when test=”${age<50 || age>250}”>中年人</c:when>
 <c:otherwise>老年人</c:otherwise>
 </c:choose>
7)forEach标签 遍历数组、集合
 //item:集合的名字
 //var:遍历集合是所遍历到的元素的名字
 //begin=“1” end=“4”部分遍历
 //step 步长值 默认为1
 //varStatus 状态值变量 index下标 count第几个元素
 <!—遍历数组 -->
 <c:forEach items=”${arr}” var=”item” varStatus=”aa”>
 ${item}||${aa.index}||${aa.count}||${aa.first}||${aa.last}
 </c:forEach>
 <!-- 遍历List集合 -->
 <c:forEach items=”${list}” var=”item”>
 ${item.id}||${item.username}//list集合里面是user对象
 </c:forEach>
 <!-- 遍历Map集合 -->
 <c:forEach>
${item.key}||${item.value.username}//value是user对象
 </c:forEach>

16、MVC架构模式(可重用性、可维护性)
发送请求,Servlet(属于控制层)负责处理请求,jsp只负责显示(属于View视图层),JavaBean负责逻辑部分
M(JavaBean):数据的逻辑,与数据库的交互逻辑(dao层和service层)
V(jsp):数据的显示
C(Servlet):数据的控制
a. 处理请求
b. 根据请求,找到某个业务逻辑处理
c. 根据业务逻辑的结果,找到某个视图响应回去

Ajax(Asynchronous JavaScript And XML)
1、步骤

var xmlhttp;
function val{
 1)获取表单数据

var username = document.getElementsByName(“username”)[0];//得到一个数组
2)创建XMLHttpRequest对象
if(window.XMLHttpRequest){//除了ie7以下版本,浏览器中都有XMLHttpRequest对象,如火狐、搜狗等
 xmlhttp  = new XMLHeepRequest();
}else if(window.ActiveXObject){//ie6,ie6.5
 xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
3)建立与服务器的连接
if(xmlhttp){//判断是否创建成功
xmlhttp.onreadystatechange = callback;//注意后面不加括号,设置状态变化时调用callback方法
xmlhttp.open(“GET”,”GetServlet?,true);
//method:提交方式,URL:提交到的目标页面,async:是否异步(true表示异步)
//POST方式提交
xmlhttp.open(“POST”,”POSTServlet”,true);
xmlhttp.setRequestHeader(“Content-Type”);
xmlhttp.send(“username=”+username.value);
4)发送请求
xmlhttp.send(null);
}
}
5)编写回调函数,用于存储服务器响应回来的数据
function callback(){
 if(xmlhttp.readystate==4){
if(xmlhttp.status==200){
var text = xmlhttp.responseText;//获取服务器的数据
   var s = document.getElementById(“s”);
   s.innerHTML = “<font color=red>”+text+”</font>”;
}
}
}

2、XML可扩展的标记性语言
格式良好的XML文件
1) 大小写敏感
2) 标签要求正确嵌套
3) 属性值必须被“”修饰
4) 标签必须成对出现
5) 必须要有根元素<?xml version=”1.0”?>

3、DOM(Document Object Model):文档对象模型


猜你喜欢

转载自blog.csdn.net/shine_a/article/details/71194284