zoukankan      html  css  js  c++  java
  • servlet学习

    9/13/2017 9:43:59 PM @author Jzedy

    前言

    使用maven创建项目,方便添加jar包,同时记录下使用idea时踩的坑
    

    jar包引用

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
    

    maven插件包引用是因为idea默认使用maven时采用JDK5.0,引用插件包后根据需要使用jdk版本
    。踩坑点–idea创建maven web项目时引用jar包时候需要到Project Structure中的Artifacts界面下的Available Elements双击引用的jar包,不然jar包没有引用上导致报错,以为pox.xml没有错误就jar包已经引用了,导致花很长时间排错。。。。

    servlet生命周期

    • init:第一次访问时候初始化
    • service:每次访问时候都会调用service
    • destroy:结束时候调用

    servlet配置

    1. 在web.xml中如下配置

      <servlet>
          <servlet-name></servlet-name>
          <servlet-class></servlet-class>
      </servlet>
      <servlet-mapping>
          <servlet-name></servlet-name>
          <url-pattern></url-pattern>
      </servlet-mapping>
    2. 使用注解配置
      @WebServlet(“/login”) 在继承HttpServlet的类上面使用WebServlet注解

    使用:

    1. 创建cookie
    2. 设置cookie有效时间
    3. 发送到浏览器
    Cookie cookie = new Cookie("username", "jzedy");//名称,值
    cookie.setMaxAge(10*60);//正数以秒为单位,零表示销毁,负数表示直到浏览器关闭
    resp.addCookie(cookie);

    Session

    1. 访问与单前请求相关联的会话对象 request.getSession([boolean]) 当默认boolean为true,代表没有时创建新的session,false表示没有时返回null
    2. 查找session中的信息 session.getAttribute
    3. 存储会话中的信息 session.setAttribute
    4. 结束session 调用removeAttribute废弃指定的值,调用invalidate废弃整个会话。

    requestDispatcher(转发)/redirect(重定向)

    调用方法:
    request.getRequestDispatcher().forward()
    response.sendRedirect()

    requestDispatcher是在服务器端运行,redirect是通过客户浏览器发送命令完成,所以redirect对浏览器是“透明的”,而requestDispatcher不是

    requestDispatcher地址栏信息不变,redirect地址栏将改变

  • 相关阅读:
    使用 Dockerfile 定制镜像
    UVA 10298 Power Strings 字符串的幂(KMP,最小循环节)
    UVA 11090 Going in Cycle!! 环平均权值(bellman-ford,spfa,二分)
    LeetCode Best Time to Buy and Sell Stock 买卖股票的最佳时机 (DP)
    LeetCode Number of Islands 岛的数量(DFS,BFS)
    LeetCode Triangle 三角形(最短路)
    LeetCode Swap Nodes in Pairs 交换结点对(单链表)
    LeetCode Find Minimum in Rotated Sorted Array 旋转序列找最小值(二分查找)
    HDU 5312 Sequence (规律题)
    LeetCode Letter Combinations of a Phone Number 电话号码组合
  • 原文地址:https://www.cnblogs.com/JzedyBlogs/p/9368661.html
Copyright © 2011-2022 走看看