WEB应用开发技术

www相关概念:

web服务器:

                提供网上信息浏览,处理http请求

                软件+硬件,装了服务器软件的一个高性能计算机

JavaScript:

                脚本语言,用于客户端网页,提供动态的交互功能

开发模式:

                CS开发模式:

                                (client客户端/server服务器)

                                   自己的电脑端->开发公司的电脑端(数据库应用服务器)   

               BS开发模式:

                                (browser浏览器/server服务器)

                                   浏览器->web服务器(装载不同站点,baidu,新浪)->数据库server

              异同:

                        负载:CS:clients完成很多功能,server负载小

                                  BS:打开网页-输入网址-web服务器-数据库server-返回页面

                                        server负载大,受网速限制

                        维护:CS:不同电脑不同版本,客户端开发代价大

                                  BS:只需要一份,代价小

                        安全:CS:

                                  BS:易于截取数据-趋势

Internet、Web、网络的三大基石(html,http,url)

              1.    Internet:物理网络,电脑+物理线路、设施

              2.    Web:Internet上的服务(网站、邮箱、ftp服务)

              3.    html 超文本标记语言(hyperText Markup Language)

                     <html> xxxx 用于网页上的排版

              3.1.  http 超文本传输协议(hyperText Transfer Protocol)

                     数据传输时的格式,浏览器和服务器交互时,数据时如何传输的

                     /1.request:/

                     |      1            2            3            4            5                   6     |

                     |       g             1.0          zh           alive       host_ip          9

                            【传输方式】:

                                   get(数据拼接在网站后https://baidu.com/s?ed=浙江工商大学)

                                   post (流的方式处理)

                            【http版本】:1.0版本/1.1版本....

                            【语言accept-language】:zh-cn

                            【连接方式connection】:keep-alive

                            【host】:192.168.1.3:80(需要连接的电脑)

                            【content-length内容长度】:“ed=浙江工商大学” 九个字

                     /2.response/

                            【http版本】:1.0版本/1.1版本....

                            【状态码】:404访问不到 、200 访问成功、 500 服务器内部错误 、503

                            【content-type内容类型】:text/html

                            【content-length内容长度】:1000

                            <html>

                                          浙江工商大学

                            </html>

                     浏览器                                       request:【https://baidu.com/s?ed=浙江工商大学】

                         ||     ------------------>管道input/output<--------------- ||返回response页面

                     web服务器(装载不同站点,baidu,新浪)       tormcat解析request请求,到达访问端口

                         ||                                                                                         ||

                     数据库server                                                  注册信息更新,返回

              4.URL

              https://baidu.com:80/s?ed=浙江工商大学

              【baidu.com】:ip

              【80】:默认端口

              【s】:资源->图片/index.jsp/jpg

              【?】参数:       【ed】参数名字

                                   【=浙江工商大学】参数值

【jsp语法】:

java server page=html<body>+java程序片段<%%>+标签<%@ %>>

jsp运行原理:

jsp->tomca(容器)

——————————————————————————————

jsp在第一次被访问的时候

    |

java文件

    |

class文件(java程序)

在tomcat文件夹中的webapp和work中

首次运行项目时会出现项目文件夹,首次运行jsp页面时work其中出现java文件和class文件

scriptlet脚本

1. 1<%!  %>    ​定义脚本

脚本:在一个页面中如何写

    -定义变量属性int a;

    -定义方法

!一般将这些对象写在javaresources中->vo=值对象,bean:java bean =value bean,业务bean: insert/delete/update/select ,所以一般不用;

!”a=9“是错误的写法,因为jsp页面中这条脚本会被保存成java文件,在文件中会被存放在class中helloword_jsp作为一个类,而类中不可以直接赋值或调用

​——————————————

1.2  <%= %>  ->${}

    -值

    -表达式

<%=3%>jsp这条脚本在保存后的java文件中会变成 ”out.print(3)“

——————————————

1.3  <% %> ->servlet

    ​-java代码

    ​-sql

不可以在内部定义函数

这条脚本在保存后的java文件中会变成在_jspservice{}方法内的代码,变成函数内部的代码,因而不能再函数的内部继续定义函数

1.4 异常处理

try()catch(Expection e){e.printStack();}

指令

指令:页面如何配置/两个页面之间(包含)

1. page:页面<%@ page ?%>

[ language="java" ]:页面使用的脚本的语言:java

[ contentType="text/html charset=UTF-8" ]:浏览器如何解析:文本/html utf-8

[ pageEncoding="UTF-8" ]:服务器:jsp-java-class  以utf-8的形式去读

[ isThreadSafe="true" ]:多线程安全,支持并发

[ isErrorPage="false" ]:当前jsp页面是不是一个错误页面(其他页面发生错误时,是否可以跳转到当前页面)

[ errorPage="" ]:当这个页面出错时,会跳转到哪个页面

[ info="" ]:某些服务器可以读取的信息

[ session="true" ]:支持session

[ autoFlush="true" ]:自动刷新

[ buffer="8kb" ]:?

[ import="" ]:页面导包语句-->可以出现多次

——————————————————

2. include:包含

[ 静态 ]:<%@ include file="c.jsp"%>

 ​1. 包含其他文件和C中的“include<studio.h>”相同

2. jsp->java时将两个jsp合并为一个,再转化为java文件

3. 功能:静态复用,页面是静态的内容是固定的(一些页面的最上面的按钮 header 和最下面的模块 footer )

4. 注意:非法出现多次出现的'contentType'具有不同的值->由于两个文件最开始都有配置信息<%@  %> ,造成。。。,需要将其删去,只留下<body>里面的内容。

[ 动态 ]:<jsp:include page="">

两个文件会各自转为java文件

——————————————————

3. taglib 标签库:jstl / mvc

动作

【动态包含】:

<jsp:include page ="Math.jsp" flush=“true”>

       flush指定页面是否要更新。

【传递参数】

<jsp:param value="gxy" name="name"/>

通过下面方式输出:

hello.jsp:

<jsp:include page ="Math.jsp">(只有动态包含才可以传递参数)

       <jsp:param value="gxy" name="name"/>

       <jsp:param value="18" name="age"/>

</jsp:include>

Math.jsp:

<% String name= request.getParameter("name"); %>

<% String age= request.getParameter("age"); %>

name:<%=name %><br/>(<br/断行符>)

age:<%=age %>

---------------------------------------------------------------

当name=“xx”中有多个name=xx的,需要通过数组进行遍历:

Math.jsp

<% String[] vls = request.getParameterValues("name");

       for(String v : vls){

             

%>

      

name:<%=v %><br/>

<%

       }

%>

【以标签的方式创建对象】:

【创建对象】<jsp:useBean>

       [useBean.jsp]:

<jsp:useBean id="stu1" class="com.gxy.vo.student"></jsp:useBean>

id

       [com.gxy.vo.student.class]:

package com.gxy.vo;

public class student {

       String name;

       int age;

       public student() {

              // TODO Auto-generated constructor stub

       }

       public String getName() {

              return name;

       }

       public void setName(String name) {

              this.name = name;

       }

       public int getAge() {

              return age;

       }

       public void setAge(int age) {

              this.age = age;

       }

      

}

java bean:

       1.get/set函数

       2.有无参的构造函数

       3.public的类

usebean:使用javabean

【设置属性值】<jsp:setProperty>

<jsp:setProperty property="name" name="stu1" value = "mac"/>

name设置的对象名->id

property:属性名

value:属性值

【取值】<jsp:getproperty>

name:<jsp:getProperty property="name" name="stu1"/><br>

age:<jsp:getProperty property="age" name="stu1"/>

       ||

       ||相当于:

       V

<%

       student stu2 = new student();

       stu2.setName("gxxxx");

       stu2.setAge(18);

%>

name:<%=stu2.getName() %>

age:<%=stu2.getAge() %>

【服务器端跳转】

<jsp:forward>

会把request原样传回去,跳转后页面依旧是第一个页面的地址

 o                                                                                                                         o

-|-   —request—>  页面1 --request-->页面2--request-->页面3—response—>   -|-

/ \                                                                                                                         / \

【客户端跳转】

response.sendRedirect()

跳转后浏览器地址栏变化,地址栏会改变为第二次请求的URL。

【内置对象】:

作用域:(变量的有效范围)page/request/response/session

程序处理流程:

接收数据->跳转处理页面(数据封装)->跳转结果显示页面

9大内置对象:

内:(tomcat容器)置:创建 好的对象

1.【 out :页面输出(小的网页)】

javax.servlet.jsp.JspWriter out = null;

<%=%>/<%%>

out.print out.write

作用域:page

每个jsp页面都有一个独立的out对象,互不干扰

--------

<%

out.print("gxy");

out.println("nihao"); 在网页上不起作用->使用"out.println("nihao"+"<br/>");"break line

out.write("ggg");

        out.print("<h1> error <h1>");

%>

-------

2. 【request 至少两个页面之间的数据传递(共享)+form表单(包裹/数据提交的单位)】

       final javax.servlet.http.HttpServletRequest request

        用处:       获取数据String name = request.getParameter("name");

                     存取数据request.setAttribute("u", u);/User u = (User)request.getAttribute("u");

                     跳转:服务器:request.getRequestDispatcher("show.jsp").forward(request, response);

      作用域:request

form---封装成request-->form_handle.jsp--->show.jsp--response->form.jsp

       生命周期: born destory

request对象的生命周期是针对一个客户端(说确切点就是一个浏览器应用程序)的一次请求,当请求完毕之后,request里边的内容也将被释放点 。

form:

    数据类型:文本框/单选/复选框/文本框/h5/日历/滑块

--------

1. form.jsp:

---------

action:指定处理数据的页面

method=“get/post”数据提交方式

              get:把数据凭借url中转递,和url编码一致

              如:http://localhost:8080/GXY_homework/form_handle.jsp?                 name=gxy&pwd=12&female=on&hb=sj&grade=89

             

              post:不会出现在url中的以流的方式独立编码

                     1.相对安全

                     2.长度到:比较大图片/文件post

---------

<body>

<form action="form_heandle.jsp" method="get" name="form1">

<input type="hidden"/>

name:<input type="text" name="name"/><br/>

pwd:<input type="password" name="pwd"/><br/>

sex:<label>男<input type="radio" name="sex" value="male"/></label>

<label>女<input type="radio" name="sex" value="female"/></label><br/>《

habbit: 睡觉<input type="checkbox" name="hb" value="sj"/>

吃饭<input type="checkbox" name="hb" value="cf"/>

玩手机<input type="checkbox" name="hb" value="wsj"/><br/>

<input type="date"/>

分数:<input type="range" name="grade" max="100"/>

<input type="color"/><br/>

<input type="submit" value="提交">

</form>

</body>

---------

提交后:

http://localhost:8080/GXY_homework/form_handle.jsp?name=gxy&pwd=12&female=on&hb=sj&grade=89

”name=on&name=on&name=on“作为数组提交

------------

2. User.java:

------------

public class User {

       private String username;

       private String sex;

       private String[] habits;

       private String pwd;

       private int grade;

       public User() {

              // TODO Auto-generated constructor stub

       }

       public String getUsername() {

              return username;

       }

       .......

------------------

3.form_handle.jsp

------------------

<%

//name=gxy&pwd=12&female=on 接收数据

       String name = request.getParameter("name");

       String pwd = request.getParameter("pwd");

       String sex= request.getParameter("sex");

//hb=sj

       String[] hbs = request.getParameterValues("hb");

//grade=89

       int grade = Integer.parseInt( request.getParameter("grade"));

//step2:封装

       User u = new User(name, sex, hbs, pwd,grade);

//step3:处理

       u.setGrade(grade+10);

//step4: 显示数据,跳转显示

      

       //跳转:是否带值

       //是:服务器跳转:<jsp:forward page=""/>

              //request.getRequestDispacher("跳转的页面").forward(request,response);

              //存值

             

       request.setAttribute("u", u);

request.getRequestDispatcher("show.jsp").forward(request, response);

      

       //否:客户端跳转vs重定向

              //response.sendRedirect("重定向的页面");

//if("gxy".equals(u.getUsername())&&"123".equals(u.getPwd()))

       //{

       //    response.sendRedirect("good.jsp");

       //}

       //else

       //{

       //    out.print("hahaha");

       //    response.sendRedirect("bed.jsp");

       //}



%>

----------

4. show.jsp

----------    

   <%

              //step1:获取数据

              User u = (User)request.getAttribute("u");

              //step2:数据处理

       %>

       <table>

              <tr>

              <td>用户名:</td><td><%=u.getUsername() %></td>

              </tr>

              <tr>

              <td>pwd:</td><td><%=u.getPwd() %></td>

              </tr>

       </table>

----------

5. good.jsp

----------

<body>

<h1>WELCOME GXY'S HOME</h1>

</body>

---------

6. bed.jsp

---------

       <h1>失败!!!</h1>

3.【response 返回值-客户端跳转】

final javax.servlet.http.HttpServletResponse response

--------------show.jsp--response->form.jsp--------

response.sendRedirect("重定向的页面");

对象的内部方法:

request.setCharacterEncoding()

这个方法用于设置从客户端接收到的请求数据的字符编码。在POST请求中,表单数据或上传的文件通常会有字符编码(如UTF-8、ISO-8859-1等)。如果客户端和服务器之间的字符编码不一致,就可能导致乱码问题。

        request.setCharacterEncoding("UTF-8");

response.setContentType( )

这个方法用于设置HTTP响应的内容类型和字符编码。内容类型(MIME类型)告诉客户端响应数据的类型(如HTML、纯文本、JSON、图片等),而字符编码则告诉客户端如何解释这些数据。

response.setContentType("text/html;charset=UTF-8")

4.【session 跟踪会话】

会话:request<->responce

在一段时间(MaxInactiveTime)内,与某个特定的服务器(网站)之间的连续的request<->responce

类:javax.servlet.http.HttpSession session = null;

作用:数据在不同页面之间的共享

       a->b 一个request ;     b->a 另一个request

       a->b->c requst.getRequestDispacher("C").forward(request,response)

对象的内部方法:

session.setAttribute(key,object)

session.getAttribute(key,object)

session.removeAttribute(key) 释放->服务器需要内存,且session作用域比较大相当于全局变量

session.setMaxInactiveInterval(30*1000*60) //ms 设置不活跃时间,存活时间,两次交互的间隔

Tomcat默认的会话时间为30分钟

session.getId()判断session是否更新

session.isNew ( )    当关闭所有的浏览器,再重新登录的时候session.isNew()才会是true

                            当每次都新打开一个浏览器用不同的用户登录,session.isNew() 是为false。session.getId()是不变的,。

session.invalidate( ) 初始化/退出登录的功能

生命周期:

会话作用域,当用户首次访问时,产生一个新的会话,以后服务器就可以记住这个会话状态。生命周期:会话超时,或者服务器端强制使会话失效。

打开一个浏览器请求一个网站的页面后,Session开始,当session超过时间限制(一般是20分种)后,session注销而失效或是人为使用session.invalidate();使用session失效。

详见:Gxy_homework 的project

购物车相关;

<%@page import="com.gxy.vo.User"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<%

       User user =(User) session.getAttribute("user");

       if(null==user){

%>

<form action="login_handle.jsp" method="post">

       用户名:<input type="text" name="username"/><br/>

       密&nbsp;码:<input type="password" name="passward"/><br/>

       <input type="submit" value="登录">

<%}else{ %>

你已经登录!

用户名:<%=user.getUsername() %><br/>

密&nbsp;码:<%=user.getPwd() %><br/>

<a href="show.jsp">商品列表</a><br/>

<a href="quit.jsp">退出登录</a>

<%} %>

</form>

</body>

</html>

5.【pagecontext 路径拼贴】

page的上下文:servlet

servlet的上下文:application

final javax.servlet.jsp.PageContext pageContext;

javax.servlet.jsp.PageContext _jspx_page_context = null;

(SeverletRequest/response)

              //路径

       pageContext.getResponse();

       pageContext.getRequest();

(httpServletRequest)             

              //获取根目录

       request.getContextPath();

<!--form action="<%=request.getContextPath() %>/UserServlet?method=checkUser" method="post"-->

              ||相当于

       HttpServletRequest hsr=(HttpServletRequest)pageContext.getResponse();

       hsr.getContextPath();

------------------

 Path_print.jsp

---------------------------------------------------

path:<%=request.getContextPath() %>

-> path:/GXY_homework        (对应的是webcontent这个文件作为根目录-新建时定义的可以修改)

pageContextPath:<%=((HttpServletRequest)pageContext.getRequest()).getContextPath()%>

-> pageContextPath:/GXY_homework

---------------------------------------------------

application = pageContext.getServletContext();

config=pageContext.getServletConfig();

out=pageContext.getOut();

session=pageContext.getSession();

得到其他的内置对象

通过pagecontext传页面上的pageContext传入java类中requestServletRequest=pageContext.getRequest();

ServletConfig=pageContext.getServletConfig();

String name = (String) ServletRequest.getAttribute("gxy");

6.【application 在线人数统计】

在服务器启动时创建、每个应用一个application

final javax.servlet.ServletContext application;

新的session创建,链接到服务器,就能统计了

-----------------

visitor_cnt.jsp  (需要将浏览器关闭才会+1)

----------------------------------------------------------------------------

<%!

       synchronized int visitorplus(Object vc){

       int cnt=(Integer)vc+1; 

       return cnt;

}

%>

<%if (session.isNew()){

       Object vc = application.getAttribute("vistorcnt");

       if(null == vc){

              //第一个访问

              application.setAttribute("vistorcnt", new Integer(1));

       }

       else{

              //临界区->同步控制

              int cnt=visitorplus(vc);

              application.setAttribute("vistorcnt", new Integer(cnt));

       }

       }%>
在线访问人数:<%=application.getAttribute("vistorcnt")%>

-----------------------------------------------------------------------------

7.【exception】页面上的异常

--------------

expection.jsp

-------------

<%@ errorpage="error.jsp"%>

---------

error.jsp

----------

error:<%=exception.tostring( )%>

------------------------------

跳转到error后地址还是expection.jsp这个地址

8.【page】==this

final java.lang.Object page = this;

9.【config】==web.xml

final javax.servlet.ServletConfig config;

【数据传递】

1.form

2.超链接<a href=""></a>

3.type="hidden"

4.request.getRequestDispacher().forward(request,response)

【乱码处理】                                                                                      

//post提交方式

       request.setCharacterEncoding("utf-8");

      String name1=request.getParameter("username");

       String pwd = request.getParameter("passward");

//get处理方式

      String name1=request.getParameter("username");

       String pwd = request.getParameter("passward");

       String name = new String(name1.getBytes("iso-8859-1"),"utf-8"); 

【记住密码+自动登录】 

【cookie技术】

浏览器端一个小文件 <4k

每个站点存放20个cookie,每个站点只有自己的站点里面才能访问

------创建------

new cookie(key,value)

cookie.getName() --key

cookie.getValue() --value

------写入硬盘---

response.addcookie()

Cookie[] cks = request.getCookies()

-----生存期-----

default-浏览器的关闭就结束

cookie.setMaxAge(60*60*3)-延长生存期

----------

login.jsp:

----------

<body>

<%

       Cookie[] cks = request.getCookies();

       if(null!=cks){

              for(Cookie ck:cks){

              System.out.println("cookies"+ck.getName()+":"+ck.getValue());

              }

       }

%>

 <%

       Cookie[] cks = request.getCookies();

       String username="";

       String userpwd="";

       if(null!=cks){

              for(Cookie ck:cks){

              System.out.println("cookies>>"+ck.getName()+":"+ck.getValue());

                     if("uname".equals(ck.getValue())){

                            username=ck.getValue();

                     }

                     else if("upwd".equals(ck.getName())){

                            userpwd=ck.getValue();

                     }

              }

       }

%>       

-------------------

login_handle.jsp

-------------------

<%

       String name=request.getParameter("username");

       String pwd = request.getParameter("passward");

      

       User u = new User();

      

       u.setPwd(pwd);

       u.setUsername(name);

      

       if("gxy".equals(name)&&"123456".equals(pwd)){

              //创建cookie

              Cookie uname = new Cookie("uname","gxy");

              Cookie upwd = new Cookie("pwd","123456");

              //存活时间

              uname.setMaxAge(10);

              upwd.setMaxAge(10);

              //存储

              response.addCookie(uname);

              response.addCookie(upwd);

             

【二层开发模式】

1.显示jsp+逻辑控制if/else/then

2. bean:业务处理:

              1)dao:取数据库的一些bean   

                     goodDao接口+实现类gooddaoImpl

                                    --有利于数据库迁移

                                   --修改时只需要新建一个Impl继承dao就可以  

              2)vo:封装对象bean 

such as:购物车  

【三层开发模式】MVC-model(vo)+view(jsp)+control(servlet)

1.jsp -------展示

2.servlet---逻辑控制--(代理+服务提供商)

3.javabean

              1)dao:取数据库的一些bean   

                     goodDao接口+实现类gooddaoImpl

                                    --有利于数据库迁移

                                   --修改时只需要新建一个Impl继承dao就可以  

              2)vo:封装对象bean 

【servlet】

1. 概念:service+let---逻辑控制服务

---服务器端的java小程序:

       -跨平台性 :平台无关-tomcat

       -放在容器上:tomcat去调试运行

       -无main:通过调用运行

多线程服务:浏览器(m多端)--------servlet(1)      

同步:临界区的安全--servlet线程不安全

-------------------------------------------------------    

多个http请求------>servlet引擎---------->servlet线程

-------------------------------------------------------

具体代码参考:三层模式

2. 定义(手写):

       2.1.servlet实现接口

---------------------

GoodServlet.java:

---------------------

public class GoodServlet implements Servlet{

       @Override

       public void init(ServletConfig config) throws ServletException {

              // TODO Auto-generated method stub

              //对象的初始化 创建

       }

      

       @Override

       public ServletConfig getServletConfig() {

              // TODO Auto-generated method stub

              //配置信息

              return null;

       }

       @Override

       public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

              // TODO Auto-generated method stub

              //提供服务

       }

       @Override

       public String getServletInfo() {

              // TODO Auto-generated method stub

             

             

              return null;

       }

       @Override

       public void destroy() {

              // TODO Auto-generated method stub

              //对象销毁舍弃

       }

}

       2.2.继承

---------------------

GoodServlet2.java:---要手写!!!!!!!!!!!

---------------------

public class GoodServlet2 extends HttpServlet{

       @Override

       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

              // TODO Auto-generated method stub

              super.doGet(req, resp);

              //逻辑控制

      

       }

       @Override

       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

              // TODO Auto-generated method stub

              super.doPost(req, resp);

       }

}

       2.3.配置-------考试的时候要手写!!!!!!!!!!!!

----------

web.xml

----------

       <!-- 对象的创建 -->

       <servlet>

              <servlet-name>gs2</servlet-name>

              <servlet-class>com.gxy.servlet.GoodServlet2</servlet-class>

       </servlet>



       <!-- url的配置jsp -->

       <servlet-mapping>

              <servlet-name>gs2</servlet-name>

              <url-pattern>/gs2</url-pattern>

       </servlet-mapping>

* `<servlet-mapping>`: 表示一个 URL 模式到 Servlet 的映射的开始。 * `<servlet-name>gs2</servlet-name>`: 这里引用了前面定义的 Servlet 的名字 `gs2`。它告诉服务器,下面的 URL 模式应该映射到前面定义的 `gs2` Servlet。 * `<url-pattern>/gs2</url-pattern>`: 定义了一个 URL 模式。当用户或客户端向服务器发送一个 URL,其路径为 `/gs2`(可能带有查询参数或其他内容,但路径部分必须是 `/gs2`)时,服务器会调用 `com.gxy.servlet.GoodServlet2` 类来处理这个请求。

       2.4.jsp引用:

------------

login.jsp

------------

路径拼贴-------->|

                         v

<form action="<%=request.getContextPath() %>/gs2" method="get">

                     .....

</form>

3.访问过程(生命周期):要了解!!!!!

       服务器启动

----->读取web.xml(servlet/servlet-mapping)

----->第一次访问servlet(url)

----->创建servlet(以servlet-class为类 创建 servlet-name命名)对象

----->调用init初始化---只初始化一次o

----->service(doget/dopost)

----->destory

4.servlet+IDE生产

5. 运行过程

6. 使用

【考试】

选择题+简答题+程序天空+2大题

简答题:15

编程:25

-------------

1. 编码过程

2. 运行原理

hs.service-> doGet() doPost()

3. 线程安全问题

servlet:数据库

记住:不要在成员变量的位置定义自己的变量

4. el表达式 expression language

--->以标签的方式在页面上输出信息,替代

                                                        <%=%>直接的一种输出

---->一个表达式+对象  ${var+1} (=<%=var+1%>)

---->取对象:[] . (getter/setter)

---->判断后面的表达式是否为空 empty /not empty

[对象]:

       1. requestscope(map)  vs request

       --->map(key,stu)   vs  request.setAttribute("key",stu)

       取对象:

       --->requestScope.key.name(Student object)

       --->requestScope.key["name"]

       取数组对象:

       --->requestScope.key[0]

============================

       2. sessionscoppe vs session

详情参考:

D:\ECLIPSE2020-12\三层模式\WebContent\login.jsp

name:${sessionScope.user.txt}=<%=user.getTxt() %>

============================

       3. pageScope vs page(不常用)

============================

     4. parms vs getparameter/getparameters(不常用)

==============================

       5. pageContext  vs pageContext

       路径拼贴

       ${pageContext.request.contextPath} vs  <%=request.getContextPath() %>

============================

jstl 标签库-避免使用<%+%>

java server standard tag library

标签的方式:值的输出/变量的定义/分支和循环的控制

指令:

<%@ page%>

<%@ include%>

<%@ taglib%>

使用:

<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>

【判断if 】

<c:if test="${empty sessionScope.user }">//</c:if>

<c:if test="${not empty sessionScope.user }">/</c:if>

                            ||

<% User user = (User)session.getAttribute("user");

if(user ==null){ } else{///}%>

------------------------------------------------------

详情参考:

D:\ECLIPSE2020-12\三层模式\WebContent\login.jsp

-----------------------------------------------------

【循环:forEach】

<%

products gd = (products)session.getAttribute("goods");

       List<Product> pds =gd.getPds();

       Iterator<Product> giter =pds.iterator();

       Product g =null;

       %>

       </table>

       <table border="1"> 

    <tr> 

        <th>商品编号</th> 

        <th>商品名称</th> 

        <th>商品价格</th> 

        <th>操作</th>

    </tr>     

    <% 

        while (giter.hasNext()) { 

            g = giter.next(); 

    %> 

    <tr> <!-- 将<tr>标签移动到循环内部 --> 

        <td><%= g.getId() %></td> 

        <td><%= g.getName() %></td> 

        <td><%= g.getPrice() %></td>

        <td><a href="delete_good_handle.jsp?index=<%=g.getId()%>">删除商品</a></td> 

    </tr> 

    <% 

        } 

    %>

<tr> <!-- 将<tr>标签移动到循环内部 --> 

        <td colspan="4"><a href="good_info.jsp">添加商品</a> </td> 

</tr>

</table>

              <br><a href="break.jsp">退出登录</a>

                                          ||

<c:if test="${not empty sessionscope.user }}">

</c:if>

<a href="break.jsp">修改商品</a>

       </table>

       <table border="1"> 

    <tr> 

        <th>商品编号</th> 

        <th>商品名称</th> 

        <th>商品价格</th> 

        <th>操作</th>

    </tr>   

<!-- status.index 索引 status.count当前是第几个   -->

<c:forEach items="${sessionScope.goods.pds}" var="go" varStatus="status">

       <tr> <!-- 将<tr>标签移动到循环内部 --> 

        <td>${go.id}</td> 

        <td>${go.name}</td>

        <td>${go.price}:${status.index}/${status.count}</td>  

        <td><a href="delete_good_handle.jsp?index=${go.id} }">删除商品</a></td> 

     </tr> 

</c:forEach>

<tr> <!-- 将<tr>标签移动到循环内部 --> 

        <td colspan="4"><a href="good_info.jsp">添加商品</a> </td> 

</tr>

</table>

              <br><a href="break.jsp">退出登录</a>

<c:if test="${not empty sessionscope.user }}">

response.sendRedirect("login.jsp");

</c:if>

【字符循环:forTokens】

delims定义分割符

<c:forTokens items="good good day day" delims=" " var="wd">

<br/>${wd}

</c:forTokens>

【开关choose】

<c:forTokens items="good good study day day up" delims=" " var="wd">

       <c:choose>

            <c:when test="${wd eq 'good'}">好</c:when>

              <c:when test="${wd eq 'study'}">学习</c:when>

              <c:when test="${wd eq 'day'}">天</c:when>

            <c:when test="${wd eq 'up'}">向上</c:when>

              <c:otherwise></c:otherwise>

       </c:choose>

</c:forTokens>

------------------------------------------------------

详情参考:

D:\ECLIPSE2020-12\三层模式\WebContent\login.jsp

-----------------------------------------------------

------------------------------------------------------

详情参考:

D:\ECLIPSE2020-12\三层模式\WebContent\show.jsp

-----------------------------------------------------

6. 文件处理

/-> Webcontent->浏览器week13bookexamplefile

/GoodServlet

【Web-info:】

getServletPath:servlet获得的是当前页面/servlet的访问路径

getcontentPath:webcontent内容目录

getServletcontext -> application -> webcontent

【src下:】

this.getclass.getResource()//classes目录或当前的类所在的

Thread.currentThread().getcontextclassLoader().getResource("/").getpath();

【详情参考:D:\ECLIPSE2020-12\三层模式\WebContent\index.jsp】

文件上传

路径分析:

String jsppage_getServletPath = request. getServletPath();//请求的页面的名称
//----/index.jsp

String webDir_getcontextPath = request. getContextPath();//获取当前Web服务目录的名称
//----/三层模式
//==${requestScope.contentPath]

String projectRealPath = request. getServletContext(). getRealPath("/WebContent");//获取web服务器项目的真实物理路径
//-----D:\tomcat\apache-tomcat-8.5.98-windows-x64\apache-tomcat-8.5.98\webapps\三层模式\WebContent
//src下
String srcpath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
//-----/D:/tomcat/apache-tomcat-8.5.98-windows-x64/apache-tomcat-8.5.98/webapps/三层模式/WEB-INF/classes/
// /com-----/D:/tomcat/apache-tomcat-8.5.98-windows-x64/apache-tomcat-8.5.98/webapps/三层模式/WEB-INF/classes/com/
//this.getclass().getResource("/").getPath();
String getProperty = System. getProperty("user.dir");//获取工程目录
//-------D:\ECLIPSE2020-12\eclipse-jee-2020-12-R-win32-x86_64\eclipse
out.println(getProperty);
package com.gxy.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUpdate
 */
@WebServlet("/FileUpdate")
public class FileUpdate extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUpdate() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method = request. getParameter("method");
		System.out.println(method);
		if("upflie".equals(method)){
			upFile(request,response);
			
		}

	}
	protected void upFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		try {
			// 1.磁盘文件项工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();

			
			// 2.创建一个文件上传的处理器
			ServletFileUpload upload = new ServletFileUpload(factory);

			// 解析request
			List<FileItem> items = upload.parseRequest(request);
		
			Iterator<FileItem> fiIter = items.iterator();
			FileItem fi = null;
			while(fiIter.hasNext()) {
				fi=fiIter.next();
				if(fi.isFormField()) {
					System.out.println(fi.getFieldName()+"+"+fi.getString());
//					note+note
//					hb+cf
				}else {
					System.out.println(fi.getName()+"+"+fi.getFieldName());
//					web.txt+upfile
					String oFn=fi.getName();

					try {
						//file
						System.out.println("getName:"+fi.getName());
						String df = ""; //dir+file name(修改一下:新名VS旧名)
						String updir= request.getServletContext().getRealPath("/upload");
						
						//week02.txt.txt
						String ext= oFn.substring(oFn.lastIndexOf("."));
						//不会重复的id
						String fnf = UUID.randomUUID().toString();
						//7a95be94-add9-4a76-9b81-8513005c1514
						
						String fn = fnf+ext;
						df += updir + "/"+fn;

						fi.write(new File(df));
						
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--1.method=post
	2.enctype (enc[ode]type)=multipart/form-data--
	路径:
	1${requestScope.contentPath}/FileUpload
	2request.getcontextPath()%>/FileUpload
	3FileUpload
	-->
<form action="FileUpdate?method=upflie" method="post" enctype="multipart/form-data">
	File to Upload:<input type="file" name="upfile"><br>
	Notes about the file:<input type="text" name="note"><br>
	hobby : <input type="checkbox" name="hb" value="cf">吃饭<br>
	<input type="checkbox" name="hb" value="sj">sleep<br>
	<input type="submit" value="上传">

</form>
</body>
</html>

tomcat中内置的对象一旦和自己写的对象重合,就可以在tomcat中运行

使用在:脚本元素中<%= %>/<% %>

【小tips】:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

——————————————

pageEncoding->保存时的编码方式(在jsp右键选择preference->Encoding->UTF-8)

——————————————

charset->在网页中编译运行时的编码方式

             

  • 18
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值