前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[表格 Table 数据结构管理]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Lua
... 'insert' table expected, got nil" 错误 Lua,作为一种轻量级脚本语言,以其小巧、灵活和高效而备受开发者的喜爱。在我们实际编写代码的时候,有时候会遇到一些让人脑壳疼的错误信息,就比如那个“bad argument 2 to 'insert',本来应该是个表格来着,结果却收到了nil”。这就像是你准备往抽屉里放衣服,却发现抽屉位置空空如也,这可真是让人丈二和尚摸不着头脑。本文将带你一起深入探讨这个错误背后的原因,并通过丰富的代码实例帮你理解它,以便你在今后的开发过程中能更游刃有余地处理此类问题。 1. 错误解析 在Lua中,当你尝试使用table.insert方法时,该方法期望接收到两个参数:一个是表(table),另一个是要插入到表中的元素。当错误信息提示"bad argument 2 to 'insert'"时,意味着函数接收到的第二个参数存在问题。这里的"2"实际上是指第二个实参,"table expected, got nil"则明确告诉我们,原本应该是一个table类型的参数,但实际获取的是nil。 2. 代码示例与分析 示例一: lua -- 创建一个空表 local myTable = {} -- 尝试向表中插入一个元素,但没有指定要插入哪个表 table.insert(nil, "I am supposed to be in a table!") -- 运行这段代码将会抛出错误:bad argument 1 to 'insert' (table expected, got nil) 在这段代码中,我们试图调用table.insert函数,但作为第一个参数传入了nil而非table,因此出现了上述错误。错误信息中的“1”是因为在Lua中,函数参数是从1开始计数的。 示例二: lua -- 正确创建并初始化一个table local myTable = {"Element 1", "Element 2"} -- 试图插入一个新的元素,但是新元素的引用丢失 local newElement = "New Element" newElement = nil -- 这里将newElement设为nil table.insert(myTable, newElement) -- 运行这段代码将会抛出错误:bad argument 2 to 'insert' (value expected, got nil) 在这个例子中,尽管我们正确提供了table作为table.insert的第一个参数,但第二个参数newElement被设置为了nil,导致插入操作失败。 3. 解决方案与思考过程 理解了错误来源后,解决问题的关键在于确保传递给table.insert的两个参数都是有效的。关于第一个参数,你可得把它搞清楚了,必须是个实实在在的table,不能是nil空空如也;而第二个参数呢,也得瞪大眼睛瞧仔细了,确保它是你真正想塞进那个表里的“良民”,也就是个有效的值。 lua -- 正确的插入操作演示 local myTable = {"Element 1", "Element 2"} -- 确保新元素存在且非nil local newElement = "New Element" table.insert(myTable, newElement) -- 此时不会出现错误 print(table.concat(myTable, ", ")) -- 输出: "Element 1, Element 2, New Element" 在实际编程过程中,我们需要时刻保持警惕,确保对变量的管理和引用是准确无误的,尤其是在进行数据结构操作如插入、删除或更新时。这种精细到每根汗毛的编程习惯,可不只是能帮我们躲开“参数错误”这类小坑,更能给咱们的程序打上一层强心针,让它的稳定性和坚固程度蹭蹭上涨。 总之,面对"bad argument 2 to 'insert' table expected, got nil"这类错误,记住一点:在执行任何修改table的操作前,请先确认所有相关变量都已正确初始化并且指向有效的值。这样一来,你就能把Lua这门超级灵活的语言玩得溜溜的,让它变成你的趁手神器,而不是绊你前进步伐的小石头。
2023-11-12 10:48:28
109
断桥残雪
转载文章
...02 复习 显示所有数据 show databases; 创建新数据库,设置编码方式utf8 create database demo2 default charset utf8; 显示创建数据的语句 show create database demo2; 删除数据库 drop database demo2; 选择使用指定的数据库 use demo1; 查看库中所有表 show tables; 创建表 create table book(bid int(4) primary key comment '书id', bname varchar(50) comment '书名',pub varchar(50) comment '出版社',author varchar(50) comment '作者' )engine=myisam charset=utf8; 所有字段名,使用,所有的字符串使用''或者"" 查看建表语句 show create table book; 查看表结构 desc book; 修改表名 rename table book to book1; 修改表属性 ,引擎和字符集 alter table book1 engine=innodb charset=utf8; 添加字段 first after alter table book1 add(type varchar(20) comment '类型',numinput int(10) comment '进货量',numstore int(10) comment '库存量'); 修改字段名 bid bno alter table book1 change bid bno int(4); 修改顺序 pub 放到author后面 alter table book1 modify pub varchar(50) after author; 修改数据类型 bno int(4) -->int(10) alter table book1 modify bno int(10); 删除字段 alter table book1 drop 字段名; 删除表 drop table 表名; 插入语句 insert into book1(bno,bname,author,type) values(1001,'斗破苍穹','天蚕土豆','玄幻');insert into book1(bno,bname,author,type) values(1002,'全职高手','蝴蝶兰','网游竞技');insert into book1(bno,bname,author,type) values(1003,'鬼吹灯','天下霸唱','恐怖');insert into book1(bno,bname,author,type)values(1004,'西游记','吴承恩','4大名著');insert into book1(bno,bname,author,type)values(1005,'java基础','王克晶','达内学习手册'); update语句 把1005号书,修改成'天线宝宝',作者不详,类型少儿 把1004号书修改成'天龙八部',作者金庸,类型武侠 update book1 set bname="天线宝宝",author="作者不详",type="少儿" where bno=1005; 删除类型是'恐怖'的所有书籍 删除全表记录 删除表格 修改book名称为book_item rename table book to book_item; 在表格尾部添加字段price double(7,2) alter table book_item add price double(7,2); 把price字段的位置放到author之后 alter table book_item modify price double(7,2) after author; 把表中存在的数据添加价格,每本书都在100~1000之间,自定 update book_item set price=199 where bno=1001; 修改1001的价格为500元 把所有字段的null字段补全 update book_item set pub="达内出版社",numinput=500,numstore=100 where pub is null; 删除价格小于150的所有条目 删除所有数据 SQL分类 数据定义语言 DDL 重点 数据操纵语言 DML 重点 增 删 改 数据查询语言 DQL select 查 事务控制语言 TCL 数据库控制语言 DCL 数据定义语言 DDL - 负责数据结构定义,与创建数据库对象的语言- 常用create alter drop- DDL不支持事务,DDL语句执行之后,不能回滚 数据操纵语言 DML - 对数据库中更改数据操作的语句- select insert update delete--> CRUD 增删改查- 通常把select相关操作,单独出来,称之为DQL- DML支持事务,在非自动提交模式时,可以利用rollback回滚操作. 数据查询语言 DQL - 筛选,分组,连表查询 面试重点 TCL 和 DCL - 事务控制语句TCL- 负责实现数据库中事务支持的语言,commit rollback savepoint等指令- DCL数据库控制语言- 管理数据库的授权,角色控制等,grant(授权),revoke(取消授权) 练习: 案例:创建一张表customer(顾客) create table customer(cid int(4) primary key comment '顾客编号',cname varchar(50) comment '顾客姓名',sex char(5) comment '顾客性别',address varchar(50) comment '地址',phone varchar(11) comment '手机',email varchar(50) comment '邮箱'); show create table customer; 插入5条数据 insert into customer values(1001,'小明','男','楼上18号','123','123@163.com');insert into customer values(1002,'小红','女','楼上17号','1234','1234@163.com');insert into customer values(1003,'老王','男','楼上18号隔壁','1234','1234@163.com');insert into customer values(1004,'老宋','男','楼上17号隔壁','1234','1234@163.com');insert into customer values(1005,'小马','女','楼上17号隔壁','1234','1234@163.com'); -1 修改一条数据的姓名 小红的姓名 -2 修改一条数据的性别 老王的性别 -3 修改一条数据的电话 1001号的电话 -4 修改一条数据的邮箱 邮箱为123@163.com,改成323@163.com -5 查询性别为 男的所有数据 select from customer where sex="男"; -6 自定义DDL操作的需求,5道题,可以同上面book表的操作 数据库数据类型 主要包括5大类 整数类型 int, big int 浮点数类型 double decimal 字符串类型 char varchar text 日期类型 date datetime timestamp time year... 其他数据类型 set.... 字符串 - char(固定长度) 定长字符串 最多255个字节- 定多少长度,就占用多少长度- 多了放不进去,少了用空格补全- 不认识内容尾部的空格- varchar(最大长度) 变长字符串 最大65535字节,但是使用一般不超过255- 只要不超过定的长度,都可以放进去- 以内容真实长度为准- 认识内容尾部的空格- text 最大65535字节- blob 大数据对象,以二进制(字节)的方式存储 整数 tinyint 1字节 smallint 2字节 int 4字节 bigint 8字节 int(6)影响的是查询时显示长度(zerofill)不影响数据的保存长度 create table t1(id1 int,id2 int(5)); insert into t1 values(111111,111111); alter table t1 modify id1 int zerofill; alter table t1 modify id2 int(5) zerofill; insert into t1 values (1,1); float 4字节 double 8字节 double(8,2) 可能会产生精度的缺失 10.0/3 3.3333333336 decimal 不会缺失精度,但是使用的时候需要指定总长度和小数位数 日期 - date 年月日- time 时分秒- datetime 年月日时分秒,到9999年,而且需要手动输入,如果没有手动输入,就显示null.- timestamp 年月日时分秒,在没有数据手动插入时,自动填入当前时间.最大值2038- bigint 1970-1-1 0:0:0 格林威治时间 案例:创建表t,字段d1 date,d2 time,d3 datetime,d4 timestamp create table t(id int,d1 date,d2 time,d3 datetime,d4 timestamp);insert into t (d1,d2) values ('1910-01-10','12:32:12');insert into t values(1,'2018-12-21','15:12:00','1995-02-10 12:08:12','2030-10-10 15:19:32');insert into t values(2,'3018-01-25','15:12:34','9234-12-31 12:12:12','2030-12-31 12:12:12');insert into t values(2,'3018-01-25','15:12:34','9999-12-31 23:59:59','2030-12-31 12:12:12'); 练习 创建人物表,插入,修改,查询 create table person(id int(4) primary key,name varchar(50),age int(3));insert into person values(1,"梅超风",36);insert into person values(2,"洪七公",96);insert into person values(3,"杨过",40);insert into person values(4,"令狐冲",28);insert into person values(5,"张三丰",100);insert into person values(6,"张翠山",27);insert into person values(7,"张无忌",27);insert into person values(8,"赵敏",18);insert into person values(9,"独孤求败",250);insert into person values(10,"楚留香",36);1.案例:修改张三丰的name为刘备,id为11update person set name="刘备",id=11 where name="张三丰";2.案例:修改2号人物的的name为夏侯渊update person set name="夏侯渊" where id=2;3.案例:根据条件修改person表中的数据,修改id是6的数据中,姓名改为'任我行', 年龄改为39update person set name="任我行",age=39 where id=6;4.案例:修改姓名是‘楚留香'的数据,把id改为20,年龄改为19update person set id=20,age=19 where name="楚留香";5.案例:把person所有的数据的年龄全部改为20 update person set age=20;6.案例:修改id为7的数据,把id改为100,姓名改为杨过,年龄改为21update person set id=100,name="杨过",age=21 where id=7;7.案例:修改姓名是独孤求败,把年龄改为35update person set age=35 where name="独孤求败";8.案例:修改id=8的信息,把姓名改为房玄龄update person set name="房玄龄" where id=8;9.案例 :修改id为20并且年龄为20的人的姓名为刘德华(郑少秋也行)提示 where...and...update person set name="郑少秋" where id=20 and age=20; 查询 没有条件的简单查询 select from 表名;查询表中所有的数据 select from person; select from t; select from emp; select from dept; 查询某些列中的值 select name as '姓名' from person; select name as '姓名',age as '年龄' from person; select id as '编号',name as '姓名',age as '年龄' from person; 学习过程的编程习惯select from 表; 工作中的编程习惯select id,name,age from person; 查询emp表中所有员工的姓名,上级领导的编号,职位,工资 select ename,mgr,job,sal from emp; 查询emp表中所有员工的编号,姓名,所属部门编号,工资 select empno,ename,deptno,sal from emp; 查询dept表中所有部门的名称和地址 select dname,loc from dept; 如果忘记了mysql的用户名和密码怎么办 卸载重新装 不重装软件如何修改密码 1.停止mysql服务 2.cmd中输入一个命令 mysqld --skip-grant-tables; -通过控制台,开启了一个mysql服务 3.开启一个新的cmd -mysql -u root -p 可以不使用密码进入数据库 show databases;----mysql 5. use mysql; 6. update user set password=password('新密码') where user="root"; 7. 关闭mysqld这个服务/进程 8. 重启mysql服务 作业 mysql02,一天的代码重新敲一遍,熟悉emp和dept列名 本篇文章为转载内容。原文链接:https://blog.csdn.net/sinat_41915844/article/details/79770973。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-02-16 12:44:07
543
转载
转载文章
...y实现应用程序的用户管理,以及实现应用程序的认证与授权等相关技术,译者希望本系列教程能成为掌握ASP.NET Identity技术的一份完整而有价值的资料。读者若是能够按照文章的描述,一边阅读、一边实践、一边理解,定能有意想不到的巨大收获!希望本系列博文能够得到广大园友的高度推荐。 15 Advanced ASP.NET Identity 15 ASP.NET Identity高级技术 In this chapter, I finish my description of ASP.NET Identity by showing you some of the advanced features it offers. I demonstrate how you can extend the database schema by defining custom properties on the user class and how to use database migrations to apply those properties without deleting the data in the ASP.NET Identity database. I also explain how ASP.NET Identity supports the concept of claims and demonstrates how they can be used to flexibly authorize access to action methods. I finish the chapter—and the book—by showing you how ASP.NET Identity makes it easy to authenticate users through third parties. I demonstrate authentication with Google accounts, but ASP.NET Identity has built-in support for Microsoft, Facebook, and Twitter accounts as well. Table 15-1 summarizes this chapter. 本章将完成对ASP.NET Identity的描述,向你展示它所提供的一些高级特性。我将演示,你可以扩展ASP.NET Identity的数据库架构,其办法是在用户类上定义一些自定义属性。也会演示如何使用数据库迁移,这样可以运用自定义属性,而不必删除ASP.NET Identity数据库中的数据。还会解释ASP.NET Identity如何支持声明(Claims)概念,并演示如何将它们灵活地用来对动作方法进行授权访问。最后向你展示ASP.NET Identity很容易通过第三方部件来认证用户,以此结束本章以及本书。将要演示的是使用Google账号认证,但ASP.NET Identity对于Microsoft、Facebook以及Twitter账号,都有内建的支持。表15-1是本章概要。 Table 15-1. Chapter Summary 表15-1. 本章概要 Problem 问题 Solution 解决方案 Listing 清单号 Store additional information about users. 存储用户的附加信息 Define custom user properties. 定义自定义用户属性 1–3, 8–11 Update the database schema without deleting user data. 更新数据库架构而不删除用户数据 Perform a database migration. 执行数据库迁移 4–7 Perform fine-grained authorization. 执行细粒度授权 Use claims. 使用声明(Claims) 12–14 Add claims about a user. 添加用户的声明(Claims) Use the ClaimsIdentity.AddClaims method. 使用ClaimsIdentity.AddClaims方法 15–19 Authorize access based on claim values. 基于声明(Claims)值授权访问 Create a custom authorization filter attribute. 创建一个自定义的授权过滤器注解属性 20–21 Authenticate through a third party. 通过第三方认证 Install the NuGet package for the authentication provider, redirect requests to that provider, and specify a callback URL that creates the user account. 安装认证提供器的NuGet包,将请求重定向到该提供器,并指定一个创建用户账号的回调URL。 22–25 15.1 Preparing the Example Project 15.1 准备示例项目 In this chapter, I am going to continue working on the Users project I created in Chapter 13 and enhanced in Chapter 14. No changes to the application are required, but start the application and make sure that there are users in the database. Figure 15-1 shows the state of my database, which contains the users Admin, Alice, Bob, and Joe from the previous chapter. To check the users, start the application and request the /Admin/Index URL and authenticate as the Admin user. 本章打算继续使用第13章创建并在第14章增强的Users项目。对应用程序无需做什么改变,但需要启动应用程序,并确保数据库中有一些用户。图15-1显示了数据库的状态,它含有上一章的用户Admin、Alice、Bob以及Joe。为了检查用户,请启动应用程序,请求/Admin/Index URL,并以Admin用户进行认证。 Figure 15-1. The initial users in the Identity database 图15-1. Identity数据库中的最初用户 I also need some roles for this chapter. I used the RoleAdmin controller to create roles called Users and Employees and assigned the users to those roles, as described in Table 15-2. 本章还需要一些角色。我用RoleAdmin控制器创建了角色Users和Employees,并为这些角色指定了一些用户,如表15-2所示。 Table 15-2. The Types of Web Forms Code Nuggets 表15-2. 角色及成员(作者将此表的标题写错了——译者注) Role 角色 Members 成员 Users Alice, Joe Employees Alice, Bob Figure 15-2 shows the required role configuration displayed by the RoleAdmin controller. 图15-2显示了由RoleAdmin控制器所显示出来的必要的角色配置。 Figure 15-2. Configuring the roles required for this chapter 图15-2. 配置本章所需的角色 15.2 Adding Custom User Properties 15.2 添加自定义用户属性 When I created the AppUser class to represent users in Chapter 13, I noted that the base class defined a basic set of properties to describe the user, such as e-mail address and telephone number. Most applications need to store more information about users, including persistent application preferences and details such as addresses—in short, any data that is useful to running the application and that should last between sessions. In ASP.NET Membership, this was handled through the user profile system, but ASP.NET Identity takes a different approach. 我在第13章创建AppUser类来表示用户时曾做过说明,基类定义了一组描述用户的基本属性,如E-mail地址、电话号码等。大多数应用程序还需要存储用户的更多信息,包括持久化应用程序爱好以及地址等细节——简言之,需要存储对运行应用程序有用并且在各次会话之间应当保持的任何数据。在ASP.NET Membership中,这是通过用户资料(User Profile)系统来处理的,但ASP.NET Identity采取了一种不同的办法。 Because the ASP.NET Identity system uses Entity Framework to store its data by default, defining additional user information is just a matter of adding properties to the user class and letting the Code First feature create the database schema required to store them. Table 15-3 puts custom user properties in context. 因为ASP.NET Identity默认是使用Entity Framework来存储其数据的,定义附加的用户信息只不过是给用户类添加属性的事情,然后让Code First特性去创建需要存储它们的数据库架构即可。表15-3描述了自定义用户属性的情形。 Table 15-3. Putting Cusotm User Properties in Context 表15-3. 自定义用户属性的情形 Question 问题 Answer 回答 What is it? 什么是自定义用户属性? Custom user properties allow you to store additional information about your users, including their preferences and settings. 自定义用户属性让你能够存储附加的用户信息,包括他们的爱好和设置。 Why should I care? 为何要关心它? A persistent store of settings means that the user doesn’t have to provide the same information each time they log in to the application. 设置的持久化存储意味着,用户不必每次登录到应用程序时都提供同样的信息。 How is it used by the MVC framework? 在MVC框架中如何使用它? This feature isn’t used directly by the MVC framework, but it is available for use in action methods. 此特性不是由MVC框架直接使用的,但它在动作方法中使用是有效的。 15.2.1 Defining Custom Properties 15.2.1 定义自定义属性 Listing 15-1 shows how I added a simple property to the AppUser class to represent the city in which the user lives. 清单15-1演示了如何给AppUser类添加一个简单的属性,用以表示用户生活的城市。 Listing 15-1. Adding a Property in the AppUser.cs File 清单15-1. 在AppUser.cs文件中添加属性 using System;using Microsoft.AspNet.Identity.EntityFramework;namespace Users.Models { public enum Cities {LONDON, PARIS, CHICAGO}public class AppUser : IdentityUser {public Cities City { get; set; } }} I have defined an enumeration called Cities that defines values for some large cities and added a property called City to the AppUser class. To allow the user to view and edit their City property, I added actions to the Home controller, as shown in Listing 15-2. 这里定义了一个枚举,名称为Cities,它定义了一些大城市的值,另外给AppUser类添加了一个名称为City的属性。为了让用户能够查看和编辑City属性,给Home控制器添加了几个动作方法,如清单15-2所示。 Listing 15-2. Adding Support for Custom User Properties in the HomeController.cs File 清单15-2. 在HomeController.cs文件中添加对自定义属性的支持 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models;namespace Users.Controllers {public class HomeController : Controller {[Authorize]public ActionResult Index() {return View(GetData("Index"));}[Authorize(Roles = "Users")]public ActionResult OtherAction() {return View("Index", GetData("OtherAction"));}private Dictionary<string, object> GetData(string actionName) {Dictionary<string, object> dict= new Dictionary<string, object>();dict.Add("Action", actionName);dict.Add("User", HttpContext.User.Identity.Name);dict.Add("Authenticated", HttpContext.User.Identity.IsAuthenticated);dict.Add("Auth Type", HttpContext.User.Identity.AuthenticationType);dict.Add("In Users Role", HttpContext.User.IsInRole("Users"));return dict;} [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;await UserManager.UpdateAsync(user);return View(user);}private AppUser CurrentUser {get {return UserManager.FindByName(HttpContext.User.Identity.Name);} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } I added a CurrentUser property that uses the AppUserManager class to retrieve an AppUser instance to represent the current user. I pass the AppUser object as the view model object in the GET version of the UserProps action method, and the POST method uses it to update the value of the new City property. Listing 15-3 shows the UserProps.cshtml view, which displays the City property value and contains a form to change it. 我添加了一个CurrentUser属性,它使用AppUserManager类接收了表示当前用户的AppUser实例。在GET版本的UserProps动作方法中,传递了这个AppUser对象作为视图模型。而在POST版的方法中用它更新了City属性的值。清单15-3显示了UserProps.cshtml视图,它显示了City属性的值,并包含一个修改它的表单。 Listing 15-3. The Contents of the UserProps.cshtml File in the Views/Home Folder 清单15-3. Views/Home文件夹中UserProps.cshtml文件的内容 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";}<div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr></table></div> @using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Caution Don’t start the application when you have created the view. In the sections that follow, I demonstrate how to preserve the contents of the database, and if you start the application now, the ASP.NET Identity users will be deleted. 警告:创建了视图之后不要启动应用程序。在以下小节中,将演示如何保留数据库的内容,如果现在启动应用程序,将会删除ASP.NET Identity的用户。 15.2.2 Preparing for Database Migration 15.2.2 准备数据库迁移 The default behavior for the Entity Framework Code First feature is to drop the tables in the database and re-create them whenever classes that drive the schema have changed. You saw this in Chapter 14 when I added support for roles: When the application was started, the database was reset, and the user accounts were lost. Entity Framework Code First特性的默认行为是,一旦修改了派生数据库架构的类,便会删除数据库中的数据表,并重新创建它们。在第14章可以看到这种情况,在我添加角色支持时:当重启应用程序后,数据库被重置,用户账号也丢失。 Don’t start the application yet, but if you were to do so, you would see a similar effect. Deleting data during development is usually not a problem, but doing so in a production setting is usually disastrous because it deletes all of the real user accounts and causes a panic while the backups are restored. In this section, I am going to demonstrate how to use the database migration feature, which updates a Code First schema in a less brutal manner and preserves the existing data it contains. 不要启动应用程序,但如果你这么做了,会看到类似的效果。在开发期间删除数据没什么问题,但如果在产品设置中这么做了,通常是灾难性的,因为它会删除所有真实的用户账号,而备份恢复是很痛苦的事。在本小节中,我打算演示如何使用数据库迁移特性,它能以比较温和的方式更新Code First的架构,并保留架构中的已有数据。 The first step is to issue the following command in the Visual Studio Package Manager Console: 第一个步骤是在Visual Studio的“Package Manager Console(包管理器控制台)”中发布以下命令: Enable-Migrations –EnableAutomaticMigrations This enables the database migration support and creates a Migrations folder in the Solution Explorer that contains a Configuration.cs class file, the contents of which are shown in Listing 15-4. 它启用了数据库的迁移支持,并在“Solution Explorer(解决方案资源管理器)”创建一个Migrations文件夹,其中含有一个Configuration.cs类文件,内容如清单15-4所示。 Listing 15-4. The Contents of the Configuration.cs File 清单15-4. Configuration.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity;using System.Data.Entity.Migrations;using System.Linq;internal sealed class Configuration: DbMigrationsConfiguration<Users.Infrastructure.AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(Users.Infrastructure.AppIdentityDbContext context) {// This method will be called after migrating to the latest version.// 此方法将在迁移到最新版本时调用// You can use the DbSet<T>.AddOrUpdate() helper extension method// to avoid creating duplicate seed data. E.g.// 例如,你可以使用DbSet<T>.AddOrUpdate()辅助器方法来避免创建重复的种子数据//// context.People.AddOrUpdate(// p => p.FullName,// new Person { FullName = "Andrew Peters" },// new Person { FullName = "Brice Lambson" },// new Person { FullName = "Rowan Miller" }// );//} }} Tip You might be wondering why you are entering a database migration command into the console used to manage NuGet packages. The answer is that the Package Manager Console is really PowerShell, which is a general-purpose tool that is mislabeled by Visual Studio. You can use the console to issue a wide range of helpful commands. See http://go.microsoft.com/fwlink/?LinkID=108518 for details. 提示:你可能会觉得奇怪,为什么要在管理NuGet包的控制台中输入数据库迁移的命令?答案是“Package Manager Console(包管理控制台)”是真正的PowerShell,这是Visual studio冒用的一个通用工具。你可以使用此控制台发送大量的有用命令,详见http://go.microsoft.com/fwlink/?LinkID=108518。 The class will be used to migrate existing content in the database to the new schema, and the Seed method will be called to provide an opportunity to update the existing database records. In Listing 15-5, you can see how I have used the Seed method to set a default value for the new City property I added to the AppUser class. (I have also updated the class file to reflect my usual coding style.) 这个类将用于把数据库中的现有内容迁移到新的数据库架构,Seed方法的调用为更新现有数据库记录提供了机会。在清单15-5中可以看到,我如何用Seed方法为新的City属性设置默认值,City是添加到AppUser类中自定义属性。(为了体现我一贯的编码风格,我对这个类文件也进行了更新。) Listing 15-5. Managing Existing Content in the Configuration.cs File 清单15-5. 在Configuration.cs文件中管理已有内容 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models;namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);}foreach (AppUser dbUser in userMgr.Users) {dbUser.City = Cities.PARIS;}context.SaveChanges();} }} You will notice that much of the code that I added to the Seed method is taken from the IdentityDbInit class, which I used to seed the database with an administration user in Chapter 14. This is because the new Configuration class added to support database migrations will replace the seeding function of the IdentityDbInit class, which I’ll update shortly. Aside from ensuring that there is an admin user, the statements in the Seed method that are important are the ones that set the initial value for the City property I added to the AppUser class, as follows: 你可能会注意到,添加到Seed方法中的许多代码取自于IdentityDbInit类,在第14章中我用这个类将管理用户植入了数据库。这是因为这个新添加的、用以支持数据库迁移的Configuration类,将代替IdentityDbInit类的种植功能,我很快便会更新这个类。除了要确保有admin用户之外,在Seed方法中的重要语句是那些为AppUser类的City属性设置初值的语句,如下所示: ...foreach (AppUser dbUser in userMgr.Users) { dbUser.City = Cities.PARIS;}context.SaveChanges();... You don’t have to set a default value for new properties—I just wanted to demonstrate that the Seed method in the Configuration class can be used to update the existing user records in the database. 你不一定要为新属性设置默认值——这里只是想演示Configuration类中的Seed方法,可以用它更新数据库中的已有用户记录。 Caution Be careful when setting values for properties in the Seed method for real projects because the values will be applied every time you change the schema, overriding any values that the user has set since the last schema update was performed. I set the value of the City property just to demonstrate that it can be done. 警告:在用于真实项目的Seed方法中为属性设置值时要小心,因为你每一次修改架构时,都会运用这些值,这会将自执行上一次架构更新之后,用户设置的任何数据覆盖掉。这里设置City属性的值只是为了演示它能够这么做。 Changing the Database Context Class 修改数据库上下文类 The reason that I added the seeding code to the Configuration class is that I need to change the IdentityDbInit class. At present, the IdentityDbInit class is derived from the descriptively named DropCreateDatabaseIfModelChanges<AppIdentityDbContext> class, which, as you might imagine, drops the entire database when the Code First classes change. Listing 15-6 shows the changes I made to the IdentityDbInit class to prevent it from affecting the database. 在Configuration类中添加种植代码的原因是我需要修改IdentityDbInit类。此时,IdentityDbInit类派生于描述性命名的DropCreateDatabaseIfModelChanges<AppIdentityDbContext> 类,和你相像的一样,它会在Code First类改变时删除整个数据库。清单15-6显示了我对IdentityDbInit类所做的修改,以防止它影响数据库。 Listing 15-6. Preventing Database Schema Changes in the AppIdentityDbContext.cs File 清单15-6. 在AppIdentityDbContext.cs文件是阻止数据库架构变化 using System.Data.Entity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Models;using Microsoft.AspNet.Identity; namespace Users.Infrastructure {public class AppIdentityDbContext : IdentityDbContext<AppUser> {public AppIdentityDbContext() : base("IdentityDb") { }static AppIdentityDbContext() {Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());}public static AppIdentityDbContext Create() {return new AppIdentityDbContext();} } public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext> {} } I have removed the methods defined by the class and changed its base to NullDatabaseInitializer<AppIdentityDbContext> , which prevents the schema from being altered. 我删除了这个类中所定义的方法,并将它的基类改为NullDatabaseInitializer<AppIdentityDbContext> ,它可以防止架构修改。 15.2.3 Performing the Migration 15.2.3 执行迁移 All that remains is to generate and apply the migration. First, run the following command in the Package Manager Console: 剩下的事情只是生成并运用迁移了。首先,在“Package Manager Console(包管理器控制台)”中执行以下命令: Add-Migration CityProperty This creates a new migration called CityProperty (I like my migration names to reflect the changes I made). A class new file will be added to the Migrations folder, and its name reflects the time at which the command was run and the name of the migration. My file is called 201402262244036_CityProperty.cs, for example. The contents of this file contain the details of how Entity Framework will change the database during the migration, as shown in Listing 15-7. 这创建了一个名称为CityProperty的新迁移(我比较喜欢让迁移的名称反映出我所做的修改)。这会在文件夹中添加一个新的类文件,而且其命名会反映出该命令执行的时间以及迁移名称,例如,我的这个文件名称为201402262244036_CityProperty.cs。该文件的内容含有迁移期间Entity Framework修改数据库的细节,如清单15-7所示。 Listing 15-7. The Contents of the 201402262244036_CityProperty.cs File 清单15-7. 201402262244036_CityProperty.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity.Migrations; public partial class Init : DbMigration {public override void Up() {AddColumn("dbo.AspNetUsers", "City", c => c.Int(nullable: false));}public override void Down() {DropColumn("dbo.AspNetUsers", "City");} }} The Up method describes the changes that have to be made to the schema when the database is upgraded, which in this case means adding a City column to the AspNetUsers table, which is the one that is used to store user records in the ASP.NET Identity database. Up方法描述了在数据库升级时,需要对架构所做的修改,在这个例子中,意味着要在AspNetUsers数据表中添加City数据列,该数据表是ASP.NET Identity数据库用来存储用户记录的。 The final step is to perform the migration. Without starting the application, run the following command in the Package Manager Console: 最后一步是执行迁移。无需启动应用程序,只需在“Package Manager Console(包管理器控制台)”中运行以下命令即可: Update-Database –TargetMigration CityProperty The database schema will be modified, and the code in the Configuration.Seed method will be executed. The existing user accounts will have been preserved and enhanced with a City property (which I set to Paris in the Seed method). 这会修改数据库架构,并执行Configuration.Seed方法中的代码。已有用户账号会被保留,且增强了City属性(我在Seed方法中已将其设置为“Paris”)。 15.2.4 Testing the Migration 15.2.4 测试迁移 To test the effect of the migration, start the application, navigate to the /Home/UserProps URL, and authenticate as one of the Identity users (for example, as Alice with the password MySecret). Once authenticated, you will see the current value of the City property for the user and have the opportunity to change it, as shown in Figure 15-3. 为了测试迁移的效果,启动应用程序,导航到/Home/UserProps URL,并以Identity中的用户(例如Alice,口令MySecret)进行认证。一旦已被认证,便会看到该用户City属性的当前值,并可以对其进行修改,如图15-3所示。 Figure 15-3. Displaying and changing a custom user property 图15-3. 显示和个性自定义用户属性 15.2.5 Defining an Additional Property 15.2.5 定义附加属性 Now that database migrations are set up, I am going to define a further property just to demonstrate how subsequent changes are handled and to show a more useful (and less dangerous) example of using the Configuration.Seed method. Listing 15-8 shows how I added a Country property to the AppUser class. 现在,已经建立了数据库迁移,我打算再定义一个属性,这恰恰演示了如何处理持续不断的修改,也为了演示Configuration.Seed方法更有用(至少无害)的示例。清单15-8显示了我在AppUser类上添加了一个Country属性。 Listing 15-8. Adding Another Property in the AppUserModels.cs File 清单15-8. 在AppUserModels.cs文件中添加另一个属性 using System;using Microsoft.AspNet.Identity.EntityFramework; namespace Users.Models {public enum Cities {LONDON, PARIS, CHICAGO} public enum Countries {NONE, UK, FRANCE, USA}public class AppUser : IdentityUser {public Cities City { get; set; }public Countries Country { get; set; }public void SetCountryFromCity(Cities city) {switch (city) {case Cities.LONDON:Country = Countries.UK;break;case Cities.PARIS:Country = Countries.FRANCE;break;case Cities.CHICAGO:Country = Countries.USA;break;default:Country = Countries.NONE;break;} }} } I have added an enumeration to define the country names and a helper method that selects a country value based on the City property. Listing 15-9 shows the change I made to the Configuration class so that the Seed method sets the Country property based on the City, but only if the value of Country is NONE (which it will be for all users when the database is migrated because the Entity Framework sets enumeration columns to the first value). 我已经添加了一个枚举,它定义了国家名称。还添加了一个辅助器方法,它可以根据City属性选择一个国家。清单15-9显示了对Configuration类所做的修改,以使Seed方法根据City设置Country属性,但只当Country为NONE时才进行设置(在迁移数据库时,所有用户都是NONE,因为Entity Framework会将枚举列设置为枚举的第一个值)。 Listing 15-9. Modifying the Database Seed in the Configuration.cs File 清单15-9. 在Configuration.cs文件中修改数据库种子 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models; namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);} foreach (AppUser dbUser in userMgr.Users) {if (dbUser.Country == Countries.NONE) {dbUser.SetCountryFromCity(dbUser.City);} }context.SaveChanges();} }} This kind of seeding is more useful in a real project because it will set a value for the Country property only if one has not already been set—subsequent migrations won’t be affected, and user selections won’t be lost. 这种种植在实际项目中会更有用,因为它只会在Country属性未设置时,才会设置Country属性的值——后继的迁移不会受到影响,因此不会失去用户的选择。 1. Adding Application Support 1. 添加应用程序支持 There is no point defining additional user properties if they are not available in the application, so Listing 15-10 shows the change I made to the Views/Home/UserProps.cshtml file to display the value of the Country property. 应用程序中如果没有定义附加属性的地方,则附加属性就无法使用了,因此,清单15-10显示了我对Views/Home/UserProps.cshtml文件的修改,以显示Country属性的值。 Listing 15-10. Displaying an Additional Property in the UserProps.cshtml File 清单15-10. 在UserProps.cshtml文件中显示附加属性 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";} <div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr> <tr><th>Country</th><td>@Model.Country</td></tr></table></div>@using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Listing 15-11 shows the corresponding change I made to the Home controller to update the Country property when the City value changes. 为了在City值变化时能够更新Country属性,清单15-11显示了我对Home控制器所做的相应修改。 Listing 15-11. Setting Custom Properties in the HomeController.cs File 清单15-11. 在HomeController.cs文件中设置自定义属性 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models; namespace Users.Controllers {public class HomeController : Controller {// ...other action methods omitted for brevity...// ...出于简化,这里忽略了其他动作方法... [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;user.SetCountryFromCity(city);await UserManager.UpdateAsync(user);return View(user);}// ...properties omitted for brevity...// ...出于简化,这里忽略了一些属性...} } 2. Performing the Migration 2. 准备迁移 All that remains is to create and apply a new migration. Enter the following command into the Package Manager Console: 剩下的事情就是创建和运用新的迁移了。在“Package Manager Console(包管理器控制台)”中输入以下命令: Add-Migration CountryProperty This will generate another file in the Migrations folder that contains the instruction to add the Country column. To apply the migration, execute the following command: 这将在Migrations文件夹中生成另一个文件,它含有添加Country数据表列的指令。为了运用迁移,可执行以下命令: Update-Database –TargetMigration CountryProperty The migration will be performed, and the value of the Country property will be set based on the value of the existing City property for each user. You can check the new user property by starting the application and authenticating and navigating to the /Home/UserProps URL, as shown in Figure 15-4. 这将执行迁移,Country属性的值将根据每个用户当前的City属性进行设置。通过启动应用程序,认证并导航到/Home/UserProps URL,便可以查看新的用户属性,如图15-4所示。 Figure 15-4. Creating an additional user property 图15-4. 创建附加用户属性 Tip Although I am focused on the process of upgrading the database, you can also migrate back to a previous version by specifying an earlier migration. Use the –Force argument make changes that cause data loss, such as removing a column. 提示:虽然我们关注了升级数据库的过程,但你也可以回退到以前的版本,只需指定一个早期的迁移即可。使用-Force参数进行修改,会引起数据丢失,例如删除数据表列。 15.3 Working with Claims 15.3 使用声明(Claims) In older user-management systems, such as ASP.NET Membership, the application was assumed to be the authoritative source of all information about the user, essentially treating the application as a closed world and trusting the data that is contained within it. 在旧的用户管理系统中,例如ASP.NET Membership,应用程序被假设成是用户所有信息的权威来源,本质上将应用程序视为是一个封闭的世界,并且只信任其中所包含的数据。 This is such an ingrained approach to software development that it can be hard to recognize that’s what is happening, but you saw an example of the closed-world technique in Chapter 14 when I authenticated users against the credentials stored in the database and granted access based on the roles associated with those credentials. I did the same thing again in this chapter when I added properties to the user class. Every piece of information that I needed to manage user authentication and authorization came from within my application—and that is a perfectly satisfactory approach for many web applications, which is why I demonstrated these techniques in such depth. 这是软件开发的一种根深蒂固的方法,使人很难认识到这到底意味着什么,第14章你已看到了这种封闭世界技术的例子,根据存储在数据库中的凭据来认证用户,并根据与凭据关联在一起的角色来授权访问。本章前述在用户类上添加属性,也做了同样的事情。我管理用户认证与授权所需的每一个数据片段都来自于我的应用程序——而且这是许多Web应用程序都相当满意的一种方法,这也是我如此深入地演示这些技术的原因。 ASP.NET Identity also supports an alternative approach for dealing with users, which works well when the MVC framework application isn’t the sole source of information about users and which can be used to authorize users in more flexible and fluid ways than traditional roles allow. ASP.NET Identity还支持另一种处理用户的办法,当MVC框架的应用程序不是有关用户的唯一信息源时,这种办法会工作得很好,而且能够比传统的角色授权更为灵活且流畅的方式进行授权。 This alternative approach uses claims, and in this section I’ll describe how ASP.NET Identity supports claims-based authorization. Table 15-4 puts claims in context. 这种可选的办法使用了“Claims(声明)”,因此在本小节中,我将描述ASP.NET Identity如何支持“Claims-Based Authorization(基于声明的授权)”。表15-4描述了声明(Claims)的情形。 提示:“Claim”在英文字典中不完全是“声明”的意思,根据本文的描述,感觉把它说成“声明”也不一定合适,所以在之后的译文中基本都写成中英文并用的形式,即“声明(Claims)”。根据表15-4中的声明(Claims)的定义:声明(Claims)是关于用户的一些信息片段。一个用户的信息片段当然有很多,每一个信息片段就是一项声明(Claim),用户的所有信息片段合起来就是该用户的声明(Claims)。请读者注意该单词的单复数形式——译者注 Table 15-4. Putting Claims in Context 表15-4. 声明(Claims)的情形 Question 问题 Answer 答案 What is it? 什么是声明(Claims)? Claims are pieces of information about users that you can use to make authorization decisions. Claims can be obtained from external systems as well as from the local Identity database. 声明(Claims)是关于用户的一些信息片段,可以用它们做出授权决定。声明(Claims)可以从外部系统获取,也可以从本地的Identity数据库获取。 Why should I care? 为何要关心它? Claims can be used to flexibly authorize access to action methods. Unlike conventional roles, claims allow access to be driven by the information that describes the user. 声明(Claims)可以用来对动作方法进行灵活的授权访问。与传统的角色不同,声明(Claims)让访问能够由描述用户的信息进行驱动。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework, but it is integrated into the standard authorization features, such as the Authorize attribute. 这不是直接由MVC框架使用的特性,但它集成到了标准的授权特性之中,例如Authorize注解属性。 Tip you don’t have to use claims in your applications, and as Chapter 14 showed, ASP.NET Identity is perfectly happy providing an application with the authentication and authorization services without any need to understand claims at all. 提示:你在应用程序中不一定要使用声明(Claims),正如第14章所展示的那样,ASP.NET Identity能够为应用程序提供充分的认证与授权服务,而根本不需要理解声明(Claims)。 15.3.1 Understanding Claims 15.3.1 理解声明(Claims) A claim is a piece of information about the user, along with some information about where the information came from. The easiest way to unpack claims is through some practical demonstrations, without which any discussion becomes too abstract to be truly useful. To get started, I added a Claims controller to the example project, the definition of which you can see in Listing 15-12. 一项声明(Claim)是关于用户的一个信息片段(请注意这个英文单词的单复数形式——译者注),并伴有该片段出自何处的某种信息。揭开声明(Claims)含义最容易的方式是做一些实际演示,任何讨论都会过于抽象根本没有真正的用处。为此,我在示例项目中添加了一个Claims控制器,其定义如清单15-12所示。 Listing 15-12. The Contents of the ClaimsController.cs File 清单15-12. ClaimsController.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} }} } Tip You may feel a little lost as I define the code for this example. Don’t worry about the details for the moment—just stick with it until you see the output from the action method and view that I define. More than anything else, that will help put claims into perspective. 提示:你或许会对我为此例定义的代码感到有点失望。此刻对此细节不必着急——只要稍事忍耐,当看到该动作方法和视图的输出便会明白。尤为重要的是,这有助于洞察声明(Claims)。 You can get the claims associated with a user in different ways. One approach is to use the Claims property defined by the user class, but in this example, I have used the HttpContext.User.Identity property to demonstrate the way that ASP.NET Identity is integrated with the rest of the ASP.NET platform. As I explained in Chapter 13, the HttpContext.User.Identity property returns an implementation of the IIdentity interface, which is a ClaimsIdentity object when working using ASP.NET Identity. The ClaimsIdentity class is defined in the System.Security.Claims namespace, and Table 15-5 shows the members it defines that are relevant to this chapter. 可以通过不同的方式获得与用户相关联的声明(Claims)。方法之一就是使用由用户类定义的Claims属性,但在这个例子中,我使用了HttpContext.User.Identity属性,目的是演示ASP.NET Identity与ASP.NET平台集成的方式(请注意这句话所表示的含义:用户类的Claims属性属于ASP.NET Identity,而HttpContext.User.Identity属性则属于ASP.NET平台。由此可见,ASP.NET Identity已经融合到了ASP.NET平台之中——译者注)。正如第13章所解释的那样,HttpContext.User.Identity属性返回IIdentity的接口实现,当使用ASP.NET Identity时,该实现是一个ClaimsIdentity对象。ClaimsIdentity类是在System.Security.Claims命名空间中定义的,表15-5显示了它所定义的与本章有关的成员。 Table 15-5. The Members Defined by the ClaimsIdentity Class 表15-5. ClaimsIdentity类所定义的成员 Name 名称 Description 描述 Claims Returns an enumeration of Claim objects representing the claims for the user. 返回表示用户声明(Claims)的Claim对象枚举 AddClaim(claim) Adds a claim to the user identity. 给用户添加一个声明(Claim) AddClaims(claims) Adds an enumeration of Claim objects to the user identity. 给用户添加Claim对象的枚举。 HasClaim(predicate) Returns true if the user identity contains a claim that matches the specified predicate. See the “Applying Claims” section for an example predicate. 如果用户含有与指定谓词匹配的声明(Claim)时,返回true。参见“运用声明(Claims)”中的示例谓词 RemoveClaim(claim) Removes a claim from the user identity. 删除用户的声明(Claim)。 Other members are available, but the ones in the table are those that are used most often in web applications, for reason that will become obvious as I demonstrate how claims fit into the wider ASP.NET platform. 还有一些可用的其它成员,但表中的这些是在Web应用程序中最常用的,随着我演示如何将声明(Claims)融入更宽泛的ASP.NET平台,它们为什么最常用就很显然了。 In Listing 15-12, I cast the IIdentity implementation to the ClaimsIdentity type and pass the enumeration of Claim objects returned by the ClaimsIdentity.Claims property to the View method. A Claim object represents a single piece of data about the user, and the Claim class defines the properties shown in Table 15-6. 在清单15-12中,我将IIdentity实现转换成了ClaimsIdentity类型,并且给View方法传递了ClaimsIdentity.Claims属性所返回的Claim对象的枚举。Claim对象所示表示的是关于用户的一个单一的数据片段,Claim类定义的属性如表15-6所示。 Table 15-6. The Properties Defined by the Claim Class 表15-6. Claim类定义的属性 Name 名称 Description 描述 Issuer Returns the name of the system that provided the claim 返回提供声明(Claim)的系统名称 Subject Returns the ClaimsIdentity object for the user who the claim refers to 返回声明(Claim)所指用户的ClaimsIdentity对象 Type Returns the type of information that the claim represents 返回声明(Claim)所表示的信息类型 Value Returns the piece of information that the claim represents 返回声明(Claim)所表示的信息片段 Listing 15-13 shows the contents of the Index.cshtml file that I created in the Views/Claims folder and that is rendered by the Index action of the Claims controller. The view adds a row to a table for each claim about the user. 清单15-13显示了我在Views/Claims文件夹中创建的Index.cshtml文件的内容,它由Claims控制器中的Index动作方法进行渲染。该视图为用户的每项声明(Claim)添加了一个表格行。 Listing 15-13. The Contents of the Index.cshtml File in the Views/Claims Folder 清单15-13. Views/Claims文件夹中Index.cshtml文件的内容 @using System.Security.Claims@using Users.Infrastructure@model IEnumerable<Claim>@{ ViewBag.Title = "Claims"; }<div class="panel panel-primary"><div class="panel-heading">Claims</div><table class="table table-striped"><tr><th>Subject</th><th>Issuer</th><th>Type</th><th>Value</th></tr>@foreach (Claim claim in Model.OrderBy(x => x.Type)) {<tr><td>@claim.Subject.Name</td><td>@claim.Issuer</td><td>@Html.ClaimType(claim.Type)</td><td>@claim.Value</td></tr>}</table></div> The value of the Claim.Type property is a URI for a Microsoft schema, which isn’t especially useful. The popular schemas are used as the values for fields in the System.Security.Claims.ClaimTypes class, so to make the output from the Index.cshtml view easier to read, I added an HTML helper to the IdentityHelpers.cs file, as shown in Listing 15-14. It is this helper that I use in the Index.cshtml file to format the value of the Claim.Type property. Claim.Type属性的值是一个微软模式(Microsoft Schema)的URI(统一资源标识符),这是特别有用的。System.Security.Claims.ClaimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
282
转载
MySQL
...一种普遍应用的关系型数据库管理系统,它能够应用于多种多样的的应用软件,涵盖数据挖掘,信息管理和网上交易。MySQL供给了一些有效手段来查阅数据库启动的过程,以协助你更好地管理你的数据库服务器。以下是如何查阅MySQL数据库启动的方法: 1.在命令行中输入以下命令启动MySQL服务器。sudo /etc/init.d/mysql start2.输入以下命令查阅MySQL的启动状态。sudo /etc/init.d/mysql status3.使用以下命令来启动MySQL服务器,如果MySQL未能启动,将会打印出错误信息。sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &4.使用以下命令重新启动MySQL服务器。sudo /etc/init.d/mysql restart5.使用以下命令停止MySQL服务器。sudo /etc/init.d/mysql stop 在查阅MySQL数据库启动的过程时,需要密切关注终端显示的信息。如果MySQL启动遇到错误或问题,你能够使用这些信息来解决它们。保持经常使用上面的命令能够协助你及时了解数据库服务器的启动情况。
2023-06-06 17:14:58
78
逻辑鬼才
转载文章
...持部署在服务端随报表数据一起传到客户端; 9、目标活:支持在数据文件中或模板中指定要输出的打印机,发票用针打、报表用激光打、小票用小票机,专机专打; 三、使用前提条件: 1、IE6以上版本、Chrome(谷歌浏览器)4.0以上版本、Firefox 4.0以上版本、Opera 11以上版本、Safari 5.0.2以上版本、iOS 4.2以上版本 或使用Chrome内核、Firefox内核的浏览器均可直接使用本打印系统; 2、在进行打印前,需要先设计好打印模板(模板设计器请见第五节); 3、打印数据必须Json的格式发送给打印服务器,并且数据必须满足指定的格式(见下文); 四、数据格式说明: 下面以一个跨境电商快递面单数据为例解释一下数据各项的含义; { "template": "waybill.fr3", /打印模板文件名。除了指定模板文件以外,还支持把模板嵌入到数据文件中,以实现在服务器端灵活使用打印模板,格式如下:/ /"template": "base64:QTBBRTNEQTE3MkFFQjIzNEFERD<后面省略>" / "ver": 4, /数据模板文件版本/ "Copies": 3, /打印份数,支持指定打印份数/ "Duplex": 1, /是否双面打印,0:默认,不双面,1:垂直,2:水平,3:单面打印(simplex)/ "Printer": "priPrinter", /指定打印机,本系统支持在数据文件中指定打印机,也支持在打印模板中指定打印机/ "PageNumbers": "", /要打印的页码范围,同打印机的打印设置里的格式相同,例如:"1,2,3"表示打印前3页, “2-5”:表示打印第2到5页,“1,2,4-8”表示打印第1、2、4到8页/ "Preview": 1, /是否预览,跟主界面上选择“预览”效果相同,取值为0:不预览,1:预览/ "Tables":[ /数据表数组/ { "Name": "Table1", /表名/ "Cols": [ /字段定义/ { "type": "str", /字段类型,可选值:String,Str,Integer,Int,Smallint,Float,Long, Blob,/ /对于图片、PDF等使用Blob类型,并把值进行Base64编码,并加前缀:/ / "base64/pdf:" 字段值是PDF; "base64/jpg:" 字段值是jpg; "base64/png:" 字段值是png; "base64/gif:" 字段值是gif; / "size": 255, /字段长度/ "name": "HAWB", /字段名称,必须与打印模板中的打印项名称相同/ "required": false /字段是否必填/ }, { "type": "int", "size": 0, "name": "NO", "required": false }, { "type": "float", "size": 0, "name": "报关公司面单号", "required": false }, { "type": "integer", "size": 0, "name": "公司内部单号", "required": false }, { "type": "str", "size": 255, "name": "发件人", "required": false }, { "type": "str", "size": 255, "name": "发件人地址", "required": false }, { "type": "str", "size": 255, "name": "发件人电话", "required": false }, { "type": "str", "size": 255, "name": "发货国家", "required": false }, { "type": "str", "size": 255, "name": "收件人", "required": false }, { "type": "str", "size": 255, "name": "收件人地址", "required": false }, { "type": "str", "size": 255, "name": "收件人电话", "required": false }, { "type": "str", "size": 255, "name": "收货人证件号码", "required": false }, { "type": "str", "size": 255, "name": "收货省份", "required": false }, { "type": "float", "size": 0, "name": "总计费重量", "required": false }, { "type": "int", "size": 0, "name": "总件数", "required": false }, { "type": "float", "size": 0, "name": "申报总价(CNY)", "required": false }, { "type": "float", "size": 0, "name": "申报总价(JPY)", "required": false }, { "type": "int", "size": 0, "name": "件数1", "required": false }, { "type": "str", "size": 255, "name": "品名1", "required": false }, { "type": "float", "size": 0, "name": "单价1(JPY)", "required": false }, { "type": "str", "size": 255, "name": "单位1", "required": false }, { "type": "float", "size": 0, "name": "申报总价1(CNY)", "required": false }, { "type": "float", "size": 0, "name": "申报总价1(JPY)", "required": false }, { "type": "int", "size": 0, "name": "件数2", "required": false }, { "type": "str", "size": 255, "name": "品名2", "required": false }, { "type": "float", "size": 0, "name": "单价2(JPY)", "required": false }, { "type": "str", "size": 255, "name": "单位2", "required": false }, { "type": "float", "size": 0, "name": "申报总价2(CNY)", "required": false }, { "type": "float", "size": 0, "name": "申报总价2(JPY)", "required": false }, { "type": "AutoInc", "size": 0, "name": "ID", "required": false }, { "type": "blob", "size": 0, "name": "附件", "required": false } ], "Data": [ /数据行定义,每一行含义见上面的字段定义/ { "HAWB": "860014010055", "NO": 1, "报关公司面单号": 200303900791, "公司内部单号": 730293, "发件人": "NAKAGAWA SUMIRE 2", "发件人地址": " 991-199-113,Kameido,Koto-ku,Tokyo", "发件人电话": "03-3999-3999", "发货国家": "日本", "收件人": "张三丰", "收件人地址": "上海市闵行区虹梅南路1660弄蔷薇八村99号9999室", "收件人电话": "182-1234-8888", "收货人证件号码": null, "收货省份": null, "总计费重量": 3.2, "总件数": 13, "申报总价(CNY)": null, "申报总价(JPY)": null, "件数1": 10, "品名1": "纸尿片", "单价1(JPY)": null, "单位1": null, "申报总价1(CNY)": null, "申报总价1(JPY)": null, "件数2": null, "品名2": null, "单价2(JPY)": null, "单位2": null, "申报总价2(CNY)": null, "申报总价2(JPY)": null, "ID": 1, "附件": "base64/pdf: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IDI3OCAyNzgKMjc4IDI3OCAyNzggMjc4IDI3OCAyNzggMjc4IDI3OCAyNzggMjc4IDI3OCAyNzggMjc4IDI3OCAyNzggMjc4CjI3OCA1NTYgNTU2IDMzMyA1NTYgNTU2IDU1NiA1NTYgMjc4IDY2NyAyNzggMjc4IDI3OCAyNzggMjc4IDY2NwoyNzggNjY3IDI3OCAyNzggMjc4IDI3OCAyNzggNjY3IDI3OCA2NjcgMjc4IDY2NyAyNzggNjY3IDI3OCAyNzgKMjc4IDY2NyAyNzggNjY3IDU1MiAyNzggMjc4IDI3OCAyNzggNTU2IDI3OCA1NTYgMjc4IDI3OCAyNzggNjY3CjI3OCA2NjcgMjc4IDI3OCAyNzggNjY3IDI3OCA2NjcgMjc4IDY2NyAyNzggNjY3IDI3OCA2NjcgMjc4IDI3OF0KL0VuY29kaW5nL1dpbkFuc2lFbmNvZGluZwovRm9udERlc2NyaXB0b3IgMTEgMCBSCj4+CmVuZG9iagoxMSAwIG9iago8PAovVHlwZS9Gb250RGVzY3JpcHRvcgovRm9udE5hbWUgL0FyaWFsTVQKL0ZsYWdzIDMyCi9Gb250QkJveFstNjY1IC0zMjUgMjAwMCAxMDA2XQovU3RlbVYgOTUKL0l0YWxpY0FuZ2xlIDAKL0NhcEhlaWdodCA5MDUKL0FzY2VudCA5MDUKL0Rlc2NlbnQgLTIxMgo+PgplbmRvYmoKMyAwIG9iago8PAovVHlwZS9QYWdlcwovQ291bnQgMQovS2lkc1s0IDAgUl0KPj4KZW5kb2JqCjIgMCBvYmoKPDwKL1R5cGUvQ2F0YWxvZwovUGFnZXMgMyAwIFIKL1BhZ2VMYXlvdXQvU2luZ2xlUGFnZQovVmlld2VyUHJlZmVyZW5jZXMgMTIgMCBSCj4+CmVuZG9iagoxMiAwIG9iago8PAovVHlwZS9WaWV3ZXJQcmVmZXJlbmNlcwo+PgplbmRvYmoKeHJlZgowIDEzCjAwMDAwMDAwMDAgNjU1MzUgZg0KMDAwMDAwMDAxNiAwMDAwMCBuDQowMDAwMDA0MjEzIDAwMDAwIG4NCjAwMDAwMDQxNTggMDAwMDAgbg0KMDAwMDAwMDcxNiAwMDAwMCBuDQowMDAwMDAwMjQxIDAwMDAwIG4NCjAwMDAwMDA4NzIgMDAwMDAgbg0KMDAwMDAwMjkyNyAwMDAwMCBuDQowMDAwMDAxMjQ1IDAwMDAwIG4NCjAwMDAwMDEwNTUgMDAwMDAgbg0KMDAwMDAwMTU2MiAwMDAwMCBuDQowMDAwMDAzOTg5IDAwMDAwIG4NCjAwMDAwMDQzMTAgMDAwMDAgbg0KdHJhaWxlcgo8PAovU2l6ZSAxMwovSW5mbyAxIDAgUgovUm9vdCAyIDAgUgovSURbPDVBMkU0QzkzOTdENEU0RDE3NkIwOTBDRUU3OTMxMzRGPjw1QTJFNEM5Mzk3RDRFNEQxNzZCMDkwQ0VFNzkzMTM0Rj5dCj4+CnN0YXJ0eHJlZgo0MzU2CiUlRU9GCg==", }, { "HAWB": "860014010035", "NO": 2, "报关公司面单号": 200303900789, "公司内部单号": 730291, "发件人": "NAKAGAWA SUMIRE", "发件人地址": " 991-199-113,Kameido,Koto-ku,Tokyo", "发件人电话": "03-3999-3999", "发货国家": "日本", "收件人": "张无忌", "收件人地址": "上海市闵行区虹梅南路1660弄蔷薇八村88号8888室", "收件人电话": "182-1234-8888", "收货人证件号码": null, "收货省份": null, "总计费重量": 3.2, "总件数": 13, "申报总价(CNY)": null, "申报总价(JPY)": null, "件数1": 10, "品名1": "纸尿片", "单价1(JPY)": null, "单位1": null, "申报总价1(CNY)": null, "申报总价1(JPY)": null, "件数2": null, "品名2": null, "单价2(JPY)": null, "单位2": null, "申报总价2(CNY)": null, "申报总价2(JPY)": null, "ID": 2, "附件":"base64/gif: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" } ] }, { "Name": "Table2", "Cols": [ { "type": "int", "size": 0, "name": "NO", "required": false }, { "type": "float", "size": 0, "name": "订单编号", "required": false }, { "type": "integer", "size": 0, "name": "下单日期", "required": false }, { "type": "str", "size": 255, "name": "下单平台", "required": false } ], "Data": [ { "NO": 1, "订单编号": 200303900791, "下单日期": "2017-01-20", "下单平台": "天猫" }, { "NO": 2, "订单编号": 200303900792, "下单日期": "2017-01-20", "下单平台": "京东" } ] } ] } 五、调用示例: <!-- ★★★ 模式1 ★★★ --> <!DOCTYPE html> <head> <meta charset="utf-8" /> <title>康虎云报表系统测试</title> </head> <body> <div style="width: 100%;text-align:center;"> <h2>康虎云报表系统</h2> <h3>打印测试(模式1)</h3> <div> <input type="button" id="btnPrint" value="打印" onClick="doSend(_reportData);" /> </div> </div> <div id="output"></div> </body> <script type="text/javascript"> //定义数据脚本 var _reportData = '{"template":"waybill.fr3","Cols":[{"type":"str","size":255,"name":"HAWB","required":false},<这里省略1000字> ]}'; //在浏览器控制台输出调试信息 console.log("reportData = " + _reportData); </script> <script language="javascript" type="text/javascript" src="cfprint.min.js"></script> <script language="javascript" type="text/javascript" src="cfprint_ext.js"></script> <script language="javascript" type="text/javascript"> /下面四个参数必须放在myreport.js脚本后面,以覆盖myreport.js中的默认值/ var _delay_send = 1000; //发送打印服务器前延时时长,-1则表示不自动打印 var _delay_close = 1000; //打印完成后关闭窗口的延时时长, -1则表示不关闭 var cfprint_addr = "127.0.0.1"; //打印服务器监听地址 var cfprint_port = 54321; //打印服务器监听端口 </script> </html> <!-- ★★★ 模式2 ★★★ --> <?php //如果有php运行环境,只需把该文件扩展名改成 .php,然后上传到web目录即可在真实服务器上测试 header("Access-Control-Allow-Origin: "); ?> <!DOCTYPE html> <head> <meta charset="utf-8" /> <title>康虎云报表系统测试</title> <style type="text/css"> output {font-size: 12px; background-color:F0FFF0;} </style> </head> <body> <div style="width: 100%;text-align:center;"> <h2>康虎云报表系统(Ver 1.3.0)</h2> <h3>打印测试(模式2)</h3> <div style="line-height: 1.5;"> <div style="width: 70%; text-align: left;"> <b>一、首先按下列步骤设置:</b><br/> 1、运行打印服务器;<br/> 2、按“停止”按钮停止服务;<br/> 3、打开“设置”区;<br/> 4、在“常用参数-->服务模式”中,选择“模式2”;<br/> 5、按“启动”按钮启动服务。 </div> <div style="width: 70%; text-align: left;"> <b>二、按本页的“打印”按钮开始打印。</b><br/> </div><br/> <input type="button" id="btnPrint" value="打印" /><br/><br/> <div style="width: 70%; text-align: left; font-size: 12px;"> 由于JavaScript在不同域名下访问会出现由来已久的跨域问题,所以正式部署到服务器使用时,要解决跨域问题。<br/> 对于IE8以上版本浏览器,只需增加一个reponse头:Access-Control-Allow-Origin即可,而对于php、jsp、asp/aspx等动态语言而言,增加一个response头是非常简单的事,例如:<br/> <b>在php:</b><br/><span style="color: red;"> <?php <br/> header("Access-Control-Allow-Origin: ");<br/> ?><br/> </span> <b>在jsp:</b><br/><span style="color: red;"> <% <br/> response.setHeader("Access-Control-Allow-Origin", ""); <br/> %><br/> </span> <b>在asp.net中:</b><br/><span style="color: red;"> Response.AppendHeader("Access-Control-Allow-Origin", ""); </span>,<br/>其他语言里,大家请自行搜索“ajax跨域”。而对于IE8以下的浏览器,大家可以自行搜索“IE6+Ajax+跨域”寻找解决办法吧,也可以联系我们帮助。 </div> </div> </div> <div id="output"></div> </body> <!-- 引入模式2所需的javascript支持库 --> <script type="text/javascript" src="cfprint_mode2.min.js" charset="UTF-8"></script> <!-- 构造报表数据 --> <script type="text/javascript"> var _reportData = '{"template":"waybill.fr3","ver":3, "Tables":[ {"Name":"Table1", "Cols":[{"type":"str","size":255,"name":"HAWB","required":false},{"type":"int","size":0,"name":"NO","required":false},{"type":"float","size":0,"name":"报关公司面单号","required":false},{"type":"integer","size":0,"name":"公司内部单号","required":false},{"type":"str","size":255,"name":"发件人","required":false},{"type":"str","size":255,"name":"发件人地址","required":false},{"type":"str","size":255,"name":"发件人电话","required":false},{"type":"str","size":255,"name":"发货国家","required":false},{"type":"str","size":255,"name":"收件人","required":false},{"type":"str","size":255,"name":"收件人地址","required":false},{"type":"str","size":255,"name":"收件人电话","required":false},{"type":"str","size":255,"name":"收货人证件号码","required":false},{"type":"str","size":255,"name":"收货省份","required":false},{"type":"float","size":0,"name":"总计费重量","required":false},{"type":"int","size":0,"name":"总件数","required":false},{"type":"float","size":0,"name":"申报总价(CNY)","required":false},{"type":"float","size":0,"name":"申报总价(JPY)","required":false},{"type":"int","size":0,"name":"件数1","required":false},{"type":"str","size":255,"name":"品名1","required":false},{"type":"float","size":0,"name":"单价1(JPY)","required":false},{"type":"str","size":255,"name":"单位1","required":false},{"type":"float","size":0,"name":"申报总价1(CNY)","required":false},{"type":"float","size":0,"name":"申报总价1(JPY)","required":false},{"type":"int","size":0,"name":"件数2","required":false},{"type":"str","size":255,"name":"品名2","required":false},{"type":"float","size":0,"name":"单价2(JPY)","required":false},{"type":"str","size":255,"name":"单位2","required":false},{"type":"float","size":0,"name":"申报总价2(CNY)","required":false},{"type":"float","size":0,"name":"申报总价2(JPY)","required":false},{"type":"int","size":0,"name":"件数3","required":false},{"type":"str","size":255,"name":"品名3","required":false},{"type":"float","size":0,"name":"单价3(JPY)","required":false},{"type":"str","size":255,"name":"单位3","required":false},{"type":"float","size":0,"name":"申报总价3(CNY)","required":false},{"type":"float","size":0,"name":"申报总价3(JPY)","required":false},{"type":"int","size":0,"name":"件数4","required":false},{"type":"str","size":255,"name":"品名4","required":false},{"type":"float","size":0,"name":"单价4(JPY)","required":false},{"type":"str","size":255,"name":"单位4","required":false},{"type":"float","size":0,"name":"申报总价4(CNY)","required":false},{"type":"float","size":0,"name":"申报总价4(JPY)","required":false},{"type":"int","size":0,"name":"件数5","required":false},{"type":"str","size":255,"name":"品名5","required":false},{"type":"float","size":0,"name":"单价5(JPY)","required":false},{"type":"str","size":255,"name":"单位5","required":false},{"type":"float","size":0,"name":"申报总价5(CNY)","required":false},{"type":"float","size":0,"name":"申报总价5(JPY)","required":false},{"type":"str","size":255,"name":"参考号","required":false},{"type":"AutoInc","size":0,"name":"ID","required":false}],"Data":[{"公司内部单号":730293,"发货国家":"日本","单价1(JPY)":null,"申报总价2(JPY)":null,"单价4(JPY)":null,"申报总价2(CNY)":null,"申报总价5(JPY)":null,"报关公司面单号":200303900791,"申报总价5(CNY)":null,"收货人证件号码":null,"申报总价1(JPY)":null,"单价3(JPY)":null,"申报总价1(CNY)":null,"申报总价4(JPY)":null,"申报总价4(CNY)":null,"收件人电话":"182-1758-9999","收件人地址":"上海市闵行区虹梅南路1660弄蔷薇八村139号502室","HAWB":"860014010055","发件人电话":"03-3684-9999","发件人地址":" 1-1-13,Kameido,Koto-ku,Tokyo","NO":3,"ID":3,"单价2(JPY)":null,"申报总价3(JPY)":null,"单价5(JPY)":null,"申报总价3(CNY)":null,"收货省份":null,"申报总价(JPY)":null,"申报总价(CNY)":null,"总计费重量":3.20,"收件人":"张三丰2","总件数":13,"品名5":null,"品名4":null,"品名3":null,"品名2":null,"品名1":"纸尿片","参考号":null,"发件人":"NAKAGAWA SUMIRE 2","单位5":null,"单位4":null,"单位3":null,"单位2":null,"单位1":null,"件数5":null,"件数4":null,"件数3":3,"件数2":null,"件数1":10},{"公司内部单号":730291,"发货国家":"日本","单价1(JPY)":null,"申报总价2(JPY)":null,"单价4(JPY)":null,"申报总价2(CNY)":null,"申报总价5(JPY)":null,"报关公司面单号":200303900789,"申报总价5(CNY)":null,"收货人证件号码":null,"申报总价1(JPY)":null,"单价3(JPY)":null,"申报总价1(CNY)":null,"申报总价4(JPY)":null,"申报总价4(CNY)":null,"收件人电话":"182-1758-9999","收件人地址":"上海市闵行区虹梅南路1660弄蔷薇八村139号502室","HAWB":"860014010035","发件人电话":"03-3684-9999","发件人地址":" 1-1-13,Kameido,Koto-ku,Tokyo","NO":1,"ID":1,"单价2(JPY)":null,"申报总价3(JPY)":null,"单价5(JPY)":null,"申报总价3(CNY)":null,"收货省份":null,"申报总价(JPY)":null,"申报总价(CNY)":null,"总计费重量":3.20,"收件人":"张三丰","总件数":13,"品名5":null,"品名4":null,"品名3":null,"品名2":null,"品名1":"纸尿片","参考号":null,"发件人":"NAKAGAWA SUMIRE","单位5":null,"单位4":null,"单位3":null,"单位2":null,"单位1":null,"件数5":null,"件数4":null,"件数3":3,"件数2":null,"件数1":10},{"公司内部单号":730292,"发货国家":"日本","单价1(JPY)":null,"申报总价2(JPY)":null,"单价4(JPY)":null,"申报总价2(CNY)":null,"申报总价5(JPY)":null,"报关公司面单号":200303900790,"申报总价5(CNY)":null,"收货人证件号码":null,"申报总价1(JPY)":null,"单价3(JPY)":null,"申报总价1(CNY)":null,"申报总价4(JPY)":null,"申报总价4(CNY)":null,"收件人电话":"182-1758-9999","收件人地址":"上海市闵行区虹梅南路1660弄蔷薇八村139号502室","HAWB":"860014010045","发件人电话":"03-3684-9999","发件人地址":" 1-1-13,Kameido,Koto-ku,Tokyo","NO":2,"ID":2,"单价2(JPY)":null,"申报总价3(JPY)":null,"单价5(JPY)":null,"申报总价3(CNY)":null,"收货省份":null,"申报总价(JPY)":null,"申报总价(CNY)":null,"总计费重量":3.20,"收件人":"张无忌","总件数":13,"品名5":null,"品名4":null,"品名3":null,"品名2":null,"品名1":"纸尿片","参考号":null,"发件人":"NAKAGAWA SUMIRE 1","单位5":null,"单位4":null,"单位3":null,"单位2":null,"单位1":null,"件数5":null,"件数4":null,"件数3":3,"件数2":null,"件数1":10}]}]}'; if(window.console) console.log("reportData = " + _reportData); </script> <!-- 设置服务器参数 --> <script language="javascript" type="text/javascript"> var cfprint_addr = "127.0.0.1"; //打印服务器监听地址 var cfprint_port = 54321; //打印服务器监听端口 var _url = "http://"+cfprint_addr+":"+cfprint_port; </script> <!-- 编写回调函数用以处理服务器返回的数据 --> <script type="text/javascript"> / 参数: readyState: XMLHttpRequest的状态 httpStatus: 服务端返回的http状态 responseText: 服务端返回的内容 / var callbackSuccess = function(readyState, httpStatus, responseText){ if (httpStatus === 200) { //{"result": 1, "message": "打印完成"} var response = CFPrint.parseJSON(responseText); alert(response.message+", 状态码["+response.result+"]"); }else{ alert('打印失败,HTTP状态代码是:'+httpStatus); } } / 参数: message: 错误信息 / var callbackFailed = function(message){ alert('发送打印任务出错: ' + message); } </script> <!-- 调用发送打印请求功能 --> <script type="text/javascript"> (function(){ document.getElementById("btnPrint").onclick = function() { CFPrint.outputid = "output"; //指定调试信息输出div的id CFPrint.SendRequest(_url, _reportData, callbackSuccess, callbackFailed); //发送打印请求 }; })(); </script> </html> 六、模板设计器(重要!重要!!,好多朋友都找不到设计器入口) 在主界面上,双击右下角的“设计”两个字,即可打开模板设计工具箱,在工具箱有三个按钮和一个大文本框。三个按钮的作用分别是: 设计:以大文本框中的json数据为数据源,打开模板设计器窗口; 预览:以大文本框中的json数据为数据源,预览当前所用模板的打印效果; 打印:以大文本框中的json数据为数据源,向打印机输出当前所用模板生成的报表; 以后将会有详细的模板设计教程发布,如果您遇到紧急的难题,请向作者咨询。 本篇文章为转载内容。原文链接:https://blog.csdn.net/chensongmol/article/details/76087600。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-04-01 18:34:12
233
转载
MySQL
...种很广泛应用的关系型数据库管理系统软件。在采用MySQL时,我们经常需要往要添加记录的列里写入数据。下面就介绍一下如何在MySQL中写入数据。 首先,我们需要接入到MySQL数据库,可以采用下面的代码: $conn = mysqli_connect("localhost", "username", "password", "dbname"); if (!$conn) { die("接入失败: " . mysqli_connect_error()); } 其中,localhost指接入的服务器地址,username和password分别指接入的账号和口令,dbname指接入的数据库实例。 接下来,我们需要创建执行语句,以往数据库里添加记录。简单的执行语句可以采用下面的模板: INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...); 其中,table_name指要添加记录的表格名称,column1,column2,column3, ...分别指要添加记录的字段名称,value1,value2,value3, ...分别指要添加记录的数据项。 此处为一个添加记录的示例: $sql = "INSERT INTO students (name, age, gender, class) VALUES ('张三', 18, '男', '一班')"; if (mysqli_query($conn, $sql)) { echo "新条目成功添加"; } else { echo "错误信息: " . $sql . " " . mysqli_error($conn); } 其中,students指要添加记录的表格名称,name、age、gender、class分别指要添加记录的字段名称,后面的数据项分别为'张三'、18、'男'、'一班'。 最后,我们需要关闭接入: mysqli_close($conn); 通过上面的步骤,我们可以在MySQL中往明确字段里写入数据。
2023-06-05 22:29:31
71
算法侠
MySQL
关系型数据库管理系统 , 关系型数据库管理系统(RDBMS)是一种基于关系模型的数据库管理系统,它以表格的形式存储数据,并通过预定义的关系或键将这些表格连接起来。在MySQL中,这种系统允许用户使用结构化查询语言(SQL)对数据进行操作,如插入、更新、删除和查询记录。其特点是数据结构化强、易于理解且支持事务处理。 Web应用程序 , Web应用程序是一种可以通过互联网访问的应用程序,通常由客户端(浏览器)和服务器端两部分构成。用户通过浏览器向服务器发送请求,服务器则运行相应的程序并返回HTML、CSS、JavaScript等构建的动态网页给客户端。MySQL作为后台数据库,可以为Web应用程序提供数据存储和检索服务,例如存储用户信息、产品列表、订单数据等。 SQL语法 , SQL(Structured Query Language)是用于管理关系型数据库的标准计算机语言。在MySQL中,SQL语句用于执行各种数据库操作,包括创建表、插入数据、更新记录、删除数据以及从数据库中检索信息等。例如,MySQL中的插入数据语句“INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...)”就是遵循SQL语法,用于将新行数据插入到指定表中的特定字段。
2023-09-26 10:25:10
66
编程狂人
JSON
...ion)是一种简洁的数据传输格式。它的句法规则简单,容易查看和编写代码,而且很容易与其他编程语言进行交流。但是,在一些情境中,我们需要将JSON数据转化成表格形式,以便于方便地检索、处理和管控数据。 将JSON数据转化成表格形式的过程,通常包含以下几个步骤: 了解JSON数据的构造:在进行转化之前,我们需要先了解JSON数据的属性名、字段类型以及嵌套关系。 创建数据库表:根据JSON数据的构造,我们需要在数据库中创建匹配的表格。 解读JSON数据:我们可以使用各种编程语言提供的JSON解读器来解读JSON数据,将其转化成数据结构。 将数据结构添加数据库表:最后,我们可以使用SQL语句将数据结构添加数据库表中。 -- 创建数据库表 CREATE TABLE users ( id INT PRIMARY KEY, name VARCHAR(50), email VARCHAR(50), address VARCHAR(100) ); -- 解读JSON数据 var data = JSON.parse('[ { "id": 1, "name": "Alice", "email": "alice@example.com", "address": { "street": "123 Main St", "city": "Anytown", "state": "USA", "zipcode": "12345" } }, { "id": 2, "name": "Bob", "email": "bob@example.com", "address": { "street": "456 High St", "city": "Anytown", "state": "USA", "zipcode": "67890" } } ]'); -- 将数据结构添加数据库表 for(var i = 0; i< data.length; i++) { var user = data[i]; var query = "INSERT INTO users (id, name, email, address) VALUES (?, ?, ?, ?)"; db.query(query, [user.id, user.name, user.email, JSON.stringify(user.address)]); } 在上述代码中,我们使用了JavaScript语言进行示例展示,但是相应的处理在其他编程语言,例如Python、Java、PHP等,也有相应的实现方法。总的来说,将JSON数据转化成表格形式,可以方便地对数据进行增删改查等处理,提高数据的处理速度和数据管控的便捷性。
2023-11-04 08:47:08
442
算法侠
Lua
...d on a nontable value”错误详解与实战解决 Lua,作为一种轻量级、可嵌入的脚本语言,在游戏开发和网络应用中被广泛应用。在实际编程的时候,咱们经常会撞上一个让人挠头的运行时错误,它就是那个“cannot call method on a nontable value”,这个错误提示是不是听起来挺拗口?其实呢,就是在说我们试图在一个非表格类型的值上调用方法了。这篇文章咱们要接地气地聊聊这个错误背后的真相,不仅有满满的代码实例撑腰,还会手把手地带大伙儿一步步揭开它的神秘面纱,最后把问题给妥妥地解决了。 1. 错误概述 当我们尝试在一个非table类型的值上调用方法时,Lua解释器会抛出这个错误信息:“cannot call method on a nontable value”。简单来说,它就是在告诉你:嘿,伙计,你试图对一个不是table的东西进行方法调用,这在Lua里是不允许的! 2. 错误会发生的场景 为了更好地理解这个问题,让我们先看一段典型的引发此错误的Lua代码: lua -- 示例1 local number = 5 number:len() -- 这将导致 "cannot call method 'len' on a nontable value" 的错误 在上述例子中,我们尝试在一个数字类型变量number上调用len()方法,但显然,数字类型并没有len()这个方法,这就违反了Lua规定,于是就出现了错误提示。 3. 解析与解决之道 首先,我们需要明确一点:在Lua中,只有table类型才能拥有方法(或者说metatable中的元方法)。所以,当你打算呼唤某个方法的时候,千万要确认这个方法是用在一个长得像表格的类型的数据上。 3.1 正确使用table的方法调用 例如,Lua字符串实际上是table的一个封装,我们可以正确地在字符串上调用方法: lua -- 示例2 local str = "Hello, World!" print(str:len()) -- 输出: 13 在这个例子中,str虽然是字符串类型,但它内部实际上是一个table,并且定义了len这个方法,所以这段代码能够正常执行。 3.2 遇到错误时的排查策略 当遇到“cannot call method on a nontable value”错误时,你可以按照以下步骤进行排查: - 检查变量类型:确认你要调用方法的变量是否为table类型。 - 查阅API文档:确保该类型的数据结构支持你所调用的方法。 - 审视代码逻辑:有可能是由于逻辑处理不当,使得原本应该是table类型的变量在某些情况下变成了其他类型。 3.3 错误修复实例 假设我们在设计一个玩家类Player,其中包含了一个返回玩家姓名的方法getName,而我们错误地在初始化阶段没有将其设置为table: lua -- 示例3 (错误示范) local Player = "John Doe" function Player.getName() return self end local player = Player print(player.getName()) -- 报错: cannot call method 'getName' on a nontable value -- 示例4 (修正后的代码) local Player = {} Player.name = "John Doe" Player.getName = function(self) return self.name end local player = Player print(player.getName()) -- 输出: John Doe 在示例3中,我们试图在一个字符串上调用方法,而在示例4中,我们将Player初始化为一个table,并为其添加了getName方法,从而避免了错误的发生。 总结一下,理解并有效规避“cannot call method on a nontable value”错误的关键在于熟知Lua的数据类型及其行为特性,以及合理地运用面向对象编程思想来组织你的代码。希望本文能帮助你在Lua的世界里更加游刃有余地解决问题,享受编程的乐趣!
2024-01-08 11:28:51
90
春暖花开
PostgreSQL
...eSQL是一种关系型数据库管理系统,它拥有强大的索引功能,可以帮助我们在大量数据中快速定位到所需要的信息。今天,咱们就一起动手探索一下,在PostgreSQL这个数据库里如何创建一个能够实实在在展示出数据的索引吧! 什么是索引? 索引是数据库系统中的一种特殊的数据结构,它可以加速对数据库表的查询操作。索引的工作原理其实就像在图书馆整理书籍那样,想象一下,我们在数据库表的某一列上设立一个“目录”,这个目录里记录的是这一列各种值所在的具体位置。当你需要查询某个数据时,就好比你在找一本书,无需把整个图书馆从头到尾翻一遍,而是直接翻开目录,根据指针找到书的确切位置。这样一来,大大提升了查找速度,省时又高效。 创建索引的方法 在PostgreSQL中,我们可以使用CREATE INDEX语句来创建一个新的索引。语法如下: sql CREATE INDEX ON (); 在这个语句中,是我们给新创建的索引命名的字符串,是我们想要在其上创建索引的表名,是我们想要在哪个列上创建索引的列名。 例如,我们有一个名为“employees”的表,其中包含员工的信息,如下所示: sql CREATE TABLE employees ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, age INT NOT NULL, address VARCHAR(255) ); 现在,我们想要在“name”列上创建一个索引,以便我们可以更快地查找员工的名字。那么,我们就可以使用以下的SQL语句: sql CREATE INDEX idx_employees_name ON employees (name); 在这个语句中,“idx_employees_name”是我们给新创建的索引命名的字符串,“employees”是我们想要在其上创建索引的表名,“name”是我们想要在哪个列上创建索引的列名。 查看索引 如果我们已经创建了一个索引,但不确定它是否起作用或者我们想要查看所有已存在的索引,我们可以使用以下的SQL语句: sql SELECT FROM pg_indexes WHERE tablename = ''; 在这个语句中,“是我们想要查看其索引的表名。“pg_indexes”是PostgreSQL的一个系统表,它包含了所有的索引信息。 性能优化 虽然索引可以帮助我们加快查询速度,但是过多的索引也会影响数据库的性能。因此,在创建索引时,我们需要权衡索引的数量和查询效率之间的关系。通常来说,当你的表格里头的数据条数蹭蹭地超过10万大关的时候,那就真的得琢磨琢磨给它创建个索引了,这样一来才能让数据查找更溜更快。此外,咱们也得留意一下,别在那些频繁得不得了的列上乱建索引。要知道,这样做的话,索引维护起来可是会让人头疼的,成本噌噌往上涨。 总的来说,索引是提高数据库查询效率的重要手段。在PostgreSQL这个数据库里,我们能够用几句简单的SQL命令轻松创建索引。而且,更酷的是,还可以借助系统自带的索引管理工具,像看菜单一样直观地查看索引的各种状态,甚至还能随心所欲地调整它们,就像给你的数据仓库整理目录一样方便。但是,我们也需要注意不要滥用索引,以免影响数据库的整体性能。
2023-06-18 18:39:15
1324
海阔天空_t
Lua
...程中,动态数组是一种数据结构,其大小可以在程序运行时动态调整。在Lua中,表格(Table)作为一种动态数组,可以根据需要添加或删除元素,无需预先设定固定的大小。例如,文章中的myTable = name = Lua, version = 5.4, popularity = true ,这个表格可以随时插入新的键值对,数组长度随之增长。 关联数组 , 关联数组也称哈希表,是一种特殊类型的数组,其中的索引可以是任何类型的数据(如字符串、数字或其他可哈希对象)。在Lua中,表格同样实现了关联数组的功能,通过字符串或其他Lua值作为键来访问对应值。例如,myTable.name即通过字符串\ name\ 作为键来获取对应的值\ Lua\ 。 即时编译技术 , 即时编译(Just-In-Time Compilation, JIT)是一种将字节码或解释型语言在运行时转换为机器码的技术,以提升程序执行效率。LuaJIT项目采用这种技术,能够在运行过程中将Lua代码编译成本地机器指令,从而极大地提高Lua脚本的执行速度。尽管文章中未直接提及即时编译技术的具体细节,但提到LuaJIT通过该技术提升了Lua代码的性能,这是Lua高性能应用的重要支撑之一。
2023-04-12 21:06:46
57
百转千回
Spark
...行SQL查询以及读写数据等多种功能。在本文中,用户首先通过构建SparkSession实例来初始化与Spark集群或本地环境的连接,并指定应用名称以便于识别和管理。 DataFrame , 在Spark中,DataFrame是一种以表格形式组织的数据结构,类似于关系型数据库中的表,每一列都可以是不同的数据类型。DataFrame支持结构化的数据处理操作,如选择特定列、过滤行、进行聚合等。在导入SQL数据库数据到Spark的过程中,数据会被转换为DataFrame对象,以便进一步进行高效的数据处理和分析。 JDBC(Java Database Connectivity) , JDBC是一种Java API,允许Java应用程序连接并执行SQL语句与各种类型的数据库进行交互。在文中,使用read.jdbc()函数从SQL数据库导入数据时,需要通过JDBC接口与数据库建立连接。这意味着用户必须提供正确的数据库URL、驱动程序信息以及其他认证凭据,这样才能通过JDBC驱动程序将SQL数据库中的数据读取到Spark的DataFrame中。
2023-12-24 19:04:25
161
风轻云淡-t
ClickHouse
... 1. 引言 在大数据处理的世界中,ClickHouse因其卓越的性能和对海量数据查询的高效支持而备受青睐。在众多功能特性中,UNION操作符无疑是实现数据聚合、合并的关键利器。本文要带你一起“潜入”ClickHouse的UNION操作符的世界,手把手教你如何把它玩得溜起来。咱会用到大量接地气、实实在在的实例代码,让你像看懂故事一样轻松理解并掌握这个超级实用的功能,绝对让你收获满满! 2. UNION操作符基础理解 在ClickHouse中,UNION操作符用于将两个或多个SELECT语句的结果集合并为一个单一的结果集。就像玩拼图那样,它能帮我们将来自各个表格或子查询中的数据片段,像搭积木一样天衣无缝地拼凑起来,让这些信息完美衔接。注意,UNION会去除重复行,若需要包含所有行(包括重复行),则需使用UNION ALL。 例如: sql SELECT FROM table1 UNION ALL SELECT FROM table2; 此例展示了从table1和table2中选取所有记录并合并的过程,其中可能包含相同的记录。 3. UNION操作符的高效使用策略 3.1 结构一致性 使用UNION时,各个SELECT语句的选择列表必须具有相同数量且对应位置的数据类型一致。这是保证数据能够正确合并的前提条件: sql SELECT id, name FROM users WHERE age > 20 UNION SELECT id, username FROM admins WHERE status = 'active'; 在这个例子中,虽然选择了不同的表,但id字段和name/username字段类型匹配,因此可以进行合并。 3.2 索引优化与排序 尽管UNION本身不会改变数据的物理顺序,但在实际应用中,如果预先对源数据进行了恰当的索引设置,并结合ORDER BY进行排序,可显著提高执行效率。 sql -- 假设已为age和status字段建立索引 (SELECT id, name FROM users WHERE age > 20 ORDER BY id) UNION ALL (SELECT id, username FROM admins WHERE status = 'active' ORDER BY id); 3.3 分布式环境下的UNION操作 在分布式集群环境下,合理利用分布式表结构和UNION能有效提升大规模数据处理能力。例如,当多个节点分别存储了部分数据时,可通过UNION跨节点汇总数据: sql SELECT FROM ( SELECT FROM distributed_table_1 UNION ALL SELECT FROM distributed_table_2 ) AS combined_data WHERE some_condition; 4. 探讨与思考 我们在实际运用ClickHouse的UNION操作符时,不仅要关注其语法形式,更要注重其实现背后的逻辑和性能影响。针对特定场景选择合适的策略,如确保数据结构一致性、合理利用索引和排序以降低IO成本,以及在分布式环境中巧妙合并数据等,这些都将是提升查询性能的关键所在。 总之,在追求数据处理效率的道路上,掌握并熟练运用ClickHouse的UNION操作符无疑是我们手中的一把利剑。一起来,咱们动手实践,不断探寻其中的宝藏,让这股力量赋能我们的数据分析,提升业务决策的精准度和效率,就像挖金矿一样,越挖越有惊喜! > 注:以上示例仅为简化演示,实际应用中请根据具体业务需求调整SQL语句和数据表结构。同时呢,为了让大家读起来不那么吃力,我在这儿就只挑了几种最常见的应用场景来举例子,实际上UNION这个操作符的能耐可不止这些,它在实际使用中的可能性多到超乎你的想象!所以,还请大家亲自上手试试看,去探索更多意想不到的用法吧!
2023-09-08 10:17:58
426
半夏微凉
Java
树形表格(Tree Table) , 树形表格是一种特殊的表格展示形式,它将数据以树状结构进行组织和呈现。在这样的表格中,每个单元格代表一个节点,节点可以包含子节点,形成多层级结构。用户可以通过展开和收起操作查看不同层级的数据,便于理解和处理具有层级关系的大量数据。 异步加载(Asynchronous Loading) , 异步加载是编程技术中的一种策略,用于优化程序性能,特别是在处理大量数据或网络请求时。在本文的上下文中,异步加载指的是在网络应用中,当需要展示树形表格的数据量较大时,不一次性加载所有数据,而是根据用户的交互行为(如滚动、点击等)动态地从服务器获取并渲染新的数据,从而避免页面卡顿,提高用户体验。 CompletableFuture , CompletableFuture是Java 8引入的一个类,它是Java并发库的一部分,用来简化异步编程模型。通过CompletableFuture,开发者能够创建、组合和管理基于Future的异步计算任务。在本文中,使用CompletableFuture来实现树形表格数据的异步加载,即在后台线程中执行耗时的数据获取操作,并在操作完成后更新UI界面。 线程池(ExecutorService) , 线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建的一组工作线程上执行这些任务。在本文的具体场景下,executorService作为一个线程池实例,负责调度和执行异步任务,即获取树形表格所需的数据,这样可以有效地复用线程资源,减少创建和销毁线程的开销,同时更好地控制并发级别,防止过多线程导致系统资源耗尽。
2023-03-08 18:52:23
385
幽谷听泉_t
Greenplum
...reenplum中的数据类型和精度:一次深入实践之旅 1. 引言 在大数据领域,Greenplum作为一款开源且高度可扩展的MPP(大规模并行处理)数据库,以其卓越的大规模数据分析能力深受广大用户的青睐。在实际操作时,我们可能会遇到需要对表格里的数据类型或者精度进行微调的情况。这背后的原因五花八门,可能是为了更有效地利用存储空间,让查询速度嗖嗖提升;也可能是为了更好地适应业务发展,满足那些新冒出来的需求点。这篇内容,咱们会手把手地通过一些实实在在的代码实例,带你逐个步骤掌握如何在Greenplum里搞定这个操作。同时,咱们还会边走边聊,一起探讨在这个过程中可能会踩到的坑以及相应的填坑大法。 2. 理解Greenplum的数据类型与精度 在Greenplum中,每列都有特定的数据类型,如整数(integer)、浮点数(real)、字符串(varchar)等,而精度则是针对数值型数据类型的特性,如numeric(10,2)表示最大整数位数为10,小数位数为2。理解这些基础概念是进行调整的前提。 sql -- 创建一个包含不同数据类型的表 CREATE TABLE test_data_types ( id INT, name VARCHAR(50), salary NUMERIC(10,2) ); 3. 调整Greenplum中的数据类型 场景一:改变数据类型 例如,假设我们的salary字段原先是INTEGER类型,现在希望将其更改为NUMERIC以支持小数点后的精度。 sql -- 首先,我们需要确保所有数据都能成功转换到新类型 ALTER TABLE test_data_types ALTER COLUMN salary TYPE NUMERIC; -- 或者,如果需要同时指定精度 ALTER TABLE test_data_types ALTER COLUMN salary TYPE NUMERIC(10,2); 注意,修改数据类型时必须保证现有数据能成功转换到新的类型,否则操作会失败。在执行上述命令前,最好先运行一些验证查询来检查数据是否兼容。 场景二:增加或减少数值类型的精度 若要修改salary字段的小数位数,可以如下操作: sql -- 增加salary字段的小数位数 ALTER TABLE test_data_types ALTER COLUMN salary TYPE NUMERIC(15,4); -- 减少salary字段的小数位数,系统会自动四舍五入 ALTER TABLE test_data_types ALTER COLUMN salary TYPE NUMERIC(10,1); 4. 考虑的因素与挑战 - 数据完整性与一致性:在调整数据类型或精度时,务必谨慎评估变更可能带来的影响,比如精度降低可能导致的数据丢失。 - 性能开销:某些数据类型之间的转换可能带来额外的CPU计算资源消耗,尤其是在大表上操作时。 - 索引重建:更改数据类型后,原有的索引可能不再适用,需要重新创建。 - 事务与并发控制:对于大型生产环境,需规划合适的维护窗口期,以避免在数据类型转换期间影响其他业务流程。 5. 结语 调整Greenplum中的数据类型和精度是一个涉及数据完整性和性能优化的关键步骤。在整个这个过程中,我们得像个侦探一样,深入地摸透业务需求,把数据验证做得像查户口似的,仔仔细细,一个都不能放过。同时,咱们还要像艺术家设计蓝图那样,精心策划每一次的变更方案。为啥呢?就是为了在让系统跑得飞快的同时,保证咱的数据既整齐划一又滴水不漏。希望这篇东西里提到的例子和讨论能实实在在帮到你,让你在用Greenplum处理数据的时候,感觉就像个武林高手,轻松应对各种挑战,游刃有余,毫不费力。
2024-02-18 11:35:29
395
彩虹之上
Lua
...与lua_gettable引发的错误 在编程的世界里,Lua语言以其轻量级、易嵌入的特点而闻名。不过嘛,就算是看起来挺简单的语言,在实际开发的时候也会碰到不少让人头疼的问题。嘿,今天咱们来聊聊在用Lua C API的时候经常会碰到的一个坑——就是用lua_pushvalue和lua_gettable这两个操作时容易出错的地方。这不仅是一个技术挑战,更是一次深入理解Lua机制的机会。 一、初次遭遇 神秘的错误提示 故事开始于一个普通的下午,我正着手为一个新的游戏项目编写脚本引擎。为了提升性能和方便以后的维护,我们打算把核心功能用C++来写,而游戏的具体玩法就交给Lua脚本来搞定。这样既高效又灵活!事情本来进展得挺顺利的,结果当我试着调用一个自定义函数时,程序突然就崩溃了。屏幕上跳出了一行让人完全摸不着头脑的错误信息:“试图调用全局‘func_name’(一个空值)”。这下我就懵圈了,心想这到底是什么鬼? 这显然不是我想要的结果。一开始,我还以为是Lua脚本加载出问题了,结果仔细一看,发现文件路径和内容都挺正常的,就不是这个原因。难道是我的C++代码出了问题?带着疑问,我开始深入研究。 二、深入探究 揭开谜底 经过一番查阅资料和调试,我发现问题出在lua_pushvalue和lua_gettable这两个API的使用上。简单地说,lua_pushvalue就像是把栈上的某个东西复制一份放到另一个地方,而lua_gettable则是从一个表格里找到特定的键,然后取出它对应的值。虽然这些功能都挺明确的,但如果在特定情况下用错了,还是会闹出运行时的笑话。 为了更好地理解这个问题,让我们来看几个具体的例子。 示例1:基本概念 c // 假设我们有一个名为myTable的表,其中包含键为"key",值为"value"的项。 lua_newtable(L); // 创建一个空表 lua_pushstring(L, "key"); // 将字符串"key"压入栈顶 lua_pushstring(L, "value"); // 将字符串"value"压入栈顶 lua_settable(L, -3); // 使用栈顶元素作为键,-2位置的元素作为值,设置到-3位置(即刚刚创建的表) 上述代码创建了一个名为myTable的表,并向其中添加了一个键值对。接下来,我们尝试通过lua_gettable访问这个值: c lua_getglobal(L, "myTable"); // 获取全局变量myTable lua_getfield(L, -1, "key"); // 从myTable中获取键为"key"的值 printf("%s\n", lua_tostring(L, -1)); // 输出结果应为"value" 这段代码应该能正确地输出value。但如果我们在lua_getfield之前没有正确地管理栈,就很有可能会触发错误。 示例2:常见的错误场景 假设我们误用了lua_pushvalue: c lua_newtable(L); lua_pushstring(L, "key"); lua_pushstring(L, "value"); lua_settable(L, -3); // 正确 lua_pushvalue(L, -1); // 这里实际上是在复制栈顶元素,而不是预期的行为 lua_gettable(L, -2); // 错误使用,因为此时栈顶元素已经不再是"key"了 这里的关键在于,lua_pushvalue只是复制了栈顶的元素,并没有改变栈的结构。当我们紧接着调用 lua_gettable 时,其实就像是在找一个根本不存在的地方的宝贝,结果当然是找不到啦,所以就出错了。 三、解决之道 掌握正确的使用方法 明白了问题所在后,解决方案就相对简单了。我们需要确保在调用lua_gettable之前,栈顶元素是我们期望的那个值。这就像是说,我们得先把栈里的东西清理干净,或者至少得确定在动手之前,栈里头的东西是我们想要的样子。 c lua_newtable(L); lua_pushstring(L, "key"); lua_pushstring(L, "value"); lua_settable(L, -3); // 清理栈,确保栈顶元素是table lua_pop(L, 1); lua_pushvalue(L, -1); // 正确使用,复制table本身 lua_gettable(L, -2); // 现在可以安全地从table中获取数据了 通过这种方式,我们可以避免因栈状态混乱而导致的错误。 四、总结与反思 通过这次经历,我深刻体会到了理解和掌握底层API的重要性。尽管Lua C API提供了强大的功能,但也需要开发者具备一定的技巧和经验才能正确使用。错误的信息常常会绕弯弯,不会直接带你找到问题的关键。所以,遇到难题时,咱们得有耐心,一步步地去分析和查找,这样才能找到解决的办法。 同时,这也提醒我们在编写任何复杂系统时,都应该重视基础理论的学习和实践。只有真正理解了背后的工作原理,才能写出更加健壮、高效的代码。 希望这篇文章对你有所帮助,如果你也有类似的经历,欢迎分享你的故事!
2024-11-24 16:19:43
131
诗和远方
转载文章
...ML文件中提取、操作数据以及清理(标准化)HTML内容。通过调用Jsoup的方法,开发者可以方便地获取到网页中的特定元素,如链接标签(LinkTag)和表格标签(TableTag)等,并进一步分析这些元素内的信息。 NodeFilter , NodeFilter是HTMLParser库中定义的一个接口,用于过滤或匹配HTML文档中的节点对象。在该文章代码示例中,作者创建了多个NodeFilter实例,比如NodeClassFilter和OrFilter,来筛选出符合特定条件的HTML节点,例如包含特定类别的TableTag和LinkTag。这样做的目的是在解析过程中仅关注与安全漏洞相关的部分。 LinkTag , 在HTML语法中,LinkTag表示超链接标签(<a>),它通常用于定义指向其他网页、资源或锚点的链接。在本文所描述的Java程序中,LinkTag是一个关键对象类型,程序会检查并提取其中的内容以识别安全漏洞的相关信息,特别是当标签内含有特定字符串时,如\ onclick\ 和\ vul-\ ,进而分析并分类(高危、中危、低危)漏洞名称。 TableTag , TableTag代表HTML中的表格标签(<table>),用于展示多行多列的数据结构。在这个Java应用案例里,TableTag同样是被重点关注的对象类型,程序会根据其属性值进行定位,并使用Jsoup解析表格内的内容,将每一行的键值对数据(如<td>元素中的文本)提取出来,作为漏洞简介或其他相关信息的一部分。
2023-07-19 10:42:16
294
转载
转载文章
...”按钮将输入和选择的数据传递给第2个JSP页面result.jsp。 (2)第2个页面,命名为result.jsp:通过request对象获得注册页面的信息,然后在该页面以表格形式显示出来。如下图所示 (建议,可以将用户信息编写成一个实体类) 2.具体代码 (1)login.jsp <%@ page contentType="text/html; charset=GB2312"%><HTML><body><center><h2>模拟注册页面</h2></center><font size=3><h3><form action="case03ssy2result.jsp" method=post><br>用户名:<input type="text" size="16" minlength="6" maxlength="16" aligin="left" name="username">   <b><i>用户名由6~16个字符组成,包括汉字,数字,字母等</i></b></br><p>密 码: <input type="password" size="16" minlength="6" maxlength="16" aligin="left" name="pwd">   <b><i>密码由6~16个字符组成,包括数字,字母等</i></b></p><p>性 别: <input type="radio" value="男" name="sex"/>男 <input type="radio" value="女" name="sex"/>女   年龄:<input type="text" size="4" name="age" id="age" style="background-color:grey" readonly><p>出生日期:<select name="year" id="year" onblur="changeAge()"> <% for(int y=1990;y<=2010;y++){ %><option value="<%=y %>"><%=y %></option><%}%></select>年<select name="month"><% for(int m=1;m<=12;m++){ %><option value="<%=m%>"><%=m %></option><%} %></select>月<select name="day"> <% for(int d=1;d<=31;d++){ %><option value="<%=d %>"><%=d %></option><%} %></select>日</p><p>爱 好:<input type="checkbox" value="唱歌" name="hobbies" />唱歌<input type="checkbox" value="听歌" name="hobbies" />听歌<input type="checkbox" value="篮球" name="hobbies" />篮球<input type="checkbox" value="乒乓球" name="hobbies" />乒乓球<input type="checkbox" value="足球" name="hobbies" />足球<input type="checkbox" value="羽毛球" name="hobbies" />羽毛球</p><p>所学课程:<select name="course" multiple="multiple" size="10"><option value="计算机科学导论">计算机科学导论</option><option value="C程序设计基础">C程序设计基础</option><option value="数据结构">数据结构</option><option value="操作系统原理">操作系统原理</option><option value="软件工程概论">软件工程概论</option><option value="算法分析与设计">算法分析与设计</option><option value="Java编程基础">Java编程基础</option><option value="计算机网络">计算机网络</option><option value="数据库系统原理及应用">数据库系统原理及应用</option><option value="软件设计">软件设计</option><option value="软件测试">软件测试</option><option value="Java Web应用程序开发">Java Web应用程序开发</option><option value="组网工程">组网工程</option><option value="软件项目管理">软件项目管理</option><option value="云计算与大数据技术">云计算与大数据技术</option><option value="粮油信息处理及模式识别">粮油信息处理及模式识别</option><option value="软件开发案例分析">软件开发案例分析</option><option value="软件交互设计">软件交互设计</option></select>按住Ctrl按钮来选择多个项目</p><p>个人简历:<textArea name="cv" rows="3" cols="35" align="top" ></textArea></p><p><center><input type="submit" value="注册" name="submit"></center></p></form></h3></font><script type="text/javascript">function changeAge() {console.log("调用了函数");var nowData = new Date();console.log(nowData.getUTCFullYear());var nowYear = nowData.getUTCFullYear();console.log(document.getElementById("year").value)var year = document.getElementById("year").value;var age = nowYear - year;var e = document.getElementById("age");e.value = age;}</script></body></HTML> (2)result.jsp <%@ page contentType="text/html; charset=GB2312"%><%! public String handleStr(String s){try{ byte [] bb=s.getBytes("GB2312");s=new String(bb);}catch(Exception exp){}return s;}%><HTML><body bgcolor=yellow><font size=3><% request.setCharacterEncoding("GB2312");String username=request.getParameter("username");String pwd=request.getParameter("pwd");String sex=request.getParameter("sex");String year=request.getParameter("year");String month=request.getParameter("month");String day=request.getParameter("day");String age=request.getParameter("age");String hobbies[]=request.getParameterValues("hobbies");String course[]=request.getParameterValues("course");String cv=request.getParameter("cv");%>注册个人信息如下:<br><table border=2><tr><td><% out.print("用户名");%></td><td><% out.print("密码"); %></td><td><% out.print("性别"); %></td><td><% out.print("出生日期"); %></td><td><% out.print("年龄"); %></td><td><% out.print("爱好"); %></td><td><% out.print("所学课程"); %></td><td><% out.print("个人简历"); %></td></tr><tr><td><% out.print(username); %></td><td><% out.print(pwd); %></td><td><% out.print(sex); %></td><td><% out.print(year+"年"+month+"月"+day+"日"); %></td><td><% out.print(age); %></td><td><% if(hobbies==null){out.println("无");}else{ for(int m=0;m<hobbies.length;m++){out.print(handleStr(hobbies[m])+" ");} }%></td><td><% if(course==null){out.println("无");}else{ for(int n=0;n<course.length;n++){out.print(handleStr(course[n])+" ");} }%></td><td><% out.print(cv); %></td></tr></table></font></body></HTML> 3.运行结果 4.总结分析 在大体功能实现的基础上,虽然实现了用户信息登录与记录,但是此界面只能输入并记录一个用户 ,无法实现多用户,有待改正。另外,在登录界面年龄下拉列表没用考录闰年与平年的区别,把每个月份都设置为了31天。 求大佬改正。 本篇文章为转载内容。原文链接:https://blog.csdn.net/Pluto_ssy/article/details/121049221。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-08-15 09:02:21
112
转载
转载文章
...容。 卡表(CardTable)在CMS中是最常见的概念之一,G1中不仅保留了这个概念,还引入了RSet。卡表到底是一个什么东西?GC最早引入卡表的目的是为了对内存的引用关系做标记,从而根据引用关系快速遍历活跃对象。举个简单的例子,有两个分区,假设分区大小都为1MB,分别为A和B。如果A中有一个对象objA,B中有一个对象objB,且objA.field=objB,那么这两个分区就有引用关系了,但是如果我们想找到分区A,要如何引用分区B?做法有两种:·遍历整个分区A,一个字一个字的移动(为什么以字为单位?原因是JVM中对象会对齐,所以不需要按字节移动),然后查看内存里面的值到底是不是指向B,这种方法效率太低,可以优化为一个对象一个对象地移动(这里涉及JVM如何识别对象,以及如何区分指针和立即数),但效率还是太低。 ·借助额外的数据结构描述这种引用关系,例如使用类似位图(bitmap)的方法,记录A和B的内存块之间的引用关系,用一个位来描述一个字,假设在32位机器上(一个字为32位),需要32KB(32KB×32=1M)的空间来描述一个分区。那么我们就可以在这个对象ObjA所在分区A里面添加一个额外的指针,这个指针指向另外一个分区B的位图,如果我们可以把对象ObjA和指针关系进行映射,那么当访问ObjA的时候,顺便访问这个额外的指针,从这个指针指向的位图就能找到被ObjA引用的分区B对应的内存块。通常我们只需要判定位图里面对应的位是否有1,有的话则认为发生了引用。 class CardTable: public CHeapObj<mtGC> {friend class VMStructs;public:typedef uint8_t CardValue;// All code generators assume that the size of a card table entry is one byte.// They need to be updated to reflect any change to this.// This code can typically be found by searching for the byte_map_base() method.STATIC_ASSERT(sizeof(CardValue) == 1);protected:// The declaration order of these const fields is important; see the// constructor before changing.const MemRegion _whole_heap; // the region covered by the card tableconst size_t _page_size; // page size used when mapping _byte_mapsize_t _byte_map_size; // in bytesCardValue _byte_map; // the card marking arrayCardValue _byte_map_base;// Some barrier sets create tables whose elements correspond to parts of// the heap; the CardTableBarrierSet is an example. Such barrier sets will// normally reserve space for such tables, and commit parts of the table// "covering" parts of the heap that are committed. At most one covered// region per generation is needed.static constexpr int max_covered_regions = 2;// The covered regions should be in address order.MemRegion _covered[max_covered_regions];// The last card is a guard card; never committed.MemRegion _guard_region;inline size_t compute_byte_map_size(size_t num_bytes);enum CardValues {clean_card = (CardValue)-1,dirty_card = 0,CT_MR_BS_last_reserved = 1};// a word's worth (row) of clean card valuesstatic const intptr_t clean_card_row = (intptr_t)(-1);// CardTable entry sizestatic uint _card_shift;static uint _card_size;static uint _card_size_in_words;size_t last_valid_index() const {return cards_required(_whole_heap.word_size()) - 1;}private:void initialize_covered_region(void region0_start, void region1_start);MemRegion committed_for(const MemRegion mr) const;public:CardTable(MemRegion whole_heap);virtual ~CardTable() = default;void initialize(void region0_start, void region1_start);// Barrier set functions.// Initialization utilities; covered_words is the size of the covered region// in, um, words.inline size_t cards_required(size_t covered_words) const {assert(is_aligned(covered_words, _card_size_in_words), "precondition");return covered_words / _card_size_in_words;}// Dirty the bytes corresponding to "mr" (not all of which must be// covered.)void dirty_MemRegion(MemRegion mr);// Clear (to clean_card) the bytes entirely contained within "mr" (not// all of which must be covered.)void clear_MemRegion(MemRegion mr);// Return true if "p" is at the start of a card.bool is_card_aligned(HeapWord p) {CardValue pcard = byte_for(p);return (addr_for(pcard) == p);}// Mapping from address to card marking array entryCardValue byte_for(const void p) const {assert(_whole_heap.contains(p),"Attempt to access p = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(p), p2i(_whole_heap.start()), p2i(_whole_heap.end()));CardValue result = &_byte_map_base[uintptr_t(p) >> _card_shift];assert(result >= _byte_map && result < _byte_map + _byte_map_size,"out of bounds accessor for card marking array");return result;}// The card table byte one after the card marking array// entry for argument address. Typically used for higher bounds// for loops iterating through the card table.CardValue byte_after(const void p) const {return byte_for(p) + 1;}void invalidate(MemRegion mr);// Provide read-only access to the card table array.const CardValue byte_for_const(const void p) const {return byte_for(p);}const CardValue byte_after_const(const void p) const {return byte_after(p);}// Mapping from card marking array entry to address of first wordHeapWord addr_for(const CardValue p) const {assert(p >= _byte_map && p < _byte_map + _byte_map_size,"out of bounds access to card marking array. p: " PTR_FORMAT" _byte_map: " PTR_FORMAT " _byte_map + _byte_map_size: " PTR_FORMAT,p2i(p), p2i(_byte_map), p2i(_byte_map + _byte_map_size));// As _byte_map_base may be "negative" (the card table has been allocated before// the heap in memory), do not use pointer_delta() to avoid the assertion failure.size_t delta = p - _byte_map_base;HeapWord result = (HeapWord) (delta << _card_shift);assert(_whole_heap.contains(result),"Returning result = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(result), p2i(_whole_heap.start()), p2i(_whole_heap.end()));return result;}// Mapping from address to card marking array index.size_t index_for(void p) {assert(_whole_heap.contains(p),"Attempt to access p = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(p), p2i(_whole_heap.start()), p2i(_whole_heap.end()));return byte_for(p) - _byte_map;}CardValue byte_for_index(const size_t card_index) const {return _byte_map + card_index;}// Resize one of the regions covered by the remembered set.void resize_covered_region(MemRegion new_region);// Card-table-RemSet-specific things.static uintx ct_max_alignment_constraint();static uint card_shift() {return _card_shift;}static uint card_size() {return _card_size;}static uint card_size_in_words() {return _card_size_in_words;}static constexpr CardValue clean_card_val() { return clean_card; }static constexpr CardValue dirty_card_val() { return dirty_card; }static intptr_t clean_card_row_val() { return clean_card_row; }// Initialize card sizestatic void initialize_card_size();// Card marking array base (adjusted for heap low boundary)// This would be the 0th element of _byte_map, if the heap started at 0x0.// But since the heap starts at some higher address, this points to somewhere// before the beginning of the actual _byte_map.CardValue byte_map_base() const { return _byte_map_base; }virtual bool is_in_young(const void p) const = 0;}; class G1CardTable : public CardTable {friend class VMStructs;friend class G1CardTableChangedListener;G1CardTableChangedListener _listener;public:enum G1CardValues {g1_young_gen = CT_MR_BS_last_reserved << 1,// During evacuation we use the card table to consolidate the cards we need to// scan for roots onto the card table from the various sources. Further it is// used to record already completely scanned cards to avoid re-scanning them// when incrementally evacuating the old gen regions of a collection set.// This means that already scanned cards should be preserved.//// The merge at the start of each evacuation round simply sets cards to dirty// that are clean; scanned cards are set to 0x1.//// This means that the LSB determines what to do with the card during evacuation// given the following possible values://// 11111111 - clean, do not scan// 00000001 - already scanned, do not scan// 00000000 - dirty, needs to be scanned.//g1_card_already_scanned = 0x1};static const size_t WordAllClean = SIZE_MAX;static const size_t WordAllDirty = 0;STATIC_ASSERT(BitsPerByte == 8);static const size_t WordAlreadyScanned = (SIZE_MAX / 255) g1_card_already_scanned;G1CardTable(MemRegion whole_heap): CardTable(whole_heap), _listener() {_listener.set_card_table(this);}static CardValue g1_young_card_val() { return g1_young_gen; }static CardValue g1_scanned_card_val() { return g1_card_already_scanned; }void verify_g1_young_region(MemRegion mr) PRODUCT_RETURN;void g1_mark_as_young(const MemRegion& mr);size_t index_for_cardvalue(CardValue const p) const {return pointer_delta(p, _byte_map, sizeof(CardValue));}// Mark the given card as Dirty if it is Clean. Returns whether the card was// Clean before this operation. This result may be inaccurate as it does not// perform the dirtying atomically.inline bool mark_clean_as_dirty(CardValue card);// Change Clean cards in a (large) area on the card table as Dirty, preserving// already scanned cards. Assumes that most cards in that area are Clean.inline void mark_range_dirty(size_t start_card_index, size_t num_cards);// Change the given range of dirty cards to "which". All of these cards must be Dirty.inline void change_dirty_cards_to(CardValue start_card, CardValue end_card, CardValue which);inline uint region_idx_for(CardValue p);static size_t compute_size(size_t mem_region_size_in_words) {size_t number_of_slots = (mem_region_size_in_words / _card_size_in_words);return ReservedSpace::allocation_align_size_up(number_of_slots);}// Returns how many bytes of the heap a single byte of the Card Table corresponds to.static size_t heap_map_factor() { return _card_size; }void initialize(G1RegionToSpaceMapper mapper);bool is_in_young(const void p) const override;}; 以位为粒度的位图能准确描述每一个字的引用关系,但是一个位通常包含的信息太少,只能描述2个状态:引用还是未引用。实际应用中JVM在垃圾回收的时候需要更多的状态,如果增加至一个字节来描述状态,则位图需要256KB的空间,这个数字太大,开销占了25%。所以一个可能的做法位图不再描述一个字,而是一个区域,JVM选择512字节为单位,即用一个字节描述512字节的引用关系。选择一个区域除了空间利用率的问题之外,实际上还有现实的意义。我们知道Java对象实际上不是一个字能描述的(有一个参数可以控制对象最小对齐的大小,默认是8字节,实际上Java在JVM中还有一些附加信息,所以对齐后最小的Java对象是16字节),很多Java对象可能是几十个字节或者几百个字节,所以用一个字节描述一个区域是有意义的。但是我没有找到512的来源,为什么512效果最好?没有相应的数据来支持这个数字,而且这个值不可以配置,不能修改,但是有理由相信512字节的区域是为了节约内存额外开销。按照这个值,1MB的内存只需要2KB的额外空间就能描述引用关系。这又带来另一个问题,就是512字节里面的内存可能被引用多次,所以这是一个粗略的关系描述,那么在使用的时候需要遍历这512字节。 再举一个例子,假设有两个对象B、C都在这512字节的区域内。为了方便处理,记录对象引用关系的时候,都使用对象的起始位置,然后用这个地址和512对齐,因此B和C对象的卡表指针都指向这一个卡表的位置。那么对于引用处理也有可有两种处理方法:·处理的时候会以堆分区为处理单位,遍历整个堆分区,在遍历的时候,每次都会以对象大小为步长,结合卡表,如果该卡表中对应的位置被设置,则说明对象和其他分区的对象发生了引用。具体内容在后文中介绍Refine的时候还会详细介绍。·处理的时候借助于额外的数据结构,找到真正对象的位置,而不需要从头开始遍历。在后文的并发标记处理时就使用了这种方法,用于找到第一个对象的起始位置。在G1除了512字节粒度的卡表之外,还有bitMap,例如使用bitMap可以描述一个分区对另外一个分区的引用情况。在JVM中bitMap使用非常多,例如还可以描述内存的分配情况。 在G1除了512字节粒度的卡表之外,还有bitMap,例如使用bitMap可以描述一个分区对另外一个分区的引用情况。在JVM中bitMap使用非常多,例如还可以描述内存的分配情况。G1在混合收集算法中用到了并发标记。在并发标记的时候使用了bitMap来描述对象的分配情况。例如1MB的分区可以用16KB(16KB×ObjectAlignmentInBytes×8=1MB)来描述,即16KB额外的空间。其中ObjectAlignmentInBytes是8字节,指的是对象对齐,第二个8是指一个字节有8位。即每一个位可以描述64位。例如一个对象长度对齐之后为24字节,理论上它占用3个位来描述这个24字节已被使用了,实际上并不需要,在标记的时候只需要标记这3个位中的第一个位,再结合堆分区对象的大小信息就能准确找出。其最主要的目的是为了效率,标记一个位和标记3个位相比能节约不少时间,如果对象很大,则更划算。这些都是源码的实现细节,大家在阅读源码时需要细细斟酌。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_16500963/article/details/132133125。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-16 20:37:50
245
转载
Lua
...Lua的世界里,表(table)是最强大的数据结构之一,它既可以作为数组,也可以作为关联数组或字典使用。然而,在我们实实在在敲代码的时候,经常会遇到这么个让人挠头的小状况:“哎呀,竟然试图访问一个在表格里压根不存在的键”,这样一来,程序可就要闹情绪,抛出运行时错误了。这篇东西,咱们就瞄准这个主题使劲深挖一下,而且我还会甩出多个代码实例,保准让大家伙儿不仅能明白这个问题是怎么回事,更能掌握解决它的方法,保证接地气儿,不带一点儿机器味儿! 1. 键不存在错误的基本概念 首先,我们需要明确的是,当你试图访问一个在Lua表中并不存在的键时,Lua并不会默默地返回nil,而是会抛出一个错误。例如: lua local my_table = {name = "John", age = 30} print(my_table["address"]) -- 这将会抛出错误:attempt to index a nil value (field 'address') 在这个例子中,我们尝试从my_table获取"address"对应的值,但该键并不存在于表中,因此Lua抛出了“键不存在”错误。 2. 如何安全地访问可能不存在的键 为了避免上述错误的发生,我们可以利用Lua中的条件判断和nil检查机制来安全地访问表中的键。下面是一个典型的示例: lua local my_table = {name = "John", age = 30} -- 安全访问方式:先检查键是否存在,再进行访问 if my_table.address then print(my_table.address) else print("Address is not set.") end 或者,你可以使用Lua的rawget函数,它不会触发元方法且对键的类型没有限制,同时也不会抛出错误: lua local address = rawget(my_table, "address") if address then print(address) else print("Address is not set.") end 3. 使用pairs和ipairs遍历检查键的存在性 当不确定表中有哪些键时,可以采用遍历的方式来检查: lua for key, value in pairs(my_table) do if key == "address" then print(value) break end end -- 如果是数字索引的连续数组部分,可以使用 ipairs for i = 1, my_table do if i == my_expected_index then print(my_table[i]) break end end 4. 自定义默认返回值——空合并操作符 // Lua 5.3引入了一个非常有用的特性——空合并操作符(也称为nil合并操作符)//,它可以用于提供默认值: lua local my_table = {name = "John", age = 30} print(my_table.address // "No Address") -- 输出 "No Address" 在这个例子中,如果my_table.address为nil,则会返回后面的字符串"No Address",这样就避免了键不存在的错误。 结语:思考与探讨 理解并妥善处理Lua表中键可能不存在的情况,是Lua编程过程中的重要一环。掌握这些技巧不仅可以避免程序因意外的键访问错误而崩溃,还能使我们的代码更加健壮、易读。希望本文的讨论和实例代码能帮助你更深入地理解这一问题,并在今后的编程实践中灵活运用,让Lua代码如丝般顺滑地运行。记住,编程不仅仅是解决问题,更是不断探索、学习和成长的过程。
2023-05-17 14:22:20
38
春暖花开
Apache Atlas
...e Atlas进行大数据领域中的元数据管理时,我们可能会遇到一个问题:Atlas Server在启动过程中出现内存溢出。伙计,这可是个大问题啊!你想啊,如果服务器罢工了,启动不了,那咱们的应用程序也就跟着玩儿不转了。本文将详细分析这个问题的原因,并提供一些可能的解决方案。 2. 问题分析 首先,我们需要了解什么是内存溢出。当程序试图分配的内存超过了系统可以提供的最大值时,就会发生内存溢出。这种情况下,系统会终止程序的执行,以防止更多的资源被消耗。 在Apache Atlas中,内存溢出通常是由于元数据库(如HBase)加载过多的数据导致的。这是因为每当数据库里有新的元数据项加入时,Atlas就像个勤劳的小助手,会麻利地把这些新数据加载进来,以便更好地应对接下来的各项操作任务。如果数据库里的元数据项实在是多到爆炸,那么加载这些玩意儿的时候,很可能会像饿狼扑食一样,大口大口地“吃掉”大量的内存。 3. 解决方案 为了解决这个问题,我们可以采取以下几种策略: 1) 数据清理:定期对元数据库进行清理,删除不再需要的历史数据。这样可以减少数据库中的数据量,从而降低内存消耗。 java // 示例代码,使用HBase API删除指定列族的所有行 HTable table = new HTable(conf, tableName); Delete delete = new Delete(rowKey); for (byte[] family : columnFamilies) { delete.addFamily(family); } table.delete(delete); 2) 数据分片:将元数据数据库分成多个部分,然后分别在不同的服务器上存储。这样一来,每台服务器只需要分担一小部分数据的处理工作,就完全能够巧妙地避开那种因为数据量太大,内存承受不住,像杯子装满水会溢出来一样的尴尬情况啦。 java // 示例代码,使用HBase API创建新的表,并设置表的分片策略 TableName tableName = TableName.valueOf("my_table"); HColumnDescriptor columnDesc = new HColumnDescriptor("info"); HRegionInfo regionInfo = new HRegionInfo(tableName, null, null, false); table = TEST_UTIL.createLocalHTable(regionInfo, columnDesc); table.setSplitPolicy(new MySplitPolicy()); 3) 使用外部缓存:对于那些频繁访问但不经常更新的元数据项,可以将其存储在一个独立的缓存中。这样,即使缓存中的数据量很大,也不会对主服务器的内存产生太大的压力。 java // 示例代码,使用Memcached作为外部缓存 MemcachedClient client = new MemcachedClient( new TCPNonblockingServerSocketFactory(), new InetSocketAddress[] {new InetSocketAddress(host, port)}); client.set(key, expirationTimeInMilliseconds, value); 这些只是一些基本的解决方案,具体的实施方式还需要根据你的实际情况进行调整。总的来说,想要搞定Apache Atlas服务器启动时那个烦人的内存溢出问题,咱们得在设计和运维这两块儿阶段都得提前做好周全的打算和精心的布局。 4. 结语 在使用Apache Atlas进行元数据管理时,我们可能会遇到各种各样的问题。但是,只要我们有足够的知识和经验,总能找到解决问题的方法。希望这篇文章能对你有所帮助。
2023-02-23 21:56:44
520
素颜如水-t
转载文章
...,二维数组是一种多维数据结构,用于存储表格形式的数据。在本文的上下文中,二维数组squareSet被用来存储消除类游戏中的方块信息,每个元素是一个子数组,代表一行方块,子数组中的每个元素则表示一个具体方块的信息,如颜色、行列位置等。通过使用二维数组,开发者能够方便地根据行列索引访问和操作每一个方块。 连通图算法 , 在计算机科学中,连通图算法是指处理图论问题的一种方法,通常用于确定图中的节点(或对象)是否通过边(或关系)彼此相连形成一个连通分量。在这篇文章中,作者应用了一个递归实现的连通图算法——checkLinked函数,当玩家鼠标移入某个方块时,该算法会遍历与其颜色相同的相邻方块,检查并收集所有可以消除的连通方块,以便进行后续的计分和动画效果展示。 定时器(Timer) , 定时器是浏览器提供的JavaScript特性之一,允许开发人员设置一段代码在特定时间间隔后执行。在这篇文章描述的游戏开发过程中,定时器被用来实现选中方块的闪烁特效。通过设置一个定时器(例如timer变量),每经过一定的时间间隔(如300毫秒),就改变选中方块的样式属性,使其产生连续的视觉变化,从而达到闪烁的效果。 绝对定位(Absolute Positioning) , 在CSS布局中,绝对定位是一种定位模式,它允许开发人员为元素指定精确的坐标值来决定其在页面上的确切位置,而不是遵循正常的文档流。文章中创建的小方块采用的就是绝对定位方式,确保它们可以根据行列位置准确地放置于游戏画布上,无论其他元素如何变化,这些方块的位置始终保持不变。
2023-06-08 15:26:34
515
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
Ctrl+R
- 启动反向搜索历史命令功能。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"