GVKun编程网logo

MyBatis-动态SQL的if、choose、when、otherwise、trim、where、set、foreach使用(各种标签详解), 以及实体间关系配置

5

想了解MyBatis-动态SQL的if、choose、when、otherwise、trim、where、set、foreach使用(各种标签详解),以及实体间关系配置的新动态吗?本文将为您提供详细的

想了解MyBatis-动态SQL的if、choose、when、otherwise、trim、where、set、foreach使用(各种标签详解), 以及实体间关系配置的新动态吗?本文将为您提供详细的信息,此外,我们还将为您介绍关于004-linux命令-搜索命令find、locate、whereis、which、type、find、locate、whereis、which 和 ty…、from、where、group、with、having、order、union、limit 的使用、HttpContext对象下的属性Application、Cache、Request、Response、Server、Session、User的新知识。

本文目录一览:

MyBatis-动态SQL的if、choose、when、otherwise、trim、where、set、foreach使用(各种标签详解), 以及实体间关系配置

MyBatis-动态SQL的if、choose、when、otherwise、trim、where、set、foreach使用(各种标签详解), 以及实体间关系配置

 

比较全的文档:https://www.cnblogs.com/zhizhao/p/7808880.html 或 https://blog.csdn.net/zhll3377/article/details/8203440

 

四:常用的动态语句标签:通过动态sql标签可以进行条件判断,条件遍历等操作从而满足结果的需要

  0. </if>

<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
    select * from t_blog where 1 = 1
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="content != null">
        and content = #{content}
    </if>
    <if test="owner != null">
        and owner = #{owner}
    </if>
</select>

 

 

<!-- 查询学生list,like姓名    concat: ‘字符串拼接’-->   
<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST    
    <if test="studentName!=null and studentName!='''' ">   
        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT(''%'', #{studentName}),''%'')    
    </if>   
</select>   

 

<select id="getEmpByIf" resultType="Emp" parameterType="Emp">
    select * from emp where 1 = 1
    <if test="job != null and job != ''''">
        and job = #{job}
    </if>
    <if test="deptno != null ">
        and deptno = #{deptno}
    </if>
</select>

 

  1. <where> : 使用其可以代替sql语句中的where关键字,一般防止在条件查询的最外层

  2.<set>:常用于<update>更新语句中,替代 sql中的“set”关键字,特别是在联合<if>进行判断是,可以有效方式当某个参数为空或者不合法是错误的更新到数据库中

  

 <update id="updateByPrimaryKeySelective" parameterType="pojo.Orderitem" >
    update orderitem
    <set >
      <if test="productId != null" >
        product_id = #{productId,jdbcType=VARCHAR},
      </if>
      <if test="count != null" >
        count = #{count,jdbcType=INTEGER},
      </if>
    </set>
    where orderitem_id = #{orderitemId,jdbcType=VARCHAR}
  </update>

  3. <choose><when></when><otherwise></otherwise></choose> 标签组:也是一个用于条件判断的标签组,和<if>的不同之处在于条件从<choose>进入,去匹配<when>中的添加,一旦匹配马上结束;若到找不到匹配项,将执行<other>中的语句;可以理解为<if>是 && 关系 <choose>是 || 关系 

  

<!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose -->     
<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <where>     
        <choose>     
            <when test="studentName!=null and studentName!='''' ">     
                    ST.STUDENT_NAME LIKE CONCAT(CONCAT(''%'', #{studentName}),''%'')      
            </when>     
            <when test="studentSex!= null and studentSex!= '''' ">     
                    AND ST.STUDENT_SEX = #{studentSex}      
            </when>     
            <when test="studentBirthday!=null">     
                AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
            </when>     
            <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='''' ">     
                AND ST.CLASS_ID = #{classEntity.classID}      
            </when>     
            <otherwise>     
                      
            </otherwise>     
        </choose>     
    </where>     
</select>   

3.1. <choose>:   

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。  if是与(and)的关系,而choose是或(or)的关系。 

 

5. <set>  

当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。
没有使用if标签时,如果有一个参数为null,都会导致错误,如下示例:

<!-- 更新学生信息 -->   
<update id="updateStudent" parameterType="StudentEntity">   
    UPDATE STUDENT_TBL    
       SET STUDENT_TBL.STUDENT_NAME = #{studentName},    
           STUDENT_TBL.STUDENT_SEX = #{studentSex},    
           STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},    
           STUDENT_TBL.CLASS_ID = #{classEntity.classID}    
     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};    
</update>   

 

6.<trim>标签:

update user
<trim prefix="set" suffixOverrides="," suffix=" where id = #{id} "> <if test="name != null and name.length()>0"> name=#{name} , </if> <if test="gender != null and gender.length()>0"> gender=#{gender} , </if> </trim>

 

 

1>. <trim prefix="" suffix="" suffixOverrides="" prefixOverrides=""></trim>
prefix:在trim标签内sql语句加上前缀。
suffix:在trim标签内sql语句加上后缀。
suffixOverrides:指定去除多余的后缀内容,如:suffixOverrides=",",去除trim标签内sql语句多余的后缀","。
prefixOverrides:指定去除多余的前缀内容

下面是一个往购物车表中插入数据的mybatis语句

<insert id="insert" parameterType="com.tortuousroad.groupon.cart.entity.Cart">
        insert into cart
        <trim prefix="(" suffix=")" suffixOverrides=","> (把 尾部的,替换成 ")")
            <if test="id != null">
                id,
            </if>
            <if test="userId != null">
                user_id,
            </if>
            <if test="dealId != null">
                deal_id,
            </if>
            <if test="dealSkuId != null">
                deal_sku_id,
            </if>
            <if test="count != null">
                count,
            </if>
            <if test="createTime != null">
                create_time,
            </if>
            <if test="updateTime != null">
                update_time,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=BIGINT},
            </if>
            <if test="userId != null">
                #{userId,jdbcType=BIGINT},
            </if>
            <if test="dealId != null">
                #{dealId,jdbcType=BIGINT},
            </if>
            <if test="dealSkuId != null">
                #{dealSkuId,jdbcType=BIGINT},
            </if>
            <if test="count != null">
                #{count,jdbcType=INTEGER},
            </if>
            <if test="createTime != null">
                #{createTime,jdbcType=TIMESTAMP},
            </if>
            <if test="updateTime != null">
                #{updateTime,jdbcType=TIMESTAMP},
            </if>
        </trim>
    </insert>

假设没有指定 suffixOverrides="," ,  

执行的sql语句也许是这样的:insert into cart (id,user_id,deal_id,) values(1,2,1,);显然是错误的
指定之后语句就会变成            insert into cart (id,user_id,deal_id) values(1,2,1);这样就将“,”去掉了。
前缀也是一个道理这里就不说了。

来自: https://blog.csdn.net/qq_33054511/article/details/70490046

 

 

 

o(^▽^)o可以看到成功匹配掉了开头的$和末尾的*

String[] deptnos = {"10", "20", "30"};

List<Emp> empList = sqlSession.getMapper(EmpMapper.class).getEmpByArray(deptnos);

 2>.

   trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。 where例子的等效trim语句:

 <!-- 查询学生list,like姓名,=性别   传入参数 map 或 实体 即可-->   
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST    
    <trim prefix="WHERE" prefixOverrides="AND|OR">   (头部的and或or 都替换成"where")
        <if test="studentName!=null and studentName!='''' ">   
            ST.STUDENT_NAME LIKE CONCAT(CONCAT(''%'', #{studentName}),''%'')    
        </if>   
        <if test="studentSex!= null and studentSex!= '''' ">   
            AND ST.STUDENT_SEX = #{studentSex}    
        </if>   
        <if test="position!=null">  
             AND ST.position like #{position}  
        </if>  
    </trim>   
</select>   

【解释】

a.我们使用<trim>替代<where>标签。

b.属性“prefix”表示:加入前缀where

c.属性“prefixOverrides”表示:自动覆盖第一个“and”或者“or”

d.后缀的用法类似;

set例子的等效trim语句(<trim>是一个非常强大的标签,因此,我们也可以通过<trim>来实现<set>的功能,如下:【这种写法的运行效果与<set>等价】):

<!-- 更新学生信息 -->   
<update id="updateStudent" parameterType="StudentEntity">   
    UPDATE STUDENT_TBL    
    <trim prefix="SET" suffixOverrides=",">   
        <if test="studentName!=null and studentName!='''' ">   
            STUDENT_TBL.STUDENT_NAME = #{studentName},    
        </if>   
        <if test="studentSex!=null and studentSex!='''' ">   
            STUDENT_TBL.STUDENT_SEX = #{studentSex},    
        </if>   
        <if test="studentBirthday!=null ">   
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},    
        </if>   
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='''' ">   
            STUDENT_TBL.CLASS_ID = #{classEntity.classID}    
        </if>   
    </trim>   
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};    
</update>   

 

7.<foreach>标签:该标签的作用是遍历集合类型的条件 

  属性:collection=“array” / collection = “list”  ----->是数组类型,还是集合类型

              item=“ productId ”------> 参数名

      open="(" separator="," close=")"  ------>开始符号,分隔符号,结束符号 

      index=“ ” ---->结束下标位置,不配置该参数时,默认为全部遍历 

 <delete id="deleteByPriKeys" parameterType="java.lang.String">
       delete from product where product_Id in
       <foreach collection="list" item="productId" open="(" separator="," close=")">
            #{productId,jdbcType = VARCHAR}
       </foreach>
  </delete> 

 

3.4.  参数为Array实例的写法:

<select id="getStudentListByClassIDs" resultMap="studentResultMap">   
    SELECT * FROM STUDENT_TBL ST    
     WHERE ST.CLASS_ID IN     
     <foreach collection="array" item="ids"  open="(" separator="," close=")">   
        #{ids}    
     </foreach>   
</select>   

接口的方法声明:

public List<StudentEntity> getStudentListByClassIDs(String[] ids);
public List<StudentEntity> getStudentListByClassIDs(String[] ids);测试代码,查询学生中,在20000002、20000003这两个班级的学生:

 3.5. Map类型的参数

<select id="dynamicForeach3Test" resultType="com.mybatis.entity.User">
    select * from t_user where username like ''%${username}%'' and id in
    <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</select>
public List<User> dynamicForeach3Test(Map<String, Object> params); 

 

五、(https://blog.csdn.net/qq_29233973/article/details/51433924 + https://blog.csdn.net/zenson_g/article/details/10137665)

1. 引用:通过<include refid="" />标签引用,refid="" 中的值指向需要引用的<sql>中的id=“”属性

<!--定义sql片段-->
<sql id="orderAndItem">
      o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count
  </sql>
 
 <select id="findOrderAndItemsByOid" parameterType="java.lang.String" resultMap="BaseResultMap">
      select
<!--引用sql片段-->
      <include refid="orderAndItem" />
      from ordertable o
      join orderitem i on o.orderitem_id = i.orderitem_id
      where o.order_id = #{orderId}
  </select>

2. 映射管理器resultMap:映射管理器,是Mybatis中最强大的工具,使用其可以进行实体类之间的关系,并管理结果和实体类间的映射关系:

1)一对一关系<assocation property = " " javaType=" ">   property = “ ” 被维护实体在宿主实体中的属性名,javaType = " " 被维护实体的类型

package pojo;
 
public class Orderitem {
  
    private String orderitemId;
 
    private String productId;
 
    private Integer count;
    
    private Product product;   

从上方代码段可以看出:Product 对象在 Orderitem 实体中以 product 属性存在 

Orderitemmapper.xml

 <resultMap id="BaseResultMap" type="pojo.Orderitem" >
    <id column="orderitem_id" property="orderitemId" jdbcType="VARCHAR" />
    <result column="product_id" property="productId" jdbcType="VARCHAR" />
    <result column="count" property="count" jdbcType="INTEGER" />
    <!-- 通过association 维护 一对一关系 -->
    <association property="product" javaType="pojo.Product">
        <id column="product_id" property="productId"/>
        <result column="product_factroy" property="productFactroy"/>
        <result column="product_store" property="productStore"/>
        <result column="product_descript" property="productDescript"/>
    </association>
  </resultMap>

通过xml的配置可以看出,在resultMap映射管理器中,通过<association> 进行了维护,也就是在查询Orderitem对象时,可以把关联的Product对象的信息也查询出来

2)一对多关系的维护<collection property=" " ofType=" "> property = “ ” 被维护实体在宿主实体中的属性名 ,ofType=“ ”是被维护方在宿主类中集合泛型限定类型

【由于在一对多关系中,多的一放是以List形式存在,因此ofType的值取用Lsit<?> 的泛型对象类型】

public class OrderTable {
 
    private String orderId;
 
    private String cid;
 
    private String address;
 
    private Date createDate;
 
    private String orderitemId;
   
    private List<Orderitem> orderitemList ;
}

OrderTableMapper.xml:

 <resultMap id="BaseResultMap" type="pojo.OrderTable" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri May 06 15:49:42 CST 2016.
    -->
    <id column="order_id" property="orderId" jdbcType="VARCHAR" />
    <result column="cid" property="cid" jdbcType="VARCHAR" />
    <result column="address" property="address" jdbcType="VARCHAR" />
    <result column="create_date" property="createDate" jdbcType="TIMESTAMP" />
    <result column="orderitem_id" property="orderitemId" jdbcType="VARCHAR" />
         <!--维护一对多的关系  -->
        <collection property="orderitemList" ofType="pojo.Orderitem">
            <id column="orderitem_id" property="orderitemId"/>
            <result column="product_id" property="productId"/>
            <result column="count" property="count"/>
        </collection> 
  </resultMap>

3)在resultMap 中需要注意两点:

3.1)关联关系的维护可以根据实体类之间的实际情况进行嵌套维护

<resultMap id="BaseResultMap" type="pojo.OrderTable" >
    <id column="order_id" property="orderId" jdbcType="VARCHAR" />
    <result column="cid" property="cid" jdbcType="VARCHAR" />
    <result column="address" property="address" jdbcType="VARCHAR" />
    <result column="create_date" property="createDate" jdbcType="TIMESTAMP" />
    <result column="orderitem_id" property="orderitemId" jdbcType="VARCHAR" />
         <!--维护一对多的关系  -->
        <collection property="orderitemList" ofType="pojo.Orderitem">
            <id column="orderitem_id" property="orderitemId"/>
            <result column="product_id" property="productId"/>
            <result column="count" property="count"/>
<span>        </span><!--嵌套一对一关系-->
            <association property="customer" javaType="pojo.Customer">
                <id column="cid" property="cid"/>
                <result column="cname" property="cname"/>
            </association>
        </collection> 
  </resultMap>

实例:

我们又一次联合了博客表和文章表,而且关注于保证特性,结果列标签的简单映射。现在用文章映射集合映射博客,可以简单写为:

<resultMap id="blogResult" type="Blog">
   <id property="id" column="blog_id" />
   <result property="title" column="blog_title"/>
   <collection property="posts" ofType="Post">
     <id property="id" column="post_id"/>
     <result property="subject" column="post_subject"/>
     <result property="body" column="post_body"/>
   </collection>
 </resultMap>
同样,要记得 id 元素的重要性,如果你不记得了,请阅读上面的关联部分。

同样, 如果你引用更长的形式允许你的结果映射的更多重用, 你可以使用下面这个替代的映射:

<resultMap id="blogResult" type="Blog">
   <id property="id" column="blog_id" />
   <result property="title" column="blog_title"/>
   <collection property="posts" ofType="Post" resultMap="blogPostResult" columnPrefix="post_"/>
 </resultMap>
 <resultMap id="blogPostResult" type="Post">
   <id property="id" column="id"/>
   <result property="subject" column="subject"/>
   <result property="body" column="body"/>
 </resultMap>

注意 这个对你所映射的内容没有深度,广度或关联和集合相联合的限制。当映射它们时你应该在大脑中保留它们的表现。你的应用在找到最佳方法前要一直进行的单元测试和性能测试。好在 myBatis 让你后来可以改变想法,而不对你的代码造成很小(或任何)影响。

高级关联和集合映射是一个深度的主题。文档只能给你介绍到这了。加上一点联系,你会很快清楚它们的用法。

 

3.2)关于出现重复列名的处理:在实际操作过程中,查询到的结果可能会出现相同的列名,这样会对映射到实体属性带来影响甚至出现报错,那么对待这个问题可以通过对列取别名的方式处理:

要记住类型别名是你的伙伴。使用它们你可以不用输入类的全路径。比如:

<!-- In mybatis-config.xml file -->
<typeAlias type="com.someapp.model.User" alias="User"/>
<!-- In SQL Mapping XML file -->
<select id="selectUsers" parameterType="int" resultType="User">  
  select id, username, hashedPassword
  from some_table
  where id = #{id}
</select>

这些情况下,MyBatis 会在幕后自动创建一个 ResultMap,基于属性名来映射列到 JavaBean 的属性上。如果列名没有精确匹配,你可以在列名上使用 select 字句的别名(一个基本的 SQL 特性)来匹配标签。比如:

<select id="selectUsers" parameterType="int" resultType="User">  
    select
    user_id             as "id",
    user_name           as "userName",
    hashed_password     as "hashedPassword"
  from some_table
  where id = #{id}
</select>

ResultMap 最优秀的地方你已经了解了很多了,但是你还没有真正的看到一个。这些简单的示例不需要比你看到的更多东西。只是出于示例的原因, 让我们来看看最后一个示例中外部的 resultMap 是什么样子的,这也是解决列名不匹配的另外一种方式。

<resultMap id="userResultMap" type="User">   
<id property="id" column="user_id" />
<result property="username" column="username"/>
<result property="password" column="password"/>
</resultMap>
引用它的语句使用 resultMap 属性就行了(注意我们去掉了 resultType 属性)。比如:
<select id="selectUsers" parameterType="int" resultMap="userResultMap">  
    select user_id, user_name, hashed_password
    from some_table
    where id = #{id}
  </select>

 

 

3.3)鉴别器:

有时一个单独的数据库查询也许返回很多不同 (但是希望有些关联) 数据类型的结果集。鉴别器元素就是被设计来处理这个情况的, 还有包括类的继承层次结构。鉴别器非常容易理解,因为它的表现很像 Java 语言中的 switch 语句。

定义鉴别器指定了 column 和 javaType 属性。列是 MyBatis 查找比较值的地方。 JavaType 是需要被用来保证等价测试的合适类型(尽管字符串在很多情形下都会有用)

<?xml version="1.0" encoding="utf-8"?>
<resultMap id="vehicleResult" type="Vehicle">
  <id property="id" column="id"/> 
  <result property="vin" column="vin"/> 
  <result property="year" column="year"/> 
  <result property="make" column="make"/> 
  <result property="model" column="model"/> 
  <result property="color" column="color"/> 
  <discriminator javaType="int" column="vehicle_type">
    <case value="1" resultType="carResult">
      <result property="doorCount" column="door_count"/>
    </case> 
    <case value="2" resultType="truckResult">
      <result property="boxSize" column="box_size"/> 
      <result property="extendedCab" column="extended_cab"/>
    </case> 
    <case value="3" resultType="vanResult">
      <result property="powerSlidingDoor" column="power_sliding_door"/>
    </case> 
    <case value="4" resultType="suvResult">
      <result property="allWheelDrive" column="all_wheel_drive"/>
    </case>
  </discriminator>
</resultMap>
 

3. 高级结果映射

 比如,我们如何映射下面这个语句?

<!-- Very Complex Statement -->
<select id="selectBlogDetails" parameterType="int" resultMap="detailedBlogResultMap"> 
       select
       B.id as blog_id,
       B.title as blog_title,
       B.author_id as blog_author_id,
       A.id as author_id,
       A.username as author_username,
       A.password as author_password,
       A.email as author_email,
       A.bio as author_bio,
       A.favourite_section as author_favourite_section,
       P.id as post_id,
       P.blog_id as post_blog_id,
       P.author_id as post_author_id,
       P.created_on as post_created_on,
       P.section as post_section,
       P.subject as post_subject,
       P.draft as draft,
       P.body as post_body,
       C.id as comment_id,
       C.post_id as comment_post_id,
       C.name as comment_name,
       C.comment as comment_text,
       T.id as tag_id,
       T.name as tag_name
  from Blog B
       left outer join Author A on B.author_id = A.id
       left outer join Post P on B.id = P.blog_id
       left outer join Comment C on P.id = C.post_id
       left outer join Post_Tag PT on PT.post_id = P.id
       left outer join Tag T on PT.tag_id = T.id
  where B.id = #{id}</select>

下面是一个完整的复杂结果映射例子 (假设作者, 博客, 博文, 评论和标签都是类型的别名) 我们来看看, 。但是不用紧张, 我们会一步一步来说明。当天最初它看起来令人生畏,但实际上非常简单。

<?xml version="1.0" encoding="utf-8"?>
 
<!-- Very Complex Result Map -->
<resultMap id="detailedBlogResultMap" type="Blog">
  <constructor>
    <idArg column="blog_id" javaType="int"/>  (对应实体中的 有参构造函数)
  </constructor> 
  <result property="title" column="blog_title"/> 
  <association property="author" javaType=" Author"> (association 专门负责描述一对一的关系)
    <id property="id" column="author_id"/> 
    <result property="username" column="author_username"/> 
    <result property="password" column="author_password"/> 
    <result property="email" column="author_email"/> 
    <result property="bio" column="author_bio"/> 
    <result property="favouriteSection" column="author_favourite_section"/>
  </association> 
  <collection property="posts" ofType="Post">
    <id property="id" column="post_id"/> 
    <result property="subject" column="post_subject"/> 
    <association property="author" javaType="Author"/> 
    <collection property="comments" ofType=" Comment">
      <id property="id" column="comment_id"/>
    </collection> 
    <collection property="tags" ofType=" Tag">
      <id property="id" column="tag_id"/>
    </collection> 
    <discriminator javaType="int" column="draft"> (鉴别器:switch)
      <case value="1" resultType="DraftPost"/>
    </discriminator>
  </collection>
</resultMap>

resultMap :

  • constructor - 类在实例化时,用来注入结果到构造方法中id – 一个 ID 结果;标记结果作为 ID 可以帮助提高整体效能
    • idArg - ID 参数;标记结果作为 ID 可以帮助提高整体效能
    • arg - 注入到构造方法的一个普通结果
  • result – 注入到字段或 JavaBean 属性的普通结果
  • association – 一个复杂的类型关联;许多结果将包成这种类型
    • 嵌入结果映射 – 结果映射自身的关联,或者参考一个
  • collection – 复杂类型的集
    • 嵌入结果映射 – 结果映射自身的集,或者参考一个
  • discriminator – 使用结果值来决定使用哪个结果映射
    • case – 基于某些值的结果映射
      • 嵌入结果映射 – 这种情形结果也映射它本身,因此可以包含很多相 同的元素,或者它可以参照一个外部的结果映射。

最佳实践 通常逐步建立结果映射。单元测试的真正帮助在这里。如果你尝试创建一次创建一个向上面示例那样的巨大的结果映射, 那么可能会有错误而且很难去控制它来工作。开始简单一些,一步一步的发展。而且要进行单元测试!使用该框架的缺点是它们有时是黑盒(是否可见源代码) 。你确定你实现想要的行为的最好选择是编写单元测试。它也可以你帮助得到提交时的错误。

004-linux命令-搜索命令find、locate、whereis、which、type

004-linux命令-搜索命令find、locate、whereis、which、type

一、概述@H_301_5@

  使用linux系统难免会忘记文件所在的位置,可以使用以下命令对系统中的文件进行搜索。@H_301_5@

1.1、find@H_301_5@

  语法:find <指定目录> <指定条件> <指定动作>@H_301_5@

  find [-H | -L | -P] [-EXdsx] [-f path] path ... [expression]@H_301_5@

  find命令搜索在根目录下的所有Nginx文件所在位置@H_301_5@

find / -name  Nginx

1.2、locate@H_301_5@

  比find命令快。因为它查询的是数据库(/var/lib/locatedb),数据库包含本地所有的文件信息。@H_301_5@

  如上例:@H_301_5@

locate Nginx

1.3、whereis@H_301_5@

  使用”whereis“命令可以搜索linux系统中的所有可执行文件即二进制文件@H_301_5@

  如搜搜grep命令@H_301_5@

whereis grep

1.4、which@H_301_5@

  使用which命令查看系统命令是否存在,并返回系统命令所在的位置@H_301_5@

  使用which命令查看grep命令是否存在以及存在的目录的命令为:@H_301_5@

which grep

1.5、type@H_301_5@

  使用type命令查看系统中的某个命令是否为系统自带的命令@H_301_5@

  使用type命令查看cd命令是否为系统自带的命令;查看grep 是否为系统自带的命令。@H_301_5@

type cd
type grep

find、locate、whereis、which 和 ty…

find、locate、whereis、which 和 ty…

1. find
 
find 是最常见和最强大的查找命令,你可以用它找到任何你想找的文件。
 
find 的使用格式如下:
 
  $ find <指定目录> < 指定条件 > < 指定动作 >
 
  - <指定目录>: 所要搜索的目录及其所有子目录。默认为当前目录。
 
  - <指定条件>: 所要搜索的文件的特征。
 
  - <指定动作>: 对搜索结果进行特定的处理。
 
如果什么参数也不加,find 默认搜索当前目录及其子目录,并且不过滤任何结果(也就是返回所有文件),将它们全都显示在屏幕上。
 
find 的使用实例:
 
  $ find . -name ''my*''
 
搜索当前目录(含子目录,以下同)中,所有文件名以 my 开头的文件。
 
  $ find . -name ''my*'' -ls
 
搜索当前目录中,所有文件名以 my 开头的文件,并显示它们的详细信息。
 
  $ find . -type f -mmin -10
 
搜索当前目录中,所有过去 10 分钟中更新过的普通文件。如果不加 - type f 参数,则搜索普通文件 + 特殊文件 + 目录。
 
2. locate
 
locate 命令其实是 “find -name” 的另一种写法,但是要比后者快得多,原因在于它不搜索具体目录,而是搜索一个数据库(/var/lib/locatedb),这个数据库中含有本地所有文件信息。Linux 系统自动创建这个数据库,并且每天自动更新一次,所以使用 locate 命令查不到最新变动过的文件。为了避免这种情况,可以在使用 locate 之前,先使用 updatedb 命令,手动更新数据库。
 
locate 命令的使用实例:
 
  $ locate /etc/sh
 
搜索 etc 目录下所有以 sh 开头的文件。
 
  $ locate ~/m
 
搜索用户主目录下,所有以 m 开头的文件。
 
  $ locate -i ~/m
 
搜索用户主目录下,所有以 m 开头的文件,并且忽略大小写。
 
3. whereis
 
whereis 命令只能用于程序名的搜索,而且只搜索二进制文件(参数 - b)、man 说明文件(参数 - m)和源代码文件(参数 - s)。如果省略参数,则返回所有信息。
 
whereis 命令的使用实例:
 
  $ whereis grep
 
4. which
 
which 命令的作用是,在 PATH 变量指定的路径中,搜索某个系统命令的位置,并且返回第一个搜索结果。也就是说,使用 which 命令,就可以看到某个系统命令是否存在,以及执行的到底是哪一个位置的命令。
 
which 命令的使用实例:
 
  $ which grep
 
5. type
 
type 命令其实不能算查找命令,它是用来区分某个命令到底是由 shell 自带的,还是由 shell 外部的独立二进制文件提供的。如果一个命令是外部命令,那么使用 - p 参数,会显示该命令的路径,相当于 which 命令。
 
type 命令的使用实例:
 
  $ type cd
 
系统会提示,cd 是 shell 的自带命令(build-in)。
 
  $ type grep
 
系统会提示,grep 是一个外部命令,并显示该命令的路径。
 
  $ type -p grep
 
加上 - p 参数后,就相当于 which 命令。

 

from、where、group、with、having、order、union、limit 的使用

from、where、group、with、having、order、union、limit 的使用

顺序很重要

  每次看数据库的一些语法时,都很自然的略过那一大堆的规则,比如说线下面这段select的语法:

select [field1,field2...] func_name
from table1,table2,view1
[left|right join table2 on condition_what]
[where condition_where]
[group by field1,field2...]
[with rollup]
[having condition_where]
[order by field1 [desc|asc]]
[limit offset,length]

  实际用的时候,除非经常使用,有些项顺序已经习以为常了,但是更多的时候,总会将顺序搞错,比如group

 

from

  后面跟表名或者视图名,表示从该表或者视图中查询数据。

  from后面可以跟多个表名或者视图名,此时表示全连接,一般不推荐使用。

mysql > select tb_one.id,tb_two.name,tb_three.addr from tb_one,tb_two,tb_three;

  

where

  后面跟的是选择的条件,条件可以是比较运算符<、=<、>、>=、=、!=、like、is not NULL等,或者逻辑运算符 and or (between and)等。

mysql> select * from cate where (id>10 and name=''abc'') or (addr is not null);
mysql> select * from cate where name like ''%abc_'';
mysql> select * from cate where create_time between ''2018-01-01 00:00:00'' and ''2018-07-20 00:00:00'';

  后面的条件可以是各种形式,包括一个in 

mysql> select * from cate where id in (select id from demo);

  

group by

  后面通常跟着的是列名或者表达式,可以根据一列进行分组,也可以对多列进行分组,多列分组的时候,只有当进行分组的所有列完全相同时,才认为是同一个组的。

  另外,group by子句通常和聚合函数一起使用,比如sum,avg,count,min,max这几个聚合函数作为select的查询结果。

  如果使用group by之后,一般不会在select后面查询的结果中指定列或者某个字段,因为这样是没有意义的,在分组时,只会统计该组的第一条数据。

#按照id分组,统计每组的price总和
mysql > select id,sum(price) from cate group by id;

#按照price和type分组,两条记录,如果price和type都对应相同,则认为是一组;否则不是一组
mysql > select count(*) from cate group by price,type;

   可以在分组后面加上with rollup,会在分组之后对每个组进行汇总。

 

having

  having和where只有很小的区别,都代表条件筛选,但是在having子句中,可以使用聚合函数;而where中是不能使用聚合函数。

  having子句是在where子句和group by子句后面的,其实having的功能可以看着再次筛选,即,前面的查询结果,再用having中的条件在来筛选一次。

mysql> select * from cate where id > 6 having id > 7;
#先找出id>6的记录,然后再从这些记录中找出id>7的记录

mysql> select sum(id),kind from cate where id !=0 group by kind having sum(id) > 8;
#同样是上面的那个逻辑,从结果中在筛选一遍

  

order by

  order by子句后面可以是一个列或者多列、表达式、正整数。正整数表示按结果表中该整数所指的那一列进行排序。

  排序默认的是升序(asc),可以显式指定排序规则,升序(asc),降序(desc)。注意空值被认为是最小值。

mysql> select * from cate order by id desc;
#按照id降序排列

mysql> select * from cate order by id asc,price desc;
#先将结果按照id升序排列,如果id相同,则按proce降序排列

  

limit

  用来限制返回结果的行数,后面可以是一个数,也可以是两个数。

mysql> select * from cate limit 5;  
#返回5条记录

mysql> select * from cate limit 3,5;  
#第一条记录下标为0,所以返回的结果是从第4条开始的5条记录:4,5,6,7,8

  

union

  可以连接多个select语句,然后将多个select的结果整合到一个表中,最终生成一个表,表的字段名称是以第一个select的字段名称为准。

  需要注意的是,每一个select语句选择的列,应具有相同的列数,并且每一列的类型要相同。并且mysql会自动从最终结果中去处重复行。

mysql> select cid,cname from cate
    -> union
    -> select id,name from demo;

  

 

 

HttpContext对象下的属性Application、Cache、Request、Response、Server、Session、User

HttpContext对象下的属性Application、Cache、Request、Response、Server、Session、User

一、HttpContext概述:

HttpContext封装关于单个HTTP请求的所有HTTP特定信息。

HttpContext基于HttpApplication的处理管道,由于HttpContext对象贯穿整个处理过程,所以,可以从HttpApplication处理管道的前端将状态数据传递到管道的后端,完成状态的传递任务。

HttpContext类它对Request、Respose、Server等等都进行了封装,并保证在整个请求周期内都可以随时随地的调用;为继承 IHttpModule 和 IHttpHandler 接口的类提供了对当前 HTTP 请求的 HttpContext 对象的引用。

当我们创建一个一般处理程序Handler.ashx时,我们可以在文件中看到这一句:public void ProcessRequest (HttpContext context);

1、访问方式

1、在WebForm或类库(包括MVC)项目中,通过Current静态属性,就能够获得HttpContext的对象。

HttpContext context = HttpContext.Current;

2、如果是在Asp.net MVC的Controller中,通过this.HttpContext就能获取到HttpContextBase对象。

HttpContextBase context = this.HttpContext;

3、如果是在MVC视图中可以这样得到:

@Html.ViewContext.HttpContext

2、成员对象:

  1. Application    :为当前 HTTP 请求获取HttpApplicationState 对象
  2. Cache :  获取当前应用程序域的Cache 对象
  3. Request  :  为当前 HTTP 请求获取HttpRequest 对象
  4. Response  :  获取当前 HTTP 响应的HttpResponse 对象
  5. Server   : 获取提供用于处理 Web 请求的方法的HttpServerUtility 对象
  6. Session    :为当前 HTTP 请求获取HttpSessionState 对象
  7. User    :为当前 HTTP 请求获取或设置安全信息。

二、Application属性:保存所有用户共用的信息

Application属性为当前 HTTP 请求获取 HttpApplicationState 对象。

Application用来保存所有用户共用的信息。

在Asp时代,如果要保存的数据在应用程序生存期内不会或者很少发生改变,那么使用Application是理想的选择。但是在Asp.net开发环境中我们把类似的配置数据放在Web.config中。

HttpApplicationState类可以通过Page.Application访问。

如果要使用Application 要注意的是所有的写操作都要在Application_OnStart事件中完成(global.Asax),尽管可以使用Application.Lock()避免了冲突,但是它串行化了对Application的请求,会产生严重的性能瓶颈。

不要使用Application保存大数据量信息。

global.asax:

void Application_OnStart()
{
    Application["UserID"] = "test";
    String UserName = Application["UserID"].ToString();

    //修改
    Application.Lock();
    Application["count"] = (Application["UserID"] as int) + 1;
    Application.Unlock();
}

三、Cache属性:当前应用程序域服务端缓存对象

Cache属性获取当前应用程序域的 Cache 对象。Cache为服务端缓存对象。

Cache和Application:用于服务端,整个应用程序、所有用户拥有。

Cache用于在Http请求期间保存页面或者数据, Cache的使用可以大大的提高整个应用程序的效率,它允许将频繁访问的服务器资源存储在内存中,当用户发出相同的请求后,服务器不是再次处理而是将Cache中保存的数据直接返回给用户,

可以看出Cache节省的是时间—服务器处理时间。

Cache实例是每一个应用程序专有的,其生命周期==该应用程序周期,应用程序重启将重新创建其实例

HttpContext.Cache 是对底层HttpRuntime.Cache 缓存类的封装,由于封装到了 HttpContext ,局限于只能在 HttpContext 下使用,即只能用于 Web 应用。

所以在可以的条件,尽量用底层的HttpRuntime.Cache ,而不是用HttpContext.Cache 。

cache一般用于数据较固定,访问较频繁的地方,例如在前端进行分页的时候,初始化把数据放入缓存中,然后每次分页都从缓存中取数据,这样减少了连接数据库的次数,提高了系统的性能。

1.创建Cache

   Cache.Insert(string key,object value,CacheDependency dependencies,DateTime absoluteExpiration,TimeSpan slidingExpiration)

Cache["ID"] = "yiner";
//或者
Cache.Insert("ID", "test");//可以缓存任何对象,比如:DataTable

//缓存依赖
CacheDependency cachedep = new CacheDependency(Server.MapPath("~/App_Data/data.xml"));
Cache.Insert("ID", "test", cachedep);//当data.xml更改时,该缓存自动删除

//设置过期时间:后两个参数依次为:过期的绝对时间、过期的相对时间
Cache.Insert("ID", "test", null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);
Cache.Insert("ID", "test", null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0));

2.销毁Cache

Cache.Remove("ID");

3.调用Cache

例如你存的是一个DataTable对象,调用如下:

DataTable finaltable = Cache["ID"] as DataTable;
//
DataTable finaltable = (DataTable)Cache.Get("ID")

四、Request属性

Request属性为当前 HTTP 请求获取 HttpRequest 对象。

在服务器收到客户端的请求后,HttpRuntime将会创建一个HttpRequest对象的实例,这个实例就是我们在页面中常用的Request。

Request属性可通过HttpContext.Current或Page对象来访问。

在客户端的请求内容中,主要包含三部分内容。请求行,请求头部,请求主体。

1、HttpRequest 对象的属性

  • Request.Headers:获取 HTTP 头集合:(结果略)
  • Request.RequestType:获取客户端的请求方式,即Get或Post:GET
  • Request.HttpMethod:获取客户端使用的 HTTP 数据传输方法(如 GET、POST 或 HEAD):GET
  • Request.AcceptTypes:获取客户端支持的 MIME 接受类型的字符串数组:*/*
  • Request.RawUrl:获取当前请求的原始URL:/WebForm1.aspx?id=a,RawUrl不包含主机信息和端口号
  • Request.Url:获取有关当前请求的 URL 的信息:http://localhost:10693/WebForm1.aspx?id=a
  • Request.UrlReferrer:获取有关客户端上次请求的 URL 的信息,该请求链接到当前的 URL:
  • Request.FilePath:获取当前请求的虚拟路径:/WebForm1.aspx
  • Request.CurrentExecutionFilePath:获取当前请求的虚拟路径:/WebForm1.aspx
  • Request.Path:获取当前请求的虚拟路径:/WebForm1.aspx
  • Request.AppRelativeCurrentExecutionFilePath:获取应用程序根的虚拟路径,并通过对应用程序根使用波形符 (~) 表示法(例如,以“~/page.aspx”的形式)使该路径成为相对路径:~/WebForm1.aspx
  • Request.PhysicalPath:获取与请求的 URL 相对应的物理文件系统路径:E:\WebApplication1\WebApplication1\WebForm1.aspx
    • Request.Files:获取客户端发送的 文件的集合:HttpFileCollection对象
    • Request.Form:获取窗体变量集合:HtmlForm控件的Method的默认值post,表单数据以HTTP标头形式发送到Server
    • Request.QueryString:获取 HTTP 查询字符串变量集合:id=a;HtmlForm控件的Method的默认值get,表单数据附在网址后。
    • Request.ServerVariables:获取 Web 服务器变量的集合:Request.ServerVariables["Local_ADDR"] :Server地址 ;Request.ServerVariables["Remote_ADDR"]:客户端地址。
    • Request.Cookies :Cookies 项的集合HttpCookieCollection对象。
    • Request.Params:获取QueryString、Form、ServerVariables和 Cookies 项的组合集合。(结果略)
    • Request.ContentEncoding:获取或设置实体主体的字符集:System.Text.UTF8Encoding
    • Request.ContentLength:指定客户端发送的内容长度(以字节计):0
    • Request.ContentType:获取或设置传入请求的 MIME 内容类型:
    • Request.Browser:获取或设置有关正在请求的客户端的浏览器功能的信息:(见下面详解)
    • Request.UserAgent:获取客户端浏览器的原始用户代理信息:(结果略)
    • Request.UserHostAddress:获取远程客户端的IP主机地址:127.0.0.1
    • Request.UserHostName:获取远程客户端的DNS名称:127.0.0.1
    • Request.UserLanguages:获取客户端语言首选项的排序字符串数组:zh-cn

    2、Request.Browser对象的属性

    Request对象的Browser属性来获取客户端浏览器的一些信息:

    • Request.Browser.Browser:获取由浏览器在 User-Agent 请求标头中发送的浏览器字符串:IE
    • Request.Browser.MajorVersion:获取浏览器的主(整数)版本号:8
    • Request.Browser.MinorVersion:获取浏览器的次(即小数)版本号:0
    • Request.Browser.ActiveXControls:指示浏览器是否支持 ActiveX 控件:True
    • Request.Browser.Cookies:示浏览器是否支持 Cookie:True
    • Request.Browser.EcmaScriptVersion:获取浏览器支持的 ECMAScript 的版本号:1.2
    • Request.Browser.W3CDomVersion:获取浏览器支持的万维网联合会 (W3C) XML 文档对象模型 (DOM) 的版本:1.0

    五、Response属性:HTTP 响应信息

    Response属性获取当前 HTTP 响应的 HttpResponse 对象。

    封装来自 ASP.NET 操作的 HTTP 响应信息。

    在代码中,HttpResponse的对象引用由关键字Response。 例如,Response.Clear()是指HttpResponse.Clear方法。

    Page类具有名为的属性Response的当前实例。

    HttpResponse类的方法和属性通过HttpApplication、 HttpContext、Page、UserControl类的Response的属性进行公开。

    1、属性

    • BufferOutput :   获取或设置一个值,该值指示是否缓冲输出并在处理完整个页之后发送它。
    • Cache :   获取网页的缓存策略(例如:过期时间、保密性设置和变化条款)。
    • Cookies :   获取响应 cookie 集合。
    • Filter  :  获取或设置一个包装筛选器对象,该对象用于在传输之前修改 HTTP 实体主体。
    • Output  :  启用到输出 HTTP 响应流的文本输出。
    • OutputStream  :  启用到输出 HTTP 内容主体的二进制输出。

    2、方法

    • AddCacheDependency(CacheDependency[])   :  将一组缓存依赖项与响应关联,这样,如果响应存储在输出缓存中并且指定的依赖项发生变化,就可以使该响应失效。
    • RemoveOutputCacheItem(String)  :  从缓存中移除与默认输出缓存提供程序关联的所有缓存项。 此方法是静态的。
    • AddCacheItemDependencies(String[]) :   使缓存项的有效性依赖于缓存中的另一项。。
    • AddFileDependencies(String[])  :  将文件名数组添加到当前响应依赖的文件名集合中。
    • SetCookie(HttpCookie)  :  更新 Cookie 集合中的一个现有 Cookie。因为 HttpResponse.SetCookie 方法仅供内部使用, 可以改为调用 HttpResponse.Cookies.Set 方法
    • AppendCookie(HttpCookie)  :  将一个 HTTP Cookie 添加到内部 Cookie 集合。
    • AppendHeader(String, String) :   将 HTTP 头添加到输出流。
    • ClearHeaders()  :  清除缓冲区流中的所有头。
    • Redirect(String, Boolean)   : 将客户端重定向到新的 URL。 指定新的 URL 并指定当前页的执行是否应终止。
    • BinaryWrite(Byte[])  :  将二进制字符串写入 HTTP 输出流。
    • Write(String)  :  将一个字符串写入 HTTP 响应输出流。
    • WriteFile(String) :   将指定文件的内容作为文件块直接写入 HTTP 响应输出流。
    • TransmitFile(String)  :  将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。
    • Clear()  :  清除缓冲区流中的所有内容输出。
    • ClearContent()  :  清除缓冲区流中的所有内容输出。
    • Flush()  :  向客户端发送当前所有缓冲的输出。
    • End()  :  将当前所有缓冲的输出发送到客户端,停止该页的执行,并引发 EndRequest 事件。
    • Close()   : 关闭到客户端的套接字连接。

    六、Server属性

    在Asp.net WebForm中,Server属性获取提供用于处理 Web 请求的方法的 HttpServerUtility 对象。而在Asp.net MVC中,Server对象是HttpServerUtilityBase对象。

    通过Page.Server属性访问,提供用于对Web请求的Help方法。

    1、属性

    • MachineName:  获取服务器的计算机名称。、
    • ScriptTimeout:   获取和设置请求超时值(以秒计)。

    2、方法

    • Execute : 在当前请求的上下文中(服务端中)执行指定资源的处理程序,然后将执行返回给调用它的页。
    • Transfer :  终止当前页的执行,并为当前请求开始执行新页。
      • HtmlEncode/HtmlDecode:   对要在浏览器中显示的HTML字符串进行编码。/对已被编码以消除无效 HTML 字符的字符串进行解码
      • UrlEncode/UrlDecode : 编码/解码URL字符串,以便通过 URL 从 Web 上进行可靠的 HTTP 传输。
      • UrlPathEncode: 对 URL 字符串的路径部分进行 URL 编码并返回编码后的字符串。
      • MapPath : 返回与 Web 服务器上的指定虚拟路径相对应的物理文件路径。 该方法经常使用。将虚拟路径转换为服务器物理路径。
      context.Response.Write(context.Server.MapPath("/"));    //输出 C:\Users\Administrator\Desktop\WebApplication1\WebApplication1\    //该方法经常用,将虚拟路径转换为物理路径
      context.Response.Write("<divbackground-color:red''>HtmlEncode测试</div>");  //如果不编码,默认就是会被浏览器解析的
      context.Response.Write(context.Server.HtmlEncode("<divbackground-color:red''>HtmlEncode测试</div>"));  //经过编码之后 原样输出

      HttpUtility 类由 HttpServerUtility 类在内部使用,HttpUtility 类包含无法从 Server访问的编码和解码实用工具方法,如:ParseQueryString()方法等。

      Response.Write("|Url:"+HttpUtility.UrlEncode("你好啊"));

      若要对 Web 应用程序之外的值进行编码或解码,请使用 WebUtility 类。

      3、Server.Execute、Server.Transfer、Response.Redirect区别

      • Server.Execute方法允许当前的ASPX页面执行一个同一Web服务器上的指定ASPX页面,当指定的ASPX页面执行完毕,控制流程重新返回原页面发出Server.Execute调用的位置。
      • Server.Transfer的跳转完全是在服务器端,浏览器根本不知道已经跳转了,因此路径显示的仍然是原路径。
      • Response.Redirect是客户端发送请求到服务器,服务器执行Response.Redirect之后,返回302,浏览器接收到请求后,再次发送一次请求到要跳转的URL.

      在网络状态较好的情况下,Redirect(url)方法效率最高!! 可重定向到同一台或非同一台服务器上的aspx或非aspx(html)资源。

      Server.Transfer方法和Server.Execute方法最灵活!! 但只能转到同一Application目录下,也有可能导致不期望的结果发生。

      Server.Execute方法占用资源最多.

      七、Session属性:每一个用户的专有信息

      Session属性为当前 HTTP 请求获取 HttpSessionState 对象。

      Session用来保存每一个用户的专有信息。 HttpSessionState类通过HttpContext或Page对象的Session属性访问。一台客户机上多个浏览器窗口访问只有一个Session。

      Session的生存期是用户持续请求时间加上一段时间(一般是20分钟左右), Session超时或者被关闭将自动释放数据信息,由于用户停止使用应用程序之后它仍在内存中存留一段时间,因此这种方法效率较低。

      Session信息是保存在Web服务器内存中的,保存数据量可大可小。

      1、配置Session

      在Web.config中的 <system.web> </system.web>之间添加

      <sessionState 
                  mode="InProc"//InProc:保存到内存,Off;StateServer;SQLServer等
                  stateConnectionString="tcpip=127.0.0.1:42424"
                  sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
                  cookieless="false" //如果cookieless=true表示不用Cookie,用URL查询字符串传送会话ID。
                  timeout="20" />

      其中timeout是过期时间,如20分钟后超时。

      2、操作Session:

      //添加:
      Session["userName"] = "aaa";
      //获取:
      if (Session["userName"] != null)
      {
          string str = Session["userName"].ToString();
      }
      
      //清除某个Session
      Session["UserName"] = null;
      Session.Remove("UserName");
      
      //清除全部Session
      Session.Clear();

      八、User属性

      User的属性提供对IPrincipal接口的属性和方法的编程访问。

      这个属性能让我们访问各种信息,包括用户是否已验证,用户的类型,用户名等等,我们还可以对该属性的功能进性扩展,以实现我们的要求。
      分配给HttpContext.User的对象必须实现IPrincipal接口,而Iprincipal定义的属性之一是Identity,它必须实现Iidentity接口。

      if (User.Identity.IsAuthenticated)
      {
          Page.Title = "Home page for " + User.Identity.Name;
      }
      else
      {
          Page.Title = "Home page for guest user.";
      }

      参考:

      https://www.cnblogs.com/DSC1991/p/8674960.html

      今天关于MyBatis-动态SQL的if、choose、when、otherwise、trim、where、set、foreach使用(各种标签详解), 以及实体间关系配置的介绍到此结束,谢谢您的阅读,有关004-linux命令-搜索命令find、locate、whereis、which、type、find、locate、whereis、which 和 ty…、from、where、group、with、having、order、union、limit 的使用、HttpContext对象下的属性Application、Cache、Request、Response、Server、Session、User等更多相关知识的信息可以在本站进行查询。

      本文标签: