前端技术
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
[小写英文字母]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Python
...代码)是一种基于拉丁字母的一套电脑编码系统,原本被设计为7位的二进制数来表示128种可能的字符,包括大小写英文字母、数字0-9、标点符号及特殊控制字符。在Python 2.x版本中,默认字符集为ASCII码,由于其字符集有限,无法直接支持显示中文等非ASCII字符。 Unicode编码 , Unicode是一个国际通用的字符集标准,旨在统一和涵盖世界上所有书面语言中的字符。它采用多字节编码方式,可以表示几乎所有人类使用的文字符号。在Python中,字符串默认使用Unicode编码,因此处理包含中文的字符串时,需要确保输出时正确转换到对应系统的编码格式以显示中文。 Python 2.x版本与Python 3.x版本 , Python是一门不断演进发展的编程语言,根据其主要版本迭代可分为Python 2.x系列和Python 3.x系列。Python 2.x版本对Unicode的支持相对有限,需要显式声明编码才能正确处理非ASCII字符;而Python 3.x版本则改进了对Unicode的支持,将默认源文件编码设置为utf-8,简化了处理非英文字符的过程,但在实际操作中仍需注意输出时的编码问题。
2023-10-24 16:40:49
333
算法侠
转载文章
...伯数字计数,而是使用小写英文字母计数,他觉得这样做,会使世界更加丰富多彩。 在他的计数法中,每个数字的位数都是相同的(使用相同个数的字母),英文字母按原先的顺序,排在前面的字母小于排在它后面的字母。我们把这样的“数字”称为Jam数字。在Jam数字中,每个字母互不相同,而且从左到右是严格递增的。每次,Jam还指定使用字母的范围,例如,从2到10,表示只能使用 b , c , d , e , f , g , h , i , j {b,c,d,e,f,g,h,i,j} b,c,d,e,f,g,h,i,j这些字母。如果再规定位数为5,那么,紧接在Jam数字“bdfijbdfij”之后的数字应该是“bdghibdghi”。(如果我们用U、V依次表示JamJam数字“bdfijbdfij”与“bdghibdghi”,则U<V,且不存在Jam数字P,使U<P<V)。 你的任务是:对于从文件读入的一个Jam数字,按顺序输出紧接在后面的5个Jam数字,如果后面没有那么多Jam数字,那么有几个就输出几个。 输入格式 共2行。 第1行为3个正整数,用一个空格隔开:s t w(其中s为所使用的最小的字母的序号,t为所使用的最大的字母的序号。w为数字的位数,这3个数满足: 1 ≤ s < T ≤ 26 , 2 ≤ w ≤ t − s 1≤s<T≤26, 2≤w≤t-s 1≤s<T≤26,2≤w≤t−s ) 第2行为具有w个小写字母的字符串,为一个符合要求的Jam数字。 所给的数据都是正确的,不必验证。 输出格式 最多为5行,为紧接在输入的Jam数字后面的5个Jam数字,如果后面没有那么多Jam数字,那么有几个就输出几个。每行只输出一个Jam数字,是由w个小写字母组成的字符串,不要有多余的空格。 输入输出样例 输入 2 10 5bdfij 输出 bdghibdghjbdgijbdhijbefgh 说明/提示 NOIP 2006 普及组 第三题 —————————————— 今天考试,当然不是14年前的普及组考试,是今天的东城区挑战赛,第三道题就是这道题,只不过改成了“唐三的计数法”,我没做过这道题,刚看到这道题还以为要用搜索,写了一个小时,直接想复杂了。后来才明白直接模拟即可! 从最后一位开始,尝试加一个字符,然后新加的字符以后的所有字符都要紧跟(就这一点,我用深搜写不出来,归根结底还是理解不够),才能使新增的字符串紧跟上一个字符串。 include <iostream>include <cstring>include <cstdio>using namespace std;int main(){int s, t, w;char str[30];cin >> s >> t >> w >> str;for (int i = 1; i <= 5; i++){for (int j = w - 1; j >= 0; j--){if (str[j] + 1 <= ('a' + (t - (w - j)))){// 确认当前有可用字母就可以大胆用了,j就是变动位str[j] += 1;// 当前位置后的位置都是对齐位for (int k = j + 1; k < w; k++)str[k] = str[j] + k - j;cout << str << endl;// 是每次找到一组合适的就跳出break;} }}return 0;}/一个方法做的时间超过半小时,或者思路减退、代码渐渐复杂、心态渐渐崩溃时,要及时切换思路。/ 本篇文章为转载内容。原文链接:https://blog.csdn.net/cool99781/article/details/116902217。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-02-12 12:42:53
562
转载
Java
...一和涵盖全球各种语言文字符号,为每种字符分配一个唯一的数字(码点)。在Java中,char类型占用两个字节(16位),可以表示Unicode中的基本多文种平面 BMP (Basic Multilingual Plane) 的任何字符,包括拉丁字母、中文汉字、特殊符号等。 ASCII码 , ASCII(American Standard Code for Information Interchange,美国信息交换标准代码)是基于拉丁字母的一套电脑编码系统,原本被设计为7位的二进制数来表示128个可能的字符,包括英文大小写字母、数字、标点符号以及一些控制字符。在Java中,虽然char类型能够存储更大的Unicode字符集,但其最初设计时也兼容ASCII码。 自动装箱与拆箱 , 在Java编程中,自动装箱是指将基本数据类型(如char)自动转换成对应的包装器类对象(如Character),而自动拆箱则是指将包装器类对象自动转换为对应的基本数据类型。例如,在使用Character类方法时,编译器会自动将char类型的变量转换为Character对象(装箱),执行完方法后再转换回char类型(拆箱),这一过程对程序员来说是透明的,有助于简化代码并提高开发效率。 基本数据类型 , 在Java编程语言中,基本数据类型是预先定义好的,具有固定内存大小且不可再细分的数据种类,如int、char、boolean等。它们直接存储值而不是引用,并且不涉及类实例化的过程。比如char,它是Java中用于存储单个字符的基本数据类型。 包装器类 , Java为每个基本数据类型都提供了一个对应的引用类型,这些引用类型被称为包装器类,如Integer对应int,Character对应char等。包装器类的主要作用在于,当需要将基本类型当作对象处理(例如放入集合类中,或者调用方法时作为参数传递)时,可以将基本类型数据封装成对象。同时,包装器类还提供了很多实用的方法来进行数值处理或类型判断等功能。例如,Character类就是对char基本类型的包装,提供了诸如isLetter()和isDigit()等方法,用于判断字符是否为字母或数字。
2023-01-16 09:53:47
470
数据库专家
PHP
...像不同的语言有不同的字母表一样,在不同的字符集中可能有着不一样的“身份证”——编码。iconv函数这个家伙吧,它就比较死板了,只能识别和处理固定的一种字符集,其他的就认不出来了。在这种情况下,我们就需要使用更复杂的方法来处理字符串了。 四、深入理解EncodingEncodingException EncodingEncodingException实际上是由于字符集之间的不兼容性引起的。在计算机的世界里,其实所有的文本都是由一串串数字“变身”出来的,就好比我们用不同的字符编码规则来告诉计算机:喂喂喂,当你看到这些特定的数字时,你要知道它们代表的是哪个字符!就像是给每个字符配上了一串独一无二的数字密码。因此,当我们尝试将一个字符集中的文本转换为另一个字符集中的文本时,如果这两个字符集对于某些字符的规定不同,那么就可能出现无法转换的情况。 这就是EncodingEncodingException的原理。为了避免犯这种错误,咱们得把各种字符集的脾性摸个透彻,然后根据需求挑选最合适的那个进行编码和解码的工作。就像是选择工具箱里的工具一样,不同的字符集就是不同的工具,用对了才能让工作顺利进行,不出差错。 总结,虽然EncodingEncodingException是一种常见的错误,但是只要我们理解其原因并采取适当的措施,就能够有效地避免这个问题。希望这篇文章能够帮助你更好地理解和处理EncodingEncodingException。
2023-11-15 20:09:01
85
初心未变_t
JQuery插件下载
...密码长度、是否包含大小写字母、数字以及特殊字符等元素。在视觉呈现上,该插件会以直观的形式展示密码强度,如进度条、颜色变化或者文字提示(例如“弱”、“中”、“强”或“非常强”)。此外,为了提升用户体验,插件还可能支持密码显示/隐藏切换功能,允许用户在输入过程中查看已输入的密码内容,确保无误。总之,这款jQuery密码输入框插件为网页表单增添了安全保障与用户体验优化,帮助开发者轻松实现对用户密码安全性的即时指导与强化,从而提升网站的整体安全水平。 点我下载 文件大小:45.19 KB 您将下载一个JQuery插件资源包,该资源包内部文件的目录结构如下: 本网站提供JQuery插件下载功能,旨在帮助广大用户在工作学习中提升效率、节约时间。 本网站的下载内容来自于互联网。如您发现任何侵犯您权益的内容,请立即告知我们,我们将迅速响应并删除相关内容。 免责声明:站内所有资源仅供个人学习研究及参考之用,严禁将这些资源应用于商业场景。 若擅自商用导致的一切后果,由使用者承担责任。
2023-12-06 19:26:44
107
本站
JQuery插件下载
...长度要求、是否包含大小写字母、数字以及特殊字符。这些规则不仅能够提升用户体验,还能显著增强网站的安全性。对于需要更个性化需求的开发者,passwordRulesHelper.js提供了灵活的配置选项,允许用户根据项目需求自定义密码强度规则。这意味着你可以设定任何符合特定场景的规则,比如限制密码中不得出现连续重复的字符,或者禁止使用某些敏感词汇作为密码的一部分。这种高度定制化的能力使得该插件适用于各种类型的网站和应用。此外,passwordRulesHelper.js还具备友好的用户界面反馈机制。当用户输入密码时,插件会即时显示密码强度提示,如通过颜色变化(绿色表示强,黄色表示中等,红色表示弱)或文字说明来直观反映当前密码的安全等级。这不仅提高了用户体验,也鼓励用户创建更安全的密码。总而言之,passwordRulesHelper.js凭借其强大的功能、高度的可定制性和直观的用户反馈,成为开发人员提升网站安全性、优化用户体验的理想选择。无论是小型个人博客还是大型企业级平台,它都能发挥重要作用。 点我下载 文件大小:44.53 KB 您将下载一个JQuery插件资源包,该资源包内部文件的目录结构如下: 本网站提供JQuery插件下载功能,旨在帮助广大用户在工作学习中提升效率、节约时间。 本网站的下载内容来自于互联网。如您发现任何侵犯您权益的内容,请立即告知我们,我们将迅速响应并删除相关内容。 免责声明:站内所有资源仅供个人学习研究及参考之用,严禁将这些资源应用于商业场景。 若擅自商用导致的一切后果,由使用者承担责任。
2024-11-06 11:02:55
65
本站
JQuery
jQuery 中文字符编码转换的艺术 1. 引言 为什么需要中文转编码? 当我们深入探索jQuery的世界,尤其是在处理网页交互、数据传输以及DOM操作时,中文字符的正确编码与解码是我们无法回避的问题。在咱们做JavaScript和Web开发这行,由于一些陈年旧账和技术的迭代更新,浏览器之间的兼容性问题时不时就会冒个泡。所以啊,老铁们,确保字符串都以UTF-8这种格式编码,那可是相当关键的一环,可马虎不得!尤其是当你在URL查询参数、Ajax请求内容或JSON数据序列化过程中遇到包含中文字符的字符串时,不恰当的编码可能会导致乱码或数据丢失。本文将带你通过生动具体的示例,揭示如何运用jQuery巧妙地实现中文字符到UTF-8编码的转换。 2. 理解基础 字符编码与Unicode 首先,让我们对“字符编码”这个概念有个基本的认识。在计算机世界里,每个字符都有对应的数字编码,比如ASCII码对于英文字符,而Unicode则是一个包含了全球所有语言字符的统一编码方案。UTF-8是一种变长的Unicode编码方式,它能高效地表示各种语言的字符,特别是对于中文这种非拉丁字符集尤为适用。 3. jQuery不是万能钥匙 JavaScript原生方法 尽管jQuery提供了丰富的DOM操作接口,但在处理字符串编码问题上,并没有直接提供特定的方法。实际上,我们通常会借助JavaScript的内置函数来完成这一任务。这是因为,在JavaScript的大脑里,它其实早就把字符串用UTF-16编码(这货也是Unicode家族的一员)给存起来了。所以,在我们捣鼓JS的时候,更关心的是怎么把这些字符串巧妙地变身成UTF-8格式,这样一来它们就能在网络世界里畅行无阻啦。 javascript // 假设有一个包含中文的字符串 var chineseString = "你好,世界!"; // 转换为UTF-8编码的字节数组 // 注意:在现代浏览器环境下,无需手动转码,此步骤仅作演示 var utf8Bytes = unescape(encodeURIComponent(chineseString)).split('').map(function(c) { return c.charCodeAt(0).toString(16); }); console.log(utf8Bytes); // 输出UTF-8编码后的字节表示 上述代码中,encodeURIComponent 方法用于将字符串中的特殊及非ASCII字符转换为适合放在URL中的形式,其实质上就是进行了UTF-8编码。然后使用 unescape 反解这个过程,得到一个已经在内存中以UTF-8编码的字符串。最后将其转化为字节数组并输出十六进制表示。 4. 实战应用场景 Ajax请求与JSON.stringify() 在实际的jQuery应用中,如发送Ajax请求: javascript $.ajax({ url: '/api/some-endpoint', type: 'POST', contentType: 'application/json; charset=UTF-8', // 设置请求头表明数据格式及编码 data: JSON.stringify({ message: chineseString }), // 自动处理中文编码 success: function(response) { console.log('Data sent and received successfully!'); } }); 在这个例子中,jQuery的$.ajax方法配合JSON.stringify将包含中文字符的对象自动转换为UTF-8编码的JSON字符串,服务器端接收到的数据能够正确解码还原。 5. 总结与思考 虽然jQuery本身并未直接提供中文转UTF-8编码的API,但通过理解和熟练运用JavaScript的内建方法,我们依然可以轻松应对这类问题。尤其在处理跨语言、跨平台的数据交换时,确保字符编码的一致性和正确性至关重要。在实际动手操作的项目里,除了得把编码转换搞定,还千万不能忘了给HTTP请求头穿上“马甲”,明确告诉服务器咱们数据是啥样的编码格式,这样才能确保信息传递时一路绿灯,准确无误。下一次当你在jQuery项目中遇到中文编码难题时,希望这篇文章能成为你的得力助手,帮你拨开迷雾,顺利解决问题。记住,编码问题虽小,但关乎用户体验,不容忽视。
2023-04-05 10:17:37
308
凌波微步
转载文章
...是在做类神经网络处理文字辨识,以你的例子而言,旋转随意角度对辨识来说并不会有太大影响,只要抓字的重心,360度旋转抓取特微值,还是可以辨识的出来。 通常文字辨识的有一个重要的动作,就是要把个别文字分割,你只要把文字弄的难分割就有不错的安全性。 --------------------------------------------------- 代码比较粗糙,而且比较菜,其中遇到一个问题,未对 Graphics 填充底色,那么文字的 ClearType 效果没有了,文字毛边比较明显,不知道为什么,谁能告诉竹子? 代码相对粗糙,没有考虑更多的情况,在测试过程中,以20px 字体呈现,效果感觉还不错,只是 ClearType 效果没有了。 帖几张看看 ------------ ------------ ------------ ------------ 有一些随机的不好,象下面这张 相关链接: 查看 V1.0 .NET 2.0 代码如下: using System; using System.Drawing; using System.Web; namespace Oran.Image { /// <summary> /// 旋转的可视验证码图象 /// </summary> public class RotatedVlidationCode { public enum RandomStringMode { /// <summary> /// 小写字母 /// </summary> LowerLetter, /// <summary> /// 大写字母 /// </summary> UpperLetter, /// <summary> /// 混合大小写字母 /// </summary> Letter, /// <summary> /// 数字 /// </summary> Digital, /// <summary> /// 混合数字与大小字母 /// </summary> Mix } public static string GenerateRandomString(int length, RandomStringMode mode) { string rndStr = string.Empty; if (length == 0) return rndStr; //以数组方式候选字符,可以更方便的剔除不要的字符,如数字 0 与字母 o char[] digitals = new char[10] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; char[] lowerLetters = new char[26] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; char[] upperLetters = new char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; char[] letters = new char[52]{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; char[] mix = new char[62]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; int[] range = new int[2] { 0, 0 }; Random random = new Random(); switch (mode) { case RandomStringMode.Digital: for (int i = 0; i < length; ++i) rndStr += digitals[random.Next(0, digitals.Length)]; break; case RandomStringMode.LowerLetter: for (int i = 0; i < length; ++i) rndStr += lowerLetters[random.Next(0, lowerLetters.Length)]; break; case RandomStringMode.UpperLetter: for (int i = 0; i < length; ++i) rndStr += upperLetters[random.Next(0, upperLetters.Length)]; break; case RandomStringMode.Letter: for (int i = 0; i < length; ++i) rndStr += letters[random.Next(0, letters.Length)]; break; default: for (int i = 0; i < length; ++i) rndStr += mix[random.Next(0, mix.Length)]; break; } return rndStr; } /// <summary> /// 显示验证码 /// </summary> /// <param name="seed">随机数辅助种子</param> /// <param name="strLen">验证码字符长度</param> /// <param name="fontSize">字体大小</param> /// <param name="mode">随机字符模式</param> /// <param name="clrFont">字体颜色</param> /// <param name="clrBg">背景颜色</param> public static void ShowValidationCode(ref int seed, int strLen, int fontSize, RandomStringMode mode, Color clrFont, Color clrBg) { int tmpSeed; unchecked { tmpSeed = (int)(seed DateTime.Now.Ticks); ++seed; } Random rnd = new Random(tmpSeed); string text = GenerateRandomString(strLen, mode); int height = fontSize 2; // 因为字体旋转后每个字体所占宽度会所有加大,所以要加一点补偿宽度 int width = fontSize text.Length + fontSize / (text.Length - 2); Bitmap bmp = new Bitmap(width, height); Graphics graphics = Graphics.FromImage(bmp); Font font = new Font("Courier New", fontSize, FontStyle.Bold); Brush brush = new SolidBrush(clrFont); Brush brushBg = new SolidBrush(clrBg); graphics.FillRectangle(brushBg, 0, 0, width, height); Bitmap tmpBmp = new Bitmap(height, height); Graphics tmpGph = null; int degree = 40; Point tmpPoint = new Point(); for (int i = 0; i < text.Length; i++) { tmpBmp = new Bitmap(height, height); tmpGph = Graphics.FromImage(tmpBmp); // tmpGph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; // 不填充底色,文字 ClearType 效果不见了,why?! // tmpGph.FillRectangle(brushBg, 0, 0, tmpBmp.Width, tmpBmp.Height); degree = rnd.Next(20, 51); // [20, 50]随机角度 if (rnd.Next(0, 2) == 0) { tmpPoint.X = 12; // 调整文本坐标以适应旋转后的图象 tmpPoint.Y = -6; } else { degree = ~degree + 1; // 逆时针旋转 tmpPoint.X = -10; tmpPoint.Y = 6; } tmpGph.RotateTransform(degree); tmpGph.DrawString(text[i].ToString(), font, brush, tmpPoint); graphics.DrawImage(tmpBmp, i fontSize, 0); // 拼接图象 } //输出图象 System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ContentType = "image/gif"; HttpContext.Current.Response.BinaryWrite(memoryStream.ToArray()); HttpContext.Current.Response.End(); //释放资源 font.Dispose(); brush.Dispose(); brushBg.Dispose(); tmpGph.Dispose(); tmpBmp.Dispose(); graphics.Dispose(); bmp.Dispose(); memoryStream.Dispose(); } } } 转载于:https://www.cnblogs.com/iRed/archive/2008/06/22/1227687.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_30600197/article/details/96672619。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-27 09:38:56
249
转载
转载文章
...接收小于等于64KB英文字符的变量和变量名,否则将无法编译。 5.访问标志(Access Flags) 在常量池结束后,紧接着的两个字节代表访问标志(Access Flags),该标志用于识别一些类或者接口层次的访问信息,其中包括:Class是类还是接口、是否定义为public、是否定义为abstract类型、类是否被声明为final等。 访问标志表 标志位一共有16个,但是并不是所有的都用到,上表只列举了其中8个,没有使用的标志位统统置为0,access_flags只有2个字节表示,但是有这么多标志位怎么计算而来的呢?它是由标志位为true的标志位值取或运算而来,比如这里我演示的class文件是一个类并且是public的,所以对应的ACC_PUBLIC和ACC_SIPER标志应该置为true,其余标志不满足则为false,那么access_flags的计算过程就是:Ox0001 | Ox0020 = Ox0021 篇幅原因,未完待续...... 参考文献:《深入理解Java虚拟机》 END 本篇文章为转载内容。原文链接:https://javar.blog.csdn.net/article/details/97532925。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-01-09 17:46:36
645
转载
转载文章
...13/2011; ‘英文月名 日, 年’,如 May 25, 2004; ‘英文星期几 英文月名 日 年 时:分:秒 时区’,如 Tue May 25 2004 00:00:00 GMT-070 alert(Date.parse('6/13/2011')); // 1307894400000 如果 Date.parse()没有传入或者不是标准的日期格式,那么就会返回 NaN。 alert(Date.parse()); // NaN 如果想输出指定的日期,那么把 Date.parse()传入 Date 构造方法里。 var box = new Date(Date.parse('6/13/2011')); // Mon Jun 13 2011 00:00:00 GMT+0800var box = new Date('6/13/2011'); // 直接传入,Date.parse()后台被调用 Date 对象及其在不同浏览器中的实现有许多奇怪的行为。其中有一种倾向是将超出的范围的值替换成当前的值,以便生成输出。例如,在解析“January 32, 2007”时,有的浏览器会将其解释为“February 1, 2007”。而 Opera 则倾向与插入当前月份的当前日期。 Date.UTC()方法同样也返回表示日期的毫秒数,但它与 Date.parse()在构建值时使用不同的信息。(年份,基于 0 的月份[0 表示 1 月,1 表示 2 月],月中的哪一天[1-31],小时数[0-23] ,分钟,秒以及毫秒)。只有前两个参数是必须的。如果没有提供月数,则天数为 1;如果省略其他参数,则统统为 0。 alert(Date.UTC(2011,11)); // 1322697600000 如果 Date.UTC()参数传递错误,那么就会出现负值或者 NaN 等非法信息。 alert(Date.UTC()); // 负值或者 NaN 如果要输出指定日期,那么直接把 Date.UTC()传入 Date 构造方法里即可。 var box = new Date(Date.UTC(2011,11, 5, 15, 13, 16)); 通用的方法 与其他类型一样,Date 类型也重写了 toLocaleString()、toString()和 valueOf()方法;但这些方法返回值与其他类型中的方法不同。 var box = new Date(Date.UTC(2011,11, 5, 15, 13, 16));alert('toString:' + box.toString());alert('toLocaleString:' + box.toLocaleString()); // 按本地格式输出 这两个方法在不同浏览器显示的效果又不一样,但不用担心,这两个方法只是在调试比较有用,在显示时间和日期上,没什么价值。valueOf()方法显示毫秒数。 日期格式化方法 Date 类型还有一些专门用于将日期格式化为字符串的方法。 var box = new Date();alert(box.toDateString()); // 以特定的格式显示星期几、月、日和年alert(box.toTimeString()); // 以特定的格式显示时、分、秒和时区alert(box.toLocaleDateString()); // 以特定地区格式显示星期几、月、日和年alert(box.toLocaleTimeString()); // 以特定地区格式显示时、分、秒和时区alert(box.toUTCString()); // 以特定的格式显示完整的 UTC 日期 组件方法 组件方法,是为我们单独获取你想要的各种时间/日期而提供的方法。需要注意的时候 ,这些方法中,有带 UTC 的,有不带 UTC 的。UTC 日期指的是在没有时区偏差的情况下的日期值。 alert(box.getTime()); // 获取日期的毫秒数,和 valueOf()返回一致alert(box.setTime(100)); // 以毫秒数设置日期,会改变整个日期alert(box.getFullYear()); // 获取四位年份alert(box.setFullYear(2012)); // 设置四位年份,返回的是毫秒数alert(box.getMonth()); // 获取月份,没指定月份,从 0 开始算起alert(box.setMonth(11)); // 设置月份alert(box.getDate()); // 获取日期alert(box.setDate(8)); // 设置日期,返回毫秒数alert(box.getDay()); // 返回星期几,0 表示星期日,6 表示星期六alert(box.setDay(2)); // 设置星期几alert(box.getHours()); // 返回时alert(box.setHours(12)); // 设置时alert(box.getMinutes()); // 返回分钟alert(box.setMinutes(22)); // 设置分钟alert(box.getSeconds()); // 返回秒数alert(box.setSeconds(44)); // 设置秒数alert(box.getMilliseconds()); // 返回毫秒数alert(box.setMilliseconds()); // 设置毫秒数alert(box.getTimezoneOffset()); // 返回本地时间和 UTC 时间相差的分钟数 以上方法除了 getTimezoneOffset(),其他都具有 UTC 功能,例如 setDate()及 getDate()获取星期几,那么就会有 setUTCDate()及getUTCDate(),表示世界协调时间。 2、正则表达式 假设用户需要在 HTML 表单中填写姓名、地址、出生日期等。那么在将表单提交到服务器进一步处理前,JavaScript 程序会检查表单以确认用户确实输入了信息并且这些信息是符合要求的。 什么是正则表达式 正则表达式(regular expression)是一个描述字符模式的对象。ECMAScript 的 RegExp 类表示正则表达式,而 String 和 RegExp 都定义了使用正则表达式进行强大的模式匹配和文本检索与替换的函数。 正则表达式主要用来验证客户端的输入数据。用户填写完表单单击按钮之后,表单就会被发送到服务器,在服务器端通常会用 PHP、ASP.NET 等服务器脚本对其进行进一步处理 。因为客户端验证,可以节约大量的服务器端的系统资源,并且提供更好的用户体验。 创建正则表达式 创建正则表达式和创建字符串类似,创建正则表达式提供了两种方法,一种是采用 new 运算符,另一个是采用字面量方式。 两种创建方式 var box = new RegExp('box'); // 第一个参数字符串var box = new RegExp('box', 'ig'); // 第二个参数可选模式修饰符 模式修饰符的可选参数 参数 含义 i 忽略大小写 g 全局匹配 m 多行匹配 var box = /box/; // 直接用两个反斜杠var box = /box/ig; // 在第二个斜杠后面加上模式修饰符 测试正则表达式 RegExp 对象包含两个方法:test()和 exec(),功能基本相似,用于测试字符串匹配。test()方法在字符串中查找是否存在指定的正则表达式并返回布尔值,如果存在则返回 true,不存在则返回 false。exec()方法也用于在字符串中查找指定正则表达式,如果 exec()方法执行成功,则返回包含该查找字符串的相关信息数组。如果执行失败,则返回 null。 RegExp 对象的方法 方法 功能 test 在字符串中测试模式匹配,返回 true 或 false exec 在字符串中执行匹配搜索,返回结果数组 // 使用 new 运算符的 test 方法示例var pattern = new RegExp('box', 'i'); // 创建正则模式,不区分大小写var str = 'This is a Box!'; // 创建要比对的字符串alert(pattern.test(str)); // 通过 test()方法验证是否匹配// 使用字面量方式的 test 方法示例var pattern = /box/i; // 创建正则模式,不区分大小写var str = 'This is a Box!';alert(pattern.test(str));// 使用一条语句实现正则匹配alert(/box/i.test('This is a Box!')); // 模式和字符串替换掉了两个变量// 使用 exec 返回匹配数组var pattern = /box/i;var str = 'This is a Box!';alert(pattern.exec(str)); // 匹配了返回数组,否则返回 null 使用字符串的正则表达式方法 除了 test()和 exec()方法,String 对象也提供了 4 个使用正则表达式的方法。 String 对象中的正则表达式方法 方法 含义 match(pattern) 返回 pattern 中的子串或 null replace(pattern, replacement) 用 replacement 替换 pattern search(pattern) 返回字符串中 pattern 开始位置 split(pattern) 返回字符串按指定 pattern 拆分的数组 // 使用 match 方法获取获取匹配数组var pattern = /box/ig; // 全局搜索var str = 'This is a Box!,That is a Box too';alert(str.match(pattern)); // 匹配到两个 Box,Boxalert(str.match(pattern).length); // 获取数组的长度// 使用 search 来查找匹配数据var pattern = /box/ig;var str = 'This is a Box!,That is a Box too';alert(str.search(pattern)); // 查找到返回位置,否则返回-1 因为 search 方法查找到即返回,也就是说无需 g 全局。 // 使用 replace 替换匹配到的数据var pattern = /box/ig;var str = 'This is a Box!,That is a Box too';alert(str.replace(pattern, 'Tom')); // 将 Box 替换成了 Tom// 使用 split 拆分成字符串数组var pattern = / /ig;var str = 'This is a Box!,That is a Box too';alert(str.split(pattern)); // 将空格拆开分组成数组 RegExp 对象的静态属性 属性 短名 含义 input $_ 当前被匹配的字符串 lastMatch $& 最后一个匹配字符串 lastParen $+ 最后一对圆括号内的匹配子串 leftContext $ 最后一次匹配前的子串 multiline $ 用于指定是否所有的表达式都用于多行的布尔值 rightContext $’ 在上次匹配之后的子串 // 使用静态属性var pattern = /(g)oogle/;var str = 'This is google!';pattern.test(str); // 执行一下alert(RegExp.input); // This is google!alert(RegExp.leftContext); // This isalert(RegExp.rightContext); // !alert(RegExp.lastMatch); // googlealert(RegExp.lastParen); // galert(RegExp.multiline); // false Opera 不支持 input、lastMatch、lastParen 和 multiline 属性。IE 不支持 multiline 属性。所有的属性可以使用短名来操作。RegExp.input 可以改写成 RegExp['$_'],依次类推。但 RegExp.input 比较特殊,它还可以写成 RegExp.$_。 RegExp 对象的实例属性 属性 含义 global Boolean 值,表示 g 是否已设置 ignoreCase Boolean 值,表示 i 是否已设置 lastIndex 整数,代表下次匹配将从哪里字符位置开始 multiline Boolean 值,表示 m 是否已设置 Source 正则表达式的源字符串形式 // 使用实例属性var pattern = /google/ig;alert(pattern.global); // true,是否全局了alert(pattern.ignoreCase); // true,是否忽略大小写alert(pattern.multiline); // false,是否支持换行alert(pattern.lastIndex); // 0,下次的匹配位置alert(pattern.source); // google,正则表达式的源字符串var pattern = /google/g;var str = 'google google google';pattern.test(str); // google,匹配第一次alert(pattern.lastIndex); // 6,第二次匹配的位 以上基本没什么用。并且 lastIndex 在获取下次匹配位置上 IE 和其他浏览器有偏差 ,主要表现在非全局匹配上。lastIndex 还支持手动设置,直接赋值操作。 获取控制 正则表达式元字符是包含特殊含义的字符。它们有一些特殊功能,可以控制匹配模式的方式。反斜杠后的元字符将失去其特殊含义。 字符类:单个字符和数字 元字符/元符号 匹配情况 . 匹配除换行符外的任意字符 [a-z0-9] 匹配括号中的字符集中的任意字符 [^a-z0-9] 匹配任意不在括号中的字符集中的字符 \d 匹配数字 \D 匹配非数字,同[^0-9]相同 \w 匹配字母和数字及_ \W 匹配非字母和数字及_ 字符类:空白字符 元字符/元符号 匹配情况 \0 匹配 null 字符 \b 匹配空格字符 \f 匹配进纸字符 \n 匹配换行符 \r 匹配回车字符 \t 匹配制表符 \s 匹配空白字符、空格、制表符和换行符 \S 匹配非空白字符 字符类:锚字符 元字符/元符号 匹配情况 ^ 行首匹配 $ 行尾匹配 \A 只有匹配字符串开始处 \b 匹配单词边界,词在[]内时无效 \B 匹配非单词边界 \G 匹配当前搜索的开始位置 \Z 匹配字符串结束处或行尾 \z 只匹配字符串结束处 字符类:重复字符 元字符/元符号 匹配情况 x? 匹配 0 个或 1 个 x x 匹配 0 个或任意多个 x x+ 匹配至少一个 x (xyz)+ 匹配至少一个(xyz) x{m,n} 匹配最少 m 个、最多 n 个 x 字符类:替代字符 元字符/元符号 匹配情况 this where 字符类:记录字符 元字符/元符号 匹配情况 (string) 用于反向引用的分组 \1 或$1 匹配第一个分组中的内容 \2 或$2 匹配第二个分组中的内容 \3 或$3 匹配第三个分组中的内容 // 使用点元字符var pattern = /g..gle/; // .匹配一个任意字符var str = 'google';alert(pattern.test(str));// 重复匹配var pattern = /g.gle/; // .匹配 0 个一个或多个var str = 'google'; //,?,+,{n,m}alert(pattern.test(str));// 使用字符类匹配var pattern = /g[a-zA-Z_]gle/; // [a-z]表示任意个 a-z 中的字符var str = 'google';alert(pattern.test(str));var pattern = /g[^0-9]gle/; // [^0-9]表示任意个非 0-9 的字符var str = 'google';alert(pattern.test(str));var pattern = /[a-z][A-Z]+/; // [A-Z]+表示 A-Z 一次或多次var str = 'gOOGLE';alert(pattern.test(str));// 使用元符号匹配var pattern = /g\wgle/; // \w匹配任意多个所有字母数字_var str = 'google';alert(pattern.test(str));var pattern = /google\d/; // \d匹配任意多个数字var str = 'google444';alert(pattern.test(str));var pattern = /\D{7,}/; // \D{7,}匹配至少 7 个非数字var str = 'google8';alert(pattern.test(str));// 使用锚元字符匹配var pattern = /^google$/; // ^从开头匹配,$从结尾开始匹配var str = 'google';alert(pattern.test(str));var pattern = /goo\sgle/; // \s 可以匹配到空格var str = 'goo gle';alert(pattern.test(str));var pattern = /google\b/; // \b 可以匹配是否到了边界var str = 'google';alert(pattern.test(str));// 使用或模式匹配var pattern = /google|baidu|bing/; // 匹配三种其中一种字符串var str = 'google';alert(pattern.test(str));// 使用分组模式匹配var pattern = /(google){4,8}/; // 匹配分组里的字符串 4-8 次var str = 'googlegoogle';alert(pattern.test(str));var pattern = /8(.)8/; // 获取 8..8 之间的任意字符var str = 'This is 8google8';str.match(pattern);alert(RegExp.$1); // 得到第一个分组里的字符串内容var pattern = /8(.)8/;var str = 'This is 8google8';var result = str.replace(pattern,'<strong>$1</strong>'); // 得到替换的字符串输出document.write(result);var pattern = /(.)\s(.)/;var str = 'google baidu';var result = str.replace(pattern, '$2 $1'); // 将两个分组的值替换输出document.write(result); 贪婪 惰性 + +? ? ?? ? {n} {n}? {n,} {n,}? {n,m} {n,m}? // 关于贪婪和惰性var pattern = /[a-z]+?/; // ?号关闭了贪婪匹配,只替换了第一个var str = 'abcdefjhijklmnopqrstuvwxyz';var result = str.replace(pattern, 'xxx');alert(result);var pattern = /8(.+?)8/g; // 禁止了贪婪,开启的全局var str = 'This is 8google8, That is 8google8, There is 8google8';var result = str.replace(pattern,'<strong>$1</strong>');document.write(result);var pattern = /8([^8])8/g; // 另一种禁止贪婪var str = 'This is 8google8, That is 8google8, There is 8google8';var result = str.replace(pattern,'<strong>$1</strong>');document.write(result);// 使用 exec 返回数组var pattern = /^[a-z]+\s[0-9]{4}$/i;var str = 'google 2012';alert(pattern.exec(str)); // 返回整个字符串var pattern = /^[a-z]+/i; // 只匹配字母var str = 'google 2012';alert(pattern.exec(str)); // 返回 googlevar pattern = /^([a-z]+)\s([0-9]{4})$/i; // 使用分组var str = 'google 2012';alert(pattern.exec(str)[0]); // google 2012alert(pattern.exec(str)[1]); // googlealert(pattern.exec(str)[2]); // 2012// 捕获性分组和非捕获性分组var pattern = /(\d+)([a-z])/; // 捕获性分组var str = '123abc';alert(pattern.exec(str));var pattern = /(\d+)(?:[a-z])/; // 非捕获性分组var str = '123abc';alert(pattern.exec(str));// 使用分组嵌套var pattern = /(A?(B?(C?)))/; // 从外往内获取var str = 'ABC';alert(pattern.exec(str));// 使用前瞻捕获var pattern = /(goo(?=gle))/; // goo 后面必须跟着 gle 才能捕获var str = 'google';alert(pattern.exec(str));// 使用特殊字符匹配var pattern = /\.\[\/b\]/; // 特殊字符,用\符号转义即可var str = '.[/b]';alert(pattern.test(str));// 使用换行模式var pattern = /^\d+/mg; // 启用了换行模式var str = '1.baidu\n2.google\n3.bing';var result = str.replace(pattern, '');alert(result); 常用的正则 检查邮政编码 var pattern = /[1-9][0-9]{5}/; // 共 6 位数字,第一位不能为 0var str = '224000';alert(pattern.test(str)); 检查文件压缩包 var pattern = /[\w]+\.zip|rar|gz/; // \w 表示所有数字和字母加下划线var str = '123.zip'; // \.表示匹配.,后面是一个选择alert(pattern.test(str)); 删除多余空格 var pattern = /\s/g; // g 必须全局,才能全部匹配var str = '111 222 333';var result = str.replace(pattern,''); // 把空格匹配成无空格alert(result); 删除首尾空格 var pattern = /^\s+/; // 强制首var str = ' goo gle ';var result = str.replace(pattern, '');pattern = /\s+$/; // 强制尾result = result.replace(pattern, '');alert('|' + result + '|');var pattern = /^\s(.+?)\s$/; // 使用了非贪婪捕获var str = ' google ';alert('|' + pattern.exec(str)[1] + '|');var pattern = /^\s(.+?)\s$/;var str = ' google ';alert('|' + str.replace(pattern, '$1') + '|'); // 使用了分组获取 简单的电子邮件验证 var pattern = /^([a-zA-Z0-9_\.\-]+)@([a-zA-Z0-9_\.\-]+)\.([a-zA-Z]{2,4})$/;var str = 'yc60.com@gmail.com';alert(pattern.test(str));var pattern = /^([\w\.\-]+)@([\w\.\-]+)\.([\w]{2,4})$/;var str = 'yc60.com@gmail.com';alert(pattern.test(str)); 3、Function类型 在 ECMAScript 中,Function(函数)类型实际上是对象。每个函数都是 Function 类型的实例,而且都与其他引用类型一样具有属性和方法。由于函数是对象,因此函数名实际上也是一个指向函数对象的指针。 函数的声明方式 普通的函数声明 function box(num1, num2) {return num1+ num2;} 使用变量初始化函数 var box= function(num1, num2) {return num1 + num2;}; 使用 Function 构造函数 var box= new Function('num1', 'num2' ,'return num1 + num2'); 第三种方式我们不推荐,因为这种语法会导致解析两次代码(第一次解析常规 ECMAScript 代码,第二次是解析传入构造函数中的字符串),从而影响性能。但我们可以通过这种语法来理解"函数是对象,函数名是指针"的概念。 作为值的函数 ECMAScript 中的函数名本身就是变量,所以函数也可以作为值来使用。也就是说,不仅可以像传递参数一样把一个函数传递给另一个函数,而且可以将一个函数作为另一个函数的结果返回。 function box(sumFunction, num) {return sumFunction(num); // someFunction}function sum(num) {return num + 10;}var result = box(sum, 10); // 传递函数到另一个函数里 函数内部属性 在函数内部,有两个特殊的对象:arguments 和 this。arguments 是一个类数组对象,包含着传入函数中的所有参数,主要用途是保存函数参数。但这个对象还有一个名叫 callee 的属性,该属性是一个指针,指向拥有这个 arguments 对象的函数。 function box(num) {if (num <= 1) {return 1;} else {return num box(num-1); // 一个简单的的递归} } 对于阶乘函数一般要用到递归算法,所以函数内部一定会调用自身;如果函数名不改变是没有问题的,但一旦改变函数名,内部的自身调用需要逐一修改。为了解决这个问题,我们可以使用 arguments.callee 来代替。 function box(num) {if (num <= 1) {return 1;} else {return num arguments.callee(num-1); // 使用 callee 来执行自身} } 函数内部另一个特殊对象是 this,其行为与 Java 和 C中的 this 大致相似。换句话说 ,this 引用的是函数据以执行操作的对象,或者说函数调用语句所处的那个作用域。当在全局作用域中调用函数时,this 对象引用的就是 window。 // 便于理解的改写例子window.color = '红色的'; // 全局的,或者 var color = '红色的';也行alert(this.color); // 打印全局的 colorvar box = {color : '蓝色的', // 局部的 colorsayColor : function () {alert(this.color); // 此时的 this 只能 box 里的 color} };box.sayColor(); // 打印局部的 coloralert(this.color); // 还是全局的// 引用教材的原版例子window.color = '红色的'; // 或者 var color = '红色的';也行var box = {color : '蓝色的'};function sayColor() {alert(this.color); // 这里第一次在外面,第二次在 box 里面}getColor();box.sayColor = sayColor; // 把函数复制到 box 对象里,成为了方法box.sayColor(); 函数属性和方法 ECMAScript 中的函数是对象,因此函数也有属性和方法。每个函数都包含两个属性 :length 和 prototype。其中,length 属性表示函数希望接收的命名参数的个数。 function box(name, age) {alert(name + age);}alert(box.length); // 2 对于 prototype 属性,它是保存所有实例方法的真正所在,也就是原型。这个属性 ,我们将在面向对象一章详细介绍。而 prototype 下有两个方法:apply()和 call(),每个函数都包含这两个非继承而来的方法。这两个方法的用途都在特定的作用域中调用函数,实际上等于设置函数体内 this 对象的值。 function box(num1, num2) {return num1 + num2; // 原函数}function sayBox(num1, num2) {return box.apply(this, [num1, num2]); // this 表示作用域,这里是 window} // []表示 box 所需要的参数function sayBox2(num1, num2) {return box.apply(this, arguments); // arguments 对象表示 box 所需要的参数}alert(sayBox(10,10)); // 20alert(sayBox2(10,10)); // 20 call()方法于 apply()方法相同,他们的区别仅仅在于接收参数的方式不同。对于 call()方法而言,第一个参数是作用域,没有变化,变化只是其余的参数都是直接传递给函数的。 function box(num1, num2) {return num1 + num2;}function callBox(num1, num2) {return box.call(this, num1, num2); // 和 apply 区别在于后面的传参}alert(callBox(10,10)); 事实上,传递参数并不是 apply()和 call()方法真正的用武之地;它们经常使用的地方是能够扩展函数赖以运行的作用域。 var color = '红色的'; // 或者 window.color = '红色的';也行var box = {color : '蓝色的'};function sayColor() {alert(this.color);}sayColor(); // 作用域在 windowsayColor.call(this); // 作用域在 windowsayColor.call(window); // 作用域在 windowsayColor.call(box); // 作用域在 box,对象冒充 这个例子是之前作用域理解的例子修改而成,我们可以发现当我们使用 call(box)方法的时候,sayColor()方法的运行环境已经变成了 box 对象里了。 使用 call()或者 apply()来扩充作用域的最大好处,就是对象不需要与方法发生任何耦合关系(耦合,就是互相关联的意思,扩展和维护会发生连锁反应)。也就是说,box 对象和 sayColor()方法之间不会有多余的关联操作,比如 box.sayColor = sayColor;。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gongxifacai_believe/article/details/108286196。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-24 13:01:25
529
转载
转载文章
...示:“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
283
转载
JQuery插件下载
...款名为“电影开场字幕文字变换特效”的jQuery与CSS3结合的插件,专门设计用于在网页中模拟电影开场时的经典动态字幕效果,为用户提供沉浸式和富有创意的文本展示方式。它充分利用了CSS3的animation属性,以平滑且高性能的方式实现丰富的动画过渡效果,如文字的模糊放大直至消失等。同时,该插件还集成了jQuery的lettering.js库,使得对单个字母或单词级别的动画控制成为可能,从而让文字变换更加细腻和个性化。通过此插件,开发者无需从零开始编写复杂的动画脚本,即可快速构建出仿佛从银幕缓缓推出的立体字幕,带来强烈的视觉冲击力和艺术表现力。无论是网站引导页、产品介绍还是内容预告,都能凭借这一特效显著提升用户体验,营造浓厚的叙事氛围。只需简单集成并配置,即可在现代浏览器上呈现令人印象深刻的电影级字幕动画效果。 点我下载 文件大小:40.24 KB 您将下载一个JQuery插件资源包,该资源包内部文件的目录结构如下: 本网站提供JQuery插件下载功能,旨在帮助广大用户在工作学习中提升效率、节约时间。 本网站的下载内容来自于互联网。如您发现任何侵犯您权益的内容,请立即告知我们,我们将迅速响应并删除相关内容。 免责声明:站内所有资源仅供个人学习研究及参考之用,严禁将这些资源应用于商业场景。 若擅自商用导致的一切后果,由使用者承担责任。
2023-01-04 12:32:06
486
本站
CSS
...可以增大或减小文本内字母间的距离,从而影响整体排版效果及阅读体验。在文章提到的例子中,使用letter-spacing: 2px; 将会使导航条中的文字每个字母间隔扩大2个像素的距离。
2023-11-07 18:25:18
438
码农
HTML
...;p>这是一段文字。</p> <img src="图片地址"> </body> </html> 在HTML代码中,<!DOCTYPE html>是声明文件类型的声明,<html>元素是包括所有HTML代码的顶层元素。<head>元素包括文档的metadata,如标题和脚本。<title>元素设定了文档的标题,该元素必需包括在head元素中。<body>元素设定了HTML包括的文本内容,如文字、图片、链接等。<h1>元素是一种标题元素,h1~h6共6种级别,用于设定不同级别的标题。<p>元素设定文本段落,可以包括文字、图片、链接等。 在编写HTML代码时,需要遵守语法规则,如元素必需成对出现,元素名要小写,属性值要用引号包括等。同时,也需要了解常用元素的属性和使用方法。例如,<img>元素用于显示图片,需要声明图片的地址和大小等属性;<a>元素用于创建链接,需要声明链接的地址和文本等属性。 在学习HTML代码时,可以参考相关教程和文档,也可以参考其他网站的源代码,学习其结构和语法。同时,还需要不断实践,编写代码才能够更好地掌握方法和规则。
2023-05-02 11:53:31
469
码农
PHP
...现用户名那块儿应该是小写字母,可咱们的代码里却给写成了大写。因此,我们只需要将用户名字段改为小写即可解决问题: sql SELECT FROM users WHERE username = 'admin' AND password = 'password' 2. 检查数据库连接 除了检查SQL查询语句之外,我们还需要检查数据库连接是否正常。如果数据库连接这环节出了岔子,就算你的SQL查询语句写得再完美无瑕,照样可能引发SQLQueryException这个小恶魔出来捣乱。 例如,假设我们的数据库服务器无法访问,那么我们在执行SQL查询语句时就会遇到SQLQueryException。要搞定这个问题,我们可以试着重启一下数据库服务器,或者瞧瞧网络连接是否一切正常。就像电脑卡顿时咱们会先选择重启一样,数据库服务器有时候也需要“刷新”一下自己。另外,也别忘了看看是不是网络这家伙在关键时刻掉链子了~ bash sudo service mysql restart 3. 使用try-catch结构捕获异常 如果我们不确定SQL查询语句是否有问题,或者不确定数据库连接是否正常,那么我们可以使用try-catch结构来捕获SQLQueryException。这样一来,当我们逮到异常情况时,就能做出相应的应对措施,而不是让程序“砰”地一下崩溃掉。 例如,我们可以使用以下代码来捕获SQLQueryException: php try { $conn = new PDO("mysql:host=localhost;dbname=myDB;charset=utf8", "username", "password"); $stmt = $conn->prepare("SELECT FROM users WHERE username=:username AND password=:password"); $stmt->execute(array( ":username" => $username, ":password" => $password )); } catch (PDOException $e) { echo "Error!: " . $e->getMessage(); } 在这个例子中,如果我们在执行SQL查询语句时遇到了SQLQueryException,那么程序就会跳转到catch语句中,并打印出错误信息。这样,我们就可以及时发现并处理SQLQueryException了。 四、总结 通过以上介绍,我们可以看出SQLQueryException是一种比较常见的数据库查询错误。为了更顺溜地搞定这个问题,咱们得先瞧瞧SQL查询语句是不是敲对了,再瞅瞅数据库连接是否顺畅。还有啊,别忘了用try-catch这个小法宝来兜住可能出现的异常情况,这样就万无一失啦!只要咱们把这些小技巧都掌握熟练了,就能轻松搞掂SQLQueryException,让它再也不能困扰咱们啦!
2023-05-04 22:50:29
88
月影清风-t
ReactJS
...,DOM事件通常采用小写和横杠分隔的命名方式(如onclick),但在ReactJS中,事件绑定则需要使用驼峰命名(如onClick)。这是一个新手很容易踩到的坑。 jsx // 错误示例: Click me // 正确示例: Click me 在上述例子中,onclick是无效的事件绑定方式,正确的做法应为onClick。 3. 错误二 忘记bind方法 在React类组件中,如果直接在事件处理函数中引用this关键字,可能会出现undefined的问题,这是因为事件处理函数默认没有绑定到当前组件实例。为此,我们需要在构造函数中进行手动绑定,或者使用箭头函数。 jsx class MyComponent extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); // 手动绑定 } handleClick() { console.log('Clicked:', this.props.message); } render() { return Click me; } } // 或者使用箭头函数实现自动绑定 class MyComponent extends React.Component { handleClick = () => { console.log('Clicked:', this.props.message); } render() { return Click me; } } 在这个案例中,如果不进行绑定或使用箭头函数,this在handleClick函数内部将不会指向组件实例,从而无法访问组件的状态和属性。 4. 错误三 动态事件绑定 在某些场景下,我们可能需要根据条件动态地绑定不同的事件处理函数。这时候,假如我们在渲染的过程中直接在里头定义函数,就像每次做饭都重新买个锅一样,会导致每一次渲染的时候,都会生成一个新的函数实例。这就像是你本来只是想热个剩菜,结果却触发了整个厨房的重新运作,完全是没必要的重新渲染过程。 jsx // 错误示例: render() { const handleClick = () => { console.log('Clicked'); }; return Click me; } // 正确示例: class MyComponent extends React.Component { handleClick = () => { console.log('Clicked'); } render() { let clickHandler; if (this.props.shouldLog) { clickHandler = this.handleClick; } else { clickHandler = () => {}; // 空函数防止不必要的调用 } return Click me; } } 在正确示例中,我们提前定义好事件处理函数,并在render方法中根据条件选择合适的处理函数进行绑定,避免了每次渲染都创建新函数的情况。 5. 结语 面对ReactJS中的事件绑定问题,关键在于深入理解其工作原理并遵循最佳实践。真功夫都是从实践中磨出来的,只有不断摔跤、摸爬滚打、学习钻研,解决各种实际问题,我们才能真正把ReactJS这个牛X的前端框架玩得溜起来。希望你在ReactJS的世界里探险时,能够巧妙地避开那些常让人跌跤的事件绑定坑洼,亲手打造出更加强劲又稳当的组件代码,让编程之路更加顺风顺水。下次当你再次面对事件绑定问题时,相信你会带着更坚定的信心和更深的理解去应对它!
2023-08-11 19:00:01
131
幽谷听泉
Tesseract
... 创建一个简单的英文单词库 english_words = set(words.words()) 对识别结果进行过滤,只保留英文单词 filtered_text = ' '.join([word for word in improved_text.split() if word.lower() in english_words]) 5. 针对异常情况的处理 当Tesseract抛出异常时,应遵循常规的异常处理原则。例如,捕获Image.open()可能导致的IOError,或者pytesseract.image_to_string()可能引发的RuntimeError等。 python try: img = Image.open('nonexistent_image.png') text = pytesseract.image_to_string(img) except IOError: print("无法打开图片文件!") except RuntimeError as e: print(f"运行时错误:{e}") 总结来说,处理Tesseract的错误和异常情况是一项涉及多个层面的工作,包括理解其内在局限性、优化输入图像、调整识别参数、结果后处理以及有效应对异常。在这个过程中,耐心调试、持续学习和实践反思都是非常关键的。让我们用人类特有的情感化思考和主观能动性去驾驭这一强大的工具,让Tesseract更好地服务于我们的需求吧!
2023-07-17 18:52:17
85
海阔天空
JSON
...析器通常会自动处理大小写问题,将所有键转换为统一的形式,通常是小写,这样可以确保在处理来自不同来源的数据时不会因为大小写不一致而导致错误。 大小写不敏感 , 指在处理数据时,不区分字母的大小写。在JSON解析中,这意味着解析器会将所有的键名统一转换为同一种形式,如全部转为小写。这种特性使得开发者在处理不同来源的数据时,不必担心字段名称的大小写差异,从而简化了数据处理逻辑,提高了代码的健壮性和可维护性。 微服务架构 , 指一种软件架构设计模式,其中应用程序被分解为一组小型独立的服务,每个服务运行在其自己的进程中,并通过轻量级通信机制(通常是HTTP API)相互通信。这种架构允许每个服务独立部署、扩展和维护,特别适合于大型复杂的应用场景。在文章中提到,由于不同服务可能由不同团队负责,字段命名风格各异,利用JSON解析器的大小写不敏感特性可以有效解决由此引发的问题。
2025-01-13 16:02:04
18
诗和远方
Java
...格? 半角空格,也叫英文空格,是一种窄字符,通常出现在英文文本中。它在Unicode编码中的位置是U+0020。在视觉上,半角空格占用的空间较小,适合在英文文本中使用。 3. 全角空格与半角空格在Java中的处理 3.1 如何区分全角空格与半角空格? 在Java中,我们可以利用Character类提供的方法来判断一个字符是否为全角空格或半角空格。例如: java public static boolean isFullWidthSpace(char c) { return c == '\u3000'; // 全角空格 } public static boolean isHalfWidthSpace(char c) { return c == ' '; // 半角空格 } 这里我们定义了两个方法isFullWidthSpace和isHalfWidthSpace,分别用于判断一个字符是否为全角空格或半角空格。这个方法虽然简单,但在实际应用中非常实用。 3.2 如何替换全角空格与半角空格? 有时候我们需要将文本中的全角空格替换为半角空格,或者反之。这时我们可以使用String类的replace或replaceAll方法。下面是一个具体的例子: java public class ReplaceSpaces { public static void main(String[] args) { String text = "这是一段包含全角空格的文字\u3000"; // 替换全角空格为半角空格 String result = text.replace('\u3000', ' '); System.out.println("替换后的结果:" + result); // 反之,替换半角空格为全角空格 String originalText = "This is a sentence with half-width spaces."; String fullWidthResult = originalText.replace(' ', '\u3000'); System.out.println("全角空格替换结果:" + fullWidthResult); } } 在这个例子中,我们首先将一段包含全角空格的文本中的全角空格替换为半角空格,然后反向操作,将一段英文文本中的半角空格替换为全角空格。用这种方法,我们就能够随心所欲地调整文本里的空格了,想怎么玩就怎么玩。 4. 实际应用案例 在实际开发中,我们经常会遇到需要处理各种复杂文本的情况。比如说,有时候用户会不小心输入全角空格,这玩意儿能直接让我们的程序翻车。这时候,我们就得对输入做一些处理,把那些全角空格换成半角空格,这样程序才能好好地工作。 假设我们正在开发一个文本编辑器,用户可以输入任意文本。为了确保文本不出错,我们在保存前得把全角空格换成半角空格。下面是实现这一功能的代码示例: java public class TextEditor { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入一段文本:"); String input = scanner.nextLine(); // 将全角空格替换为半角空格 String correctedInput = input.replace('\u3000', ' '); // 保存修正后的文本 saveText(correctedInput); System.out.println("文本已保存!"); } private static void saveText(String text) { // 这里可以添加保存文本的逻辑,例如保存到文件等 System.out.println("保存的内容:" + text); } } 在这个例子中,我们创建了一个简单的文本编辑器,用户可以输入一段文本。在保存文本之前,我们调用replace方法将其中的全角空格替换为半角空格,从而确保文本的正确性。这样一来,就算大伙儿一不小心打了个全角空格进来,我们的程序也能妥妥地应对,不会出岔子。 5. 总结 全角空格与半角空格在Java编程中是一个不容忽视的小细节。通过对它们的正确理解和处理,我们可以避免很多潜在的问题。希望大家在阅读本文后,能够掌握如何在Java中区分和处理这两种空格,从而在实际开发中更加得心应手。 最后,我想说的是,编程不仅是技术的较量,更是对细节的把握。每一个看似微不足道的小问题,都可能成为影响整个项目的关键。因此,我们要时刻保持警惕,不断学习和积累经验,才能成为一名优秀的程序员。希望我的分享能对你有所帮助,也欢迎你在评论区留言交流,让我们一起进步!
2024-12-22 15:53:15
89
风轻云淡
Tesseract
...景:一份文档中混杂着英文、中文和日文等不同语言的文字。对于Tesseract这货来说,识别单独一种语言时,表现那可是相当赞的。不过呢,一旦遇到这种“乱炖”式的多种语言混合场景,它可能就有点犯迷糊了。其实呢,Tesseract这家伙在训练的时候,专门是学了一门针对特定语言的“独门秘籍”。不过呢,一旦遇到一张图片里混杂了好几种语言的情况,它可能就有点犯晕了,因为各种语言的特点相互交错,让它傻傻分不清楚。 3. Tesseract处理多语言混合文本的实战演示 --- python import pytesseract from PIL import Image 假设我们有一个包含英文、中文和日文的混合文本图片文件 'mixed_languages.png' img = Image.open('mixed_languages.png') 默认情况下,Tesseract会尝试使用其已训练的语言模型进行识别 default_result = pytesseract.image_to_string(img) 输出结果可能会出现混淆,因为Tesseract默认只识别一种语言 为了改进识别效果,我们可以明确指定要识别的所有语言 multi_lang_result = pytesseract.image_to_string(img, lang='eng+chi_sim+jpn') 这样,Tesseract将会尝试结合三种语言模型来解析图片中的文本,理论上可以提高混合文本的识别准确率 4. 解决策略与思考过程 --- 尽管上述方法可以在一定程度上缓解多语言混合文本的识别问题,但并不总是万无一失。Tesseract在识别混合文本时仍面临如下挑战: - 语言边界检测:Tesseract在没有明确语境的情况下难以判断哪部分文字属于哪种语言。 - 语言权重分配:即使指定了多种语言,Tesseract也可能无法准确地为不同区域分配合适的语言权重。 为此,我们可以尝试以下策略: - 预处理:利用图像分割技术,根据字体、颜色、位置等因素对不同语言区域进行划分,然后分别用对应的语言模型进行识别。 - 调整配置:Tesseract支持一些高级配置选项,如--oem和--psm,通过合理设置这些参数,有可能改善识别性能。 - 自定义训练:如果条件允许,还可以针对特定的混合文本类型,收集数据并训练自定义的混合语言模型。 5. 结论与探讨 --- 虽然Tesseract在处理多语言混合文本时存在挑战,但我们不能否认其在解决复杂OCR问题上的巨大潜力。当你真正摸透了它的运行门道,再灵活耍弄各种小策略,咱们就能一步步地把它在混合文本识别上的表现调校得更上一层楼。当然,这个过程不仅需要耐心调试,更需人类的智慧与创造力。每一次对技术边界的探索都是对人类理解和掌握世界的一次深化,让我们一起期待未来的Tesseract能够更好地服务于我们的多元文化环境吧! 以上所述仅为基本思路,实际应用中还需结合具体场景进行细致分析与实验验证。说真的,机器学习这片领域就像一个充满无尽奇妙的迷宫乐园,我们得揣着满满的好奇心和满腔热情,去尝试每一条可能的道路,才能真正找到那个专属于自己的、最完美的解决方案。
2023-03-07 23:14:16
136
人生如戏
Tesseract
...要能清晰地分辨出每个字母的形状和细节,这样才能准确无误地认出它们。不过呢,如果图片里的字边边糊糊的,Tesseract 就抓不住那些细节了,结果就是它可能会认错字,甚至压根儿认不出来。 3. 常见的解决方案 那么,我们应该如何应对这种问题呢?这里有几个常见的方法,我们可以尝试一下: 3.1 图像预处理 3.1.1 二值化 首先,我们可以对图像进行二值化处理。这就像给图像穿上一件黑白的外衣,使得图像中的文本更加突出。这样,Tesseract就能更容易地识别出文本的轮廓。 python import cv2 import numpy as np 读取图像 image = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE) 二值化处理 _, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) 保存结果 cv2.imwrite('binary_example.jpg', binary_image) 3.1.2 锐化 其次,我们可以使用图像锐化技术来增强图像的边缘。这就像给图像打了一剂强心针,让它看起来更加清晰。 python 使用自定义核进行锐化 kernel = np.array([[0, -1, 0], [-1, 5,-1], [0, -1, 0]], dtype=np.float32) sharpened_image = cv2.filter2D(binary_image, -1, kernel) 保存结果 cv2.imwrite('sharpened_example.jpg', sharpened_image) 3.2 调整Tesseract参数 除了图像预处理之外,我们还可以通过调整Tesseract的参数来提高识别精度。Tesseract提供了许多参数,我们可以根据实际情况进行调整。 3.2.1 设置Page Segmentation Mode Tesseract的Page Segmentation Mode(PSM)参数可以帮助我们更好地控制文本区域的分割方式。例如,如果我们知道图像中只有一行文本,可以设置为PSM_SINGLE_LINE,这样Tesseract就会更专注于这一行文本的识别。 python import pytesseract 设置PSM参数 custom_config = r'--psm 6' text = pytesseract.image_to_string(sharpened_image, config=custom_config) print(text) 3.2.2 提高字符分割精度 另一个参数是Char Whitespace,它可以帮助我们更好地控制字符之间的间距。要是文本行与行之间的距离比较大,你可以把这数值调大一点。这样一来,Tesseract这个工具就能更轻松地分辨出每个字母了。 python 提高字符分割精度 custom_config = r'--oem 1 --psm 6 -c tessedit_char_whitesp=1' text = pytesseract.image_to_string(sharpened_image, config=custom_config) print(text) 4. 实战案例 接下来,让我们来看一个实战案例。假设我们有一张边缘模糊的文本图像,我们需要使用Tesseract来进行识别。 4.1 图像预处理 首先,我们对图像进行二值化和锐化处理: python import cv2 import numpy as np 读取图像 image = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE) 二值化处理 _, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) 使用自定义核进行锐化 kernel = np.array([[0, -1, 0], [-1, 5,-1], [0, -1, 0]], dtype=np.float32) sharpened_image = cv2.filter2D(binary_image, -1, kernel) 保存结果 cv2.imwrite('sharpened_example.jpg', sharpened_image) 4.2 调整Tesseract参数 然后,我们使用Tesseract进行识别,并设置一些参数来提高识别精度: python import pytesseract 设置PSM参数 custom_config = r'--psm 6' text = pytesseract.image_to_string(sharpened_image, config=custom_config) print(text) 4.3 结果分析 经过上述处理,我们得到了较为清晰的图像,并且识别结果也更加准确。当然,实际效果可能会因图像质量的不同而有所差异,但至少我们已经尽力了! 5. 总结 总之,面对文本边缘模糊的问题,我们可以通过图像预处理和调整Tesseract参数来提高识别精度。虽然这招不是啥灵丹妙药,但在很多麻烦事儿上,它已经挺管用了。希望大家在使用Tesseract时能够多尝试不同的方法,找到最适合自己的方案。
2024-12-25 16:09:16
65
飞鸟与鱼
CSS
...中会引发问题。不同于英文标点,中文标点通常具有更强的内联性,例如全角句号、逗号等不会出现在单词或句子的尾部,而是紧贴前一个字符。此外,中文段落间的换行规则也与英文不同,新段落不直接跟在上一段文字后面,而是需要保持一定的缩进距离。 html 这是一段中文文本,结尾的句号应该紧贴前一个字。 这是新的一段,注意它与上一段之间的间距。 2. CSS中的默认排版行为 在默认情况下,浏览器根据W3C规范对中文标点进行处理,但在某些场景下,如自定义字体、行高、字间距等因素可能会影响标点符号的正常排布。 css / 默认CSS / body { font-family: '宋体', sans-serif; } / 这种情况下标点符号一般能正确显示,但如果更换其他非中文字体,可能出现标点位置异常 / 3. 解决方案一 调整字间距 为了解决标点过于紧凑或分散的问题,我们可以利用CSS的letter-spacing属性调整字间距,确保标点符号与汉字间有合适的间距。 css p { letter-spacing: normal; / 或者设置具体像素值,如0.1em / } 4. 解决方案二 使用white-space属性 针对中文段落换行问题,可以运用white-space属性。例如,使用pre-wrap可保留文本中的换行符并允许自动换行。 css p { white-space: pre-wrap; text-indent: 2em; / 设置首行缩进以符合中文段落排版习惯 / } 5. 解决方案三 针对特定标点符号的定位 对于个别特殊的标点符号,还可以通过伪元素结合margin或padding实现精准定位。 css p::after { content: "。"; / 添加一个全角句号 / margin-left: -0.1em; / 微调标点符号的位置 / } 6. 思考与探讨 虽然以上方法能够有效改善中文标点符号的排版效果,但实际应用中还需结合具体场景灵活调整。同时,随着CSS3及Web typography的发展,诸如text-align-last、line-break等高级特性也为更精细的排版提供了可能。因此,在优化中文排版体验的过程中,我们需要不断学习和探索,让CSS更好地服务于我们的多语言网页设计。 总结来说,面对CSS中的中文标点符号排版问题,关键在于理解其内在规律,借助CSS属性工具箱,辅以细致入微的调试与观察,才能达到理想的效果。在这个过程中,作为开发者大伙儿,咱们得把每一个细节都当作是手中的艺术品在精心打磨,得用真心去感知、去打造那种让人读起来超爽的体验,就像工匠对自己的作品精雕细琢一样。
2023-06-22 11:49:35
441
彩虹之上_
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
unzip archive.zip
- 解压ZIP格式的压缩文件。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"