栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaWeb-02

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaWeb-02

JavaWeb response重定向

一个web资源B收到客户端A请求以后,B会通知A客户端去访问另一个web资源C,这个过程称为重定向。

重定向和转发的区别

相同点:

页面都会跳转

不同点:

请求转发的时候,url不会发生变化重定向的时候,url地址栏会发生变化 HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过HttpServletRequest的方法,获得客户端的所有信息。

LoginServlet.class

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbys = req.getParameterValues("hobbys");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbys));

        //通过请求转发
        req.getRequestDispatcher("/success.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req, resp);
    }
}
    
        LoginServlet
        com.kang.servlet.LoginServlet
    


    
        LoginServlet
        /login
    

cookie session

会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话。

有状态会话:一个同学来过教室,下次再来就能知道这个同学来过

一个网站如何证明来过?

    服务端给客户端一个信件,客户端下次访问服务端的时候带上新建就可以了,cookie服务器登记来过,下次来的时候服务器去匹配

http是一个无状态的协议

无状态:就是说这次请求和上一次请求没有任何关系,互不认识。无状态的好处是快速。坏处是假如我们想要把www.zhihu.com/login.html和www.zhihu.com/index.html两个网址关联起来,必须使用某些手段

保存会话的两种技术

cookie(饼干):

客户端技术(响应,请求)

session(会话):

服务器技术,利用这个技术可以保存用户的会话信息。可以把信息或者数据放在session中。

应用场景:
网站登录之后,下一次访问不用登录可以直接上去

public class cookieDemo01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("GBK");
        resp.setCharacterEncoding("GBK");

        PrintWriter out = resp.getWriter();
        //cookie 服务器端从客户端获取
        cookie[] cookies = req.getcookies();//返回数组,可能存在多个cookie

        //判断cookie是否存在
        if (cookies != null) {

            out.write("上一次到访的时间: ");
            for (cookie cookie : cookies) {
                if( cookie.getName().equals("lastLoginTime")){
                    //获取cookie中的值
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    out.write(date.toLocaleString());
                }

            }

        } else {
            out.write("这是您第一次来");
        }

        //服务给客户端响应一个cookie
        cookie cookie1 = new cookie("lastLoginTime", System.currentTimeMillis()+"");
        //有效期为一天
        cookie1.setMaxAge(24*60*60);
        resp.addcookie(cookie1);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

  
        cookie
        com.kang.servlet.cookieDemo01
    
    
        cookie
        /c1
    

一个网站cookie是否存在上限 ?

300个cookie浏览器上限一个cookie只能保存一个信息一个web站点可以给浏览器发送多个cookie,最多存放20个cookiecookie大小有限制,最多为4kb

删除cookie:

不设置有效期,关闭浏览器,自动失效设置有效时间为0 Session(重点)

session(会话):

服务器技术,利用这个技术可以保存用户的会话信息。可以把信息或者数据放在session中。

什么是session:

服务器会给每一个用户(浏览器)创建一个session对象一个session独占一个浏览器,只要浏览器没关闭,session就存在用户登陆以后,整个网站都能访问

session和cookie区别:

cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)Session把用户的数据写到用户独占Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)Session对象由服务器创建

使用场景:

保存一个登录用户的信息购物车信息在整个网站中经常使用的数据,将其保存在Session中 JSP

Java Server Pages:java服务器端页面,也和servlet一样,用于动态web技术

最大的特点:

写JSP就像在写HTMLJSP页面中可以嵌入java代码 JSP原理

JSP本质上就是一个servlet程序

浏览器向服务器发送请求,不管访问什么资源,本质上都是在访问servlet

在JSP页面中,只要是java代码就会原封不动的输出,如果是html代码,就会被转换为

  out.write("Titlern");
JSP基础语法

JSP作为java技术的一种应用,拥有一些自己扩充的语法,java所有语法都支持。

jsp声明,会被编译到jsp生成java代码的类中!其他的,就会被生成到_jspService方法中!

方法里面的的可以调用方法外边的,方法外边的作用域更高一点

<%%>
<%=%>
<%!%>

<%--注释--%>

jsp声明

<%!
  static {
    System.out.println("servlet load...");
  }

  private String globalVar = "kkk";

  public void zyy() {
    System.out.println("进入了kkk方法!");
  }
%>

<%kkk();%>
JSP内置对象及作用域

九大内置对象

PageContext 页面上下文 (存东西)Request (存东西)ResponseSession (存东西)Application [ServletContext] (存东西)config [ServletConfig]outpageexception

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


    Title



<%--内置对象--%>
<%
    pageContext.setAttribute("name1", "kk1");  //保存的数据只在一个页面有效
    request.setAttribute("name2", "kk2");   // 保存的数据只在一次请求中有效,请求转发会携带这个数据
    session.setAttribute("name3", "kk3");   //保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
    application.setAttribute("name4", "kk4");  //保存的数据只在服务器中有效,从打开浏览器到关闭浏览器
%>
<%
    //从pageContext取出,我们通过寻找的方式来
    //从底层到高层(作用域):page-->request-->session-->appliaction
    String name1 = (String) pageContext.getAttribute("name1");
    String name2 = (String) pageContext.getAttribute("name2");
    String name3 = (String) pageContext.getAttribute("name3");
    String name4 = (String) pageContext.getAttribute("name4");

%>
取值:
${name1}
${name2}
${name3}
${name4}




request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用

session:客户端向服务器发送请求,产生的数据,用户用完一会儿还有,比如购物车。

application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据

JSP标签、JSTL标签、EL表达式
     
            javax.servlet.jsp.jstl
            jstl-api
            1.2
        
        
            taglibs
            standard
            1.1.2
        

EL表达式:

获取数据执行运算获取web开发的常用对象

JSP标签

jsptag.jsp


    
    


jsptag2.jsp

成功了

<%=request.getParameter("name")%>
<%=request.getParameter("age")%>

JSTL表达式

jstl标签库的使用就是为了弥补HTML标签的不足;它自定义了许多标签,可以供我们,标签的功能和java代码一样。

核心标签(掌握)

引入对应的taglib使用其中的方法在tomcat也需要引入jstl的包,,否则会报错,JSTL解析错误

格式化标签

sql标签

xml标签

JavaBean

实体类

javabean有特定的写法:

必须要有一个无参构造属性必须私有化必须有对应的get/set方法

一般用来和数据库的字段做映射 ORM:

ORM:对象关系映射

表–>类字段–>属性行记录–>对象

idnameageaddress
1张三15西安
2李四25北京
3王二17上海

Model:

业务处理:业务逻辑(Service)数据持久层:CRUD (Dao)

VIiew:

展示数据提供链接发起Servlet请求(a,form,img…)

Controller (Servlet):

接收用户的请求:(req:请求参数)交给业务层处理对应的代码控制视图的跳转

登录--->接收用户的登录请求----->处理用户的请求(获取用户的的参数:username,password)---
-->交给业务层处理登录业务(判断用户名、密码是否正确:事务)----->Dao层查询用户名和密码是否正确

Filter

Filter:过滤器,用来过滤网站的数据

处理中文乱码登录验证…

设置过滤器,经过此路径的请求,转发都会被过滤,设置

CharacterEncodingFilter.class

package com.kang.filter;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import java.io.IOException;

import java.util.logging.LogRecord;
import javax.servlet.Filter;

public class CharacterEncodingFilter extends HttpServlet implements Filter{


    //初始化
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");

    }

    public  void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException{

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        System.out.println("执行前");
        chain.doFilter(request,response);
        System.out.println("执行后");
    }

    //销毁
    public void destroy() {
        System.out.println("销毁");
    }

    public boolean isLoggable(LogRecord record) {
        return false;
    }
}

ShowServlet.class

package com.kang.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

      resp.setCharacterEncoding("utf-8");
        resp.getWriter().write("你好呀!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      doGet(req, resp);
    }
}

web.xml

    
        show
        com.kang.servlet.ShowServlet
    
    
        show
        /servlet/show
    
    
    
        show
        /show
    


    
        CharacterEncodingFilter
        com.kang.filter.CharacterEncodingFilter
    
        
            CharacterEncodingFilter
            /servlet/*
        

Listener

监听器

OnlineCountListener.class

package com.kang.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


public class OnlineCountListener implements HttpSessionListener {

    //创建session监听:观察一举一动
    //一旦创建session就会触发一次这个事件
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer onlineCount =(Integer)ctx.getAttribute("OnlineCount");

        if(onlineCount==null){
            onlineCount=new Integer(1);
        }else {
            int count = onlineCount.intValue();
            onlineCount=new Integer(count+1);
        }

        ctx.setAttribute("OnlineCount",onlineCount);

    }

    //销毁session监听
    //一旦销毁session就会触发一次这个事件
    public void sessionDestroyed(HttpSessionEvent se) {

        ServletContext ctx = se.getSession().getServletContext();
        Integer onlineCount =(Integer)ctx.getAttribute("OnlineCount");

        if(onlineCount==null){
            onlineCount=new Integer(0);
        }else {
            int count = onlineCount.intValue();
            onlineCount=new Integer(count-1);
        }

        ctx.setAttribute("OnlineCount",onlineCount);

    }
}

index.jsp

 当前有 <%=this.getServletConfig().getServletContext().getAttribute("OnlineCount") %>  人在线


web.xml

  
        com.kang.listener.OnlineCountListener
    
    
    
JDBC

需要jar包支持:

java.sqljavax.sqlmysql-conneter-java…连接驱动(必须要导入) JUNIT

在方法上加个@Test注解,就可以直接进行测试

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763810.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号