前端技术
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
[Java开发者个人技能展示HTML简历 ]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...ype="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
113
转载
转载文章
...的飞速发展,现代软件开发工程师所需掌握的技术栈正在不断拓宽和深化。 例如,对于服务端开发者而言,在熟悉了Java基础、数据库操作(如MySQL)及Spring框架后,进一步了解微服务架构及其相关技术(如Docker、Kubernetes)已成为行业趋势。同时,云原生应用开发也是目前热门的方向,学习和掌握阿里云、AWS或Google Cloud等主流云服务提供商的解决方案和技术将大大提升个人竞争力。 而对于前端开发者来说,除了HTML、CSS、JavaScript的基本功外,Vue.js、React或Angular等现代化前端框架的应用以及TypeScript等强类型语言的使用正逐渐成为标配。此外,随着WebAssembly的兴起,对底层性能优化的需求也在增加,理解浏览器工作原理以及如何运用Web Worker、Service Worker提升用户体验变得愈发重要。 与此同时,数据结构与算法始终是程序员的核心素养之一,无论面试还是实际工作中,扎实的算法基础都能使开发者在解决问题时更加游刃有余。因此,即使在快速掌握实战技能的同时,也不能忽视理论知识的学习,包括但不限于《算法导论》、LeetCode等经典资源。 总之,在持续探索编程世界的过程中,保持与时俱进、关注最新技术动态,并结合自身兴趣和发展方向深入学习,才是实现从初级到高级甚至专家级程序员蜕变的关键所在。
2023-07-02 23:59:06
60
转载
转载文章
...;!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><em>强调文本</em><br><strong>加粗文本</strong><br><dfn>定义项目</dfn><br><code>一段电脑代码</code><br><samp>计算机样本</samp><br><kbd>键盘输入</kbd><br><var>变量</var></body></html 2、HTML <audio> 标签 <audio> 标签是 HTML5 提供的用来播放音频文件的。 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><audio controls><source src="/statics/demosource/horse.ogg" ><source src="/statics/demosource/horse.mp3" >您的浏览器不支持 audio 元素。</audio></body></html> 3、HTML <area> 标签 <area> 标签可以在图像上划分区域,这些区域是可以点击的,并且对应不同的操作。 <!DOCTYPE html><html><head><meta charset="utf-8"><title>W3Cschool(w3cschool.cn)</title></head><body><p>点击太阳或其他行星,注意变化:</p><img src="/statics/images/course/planets.gif" width="145" height="126" alt="Planets" usemap="planetmap"><map name="planetmap"><area shape="rect" coords="0,0,82,126" target="_blank" alt="Sun" href="/statics/images/course/sun.gif"><area shape="circle" coords="90,58,3" target="_blank" alt="Mercury" href="/statics/images/course/merglobe.gif"><area shape="circle" coords="124,58,8" target="_blank" alt="Venus" href="/statics/images/course/venglobe.gif"></map></body></html> 4、HTML <select> 标签定义及使用说明 <select> 元素用来创建下拉列表。 <!DOCTYPE html><html><head><meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><select><option value="volvo" style="display:none">Volvo</option><option value="saab">Saab</option><option value="opel">Opel</option><option value="audi">Audi</option></select></body></html> 5、HTML <style> 标签 <style> 标签包含了 HTML 文档的样式详细,在默认情况下,在该元素内写入的样式指令将被认为是CSS。 <!DOCTYPE html><html><head><meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title><style type="text/css">h1 {color:red;}p {color:blue;}</style></head><body><h1>这是一个标题</h1><p>这是一个段落。</p></body></html> 7、HTML <sub> 标签 包含在 <sub> 标签和其结束标签 </sub> 中的内容会以正常内容的一半的高度显示在下方,而且通常较小,请参见下述例子: <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool教程(w3cschool.cn)</title> </head><body><p>这个文本包含 <sub>下标</sub>文本。</p><p>这个文本包含 <sup>上标</sup> 文本。</p></body></html> 8、HTML <summary> 标签 <summary> 标签元素作为一个<datails>元素的标题,该标题可以包含详细的信息,但是默认情况下不显示,需要单击才能显示详细信息,请参考下述示 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><details><summary>Copyright 1999-2011.</summary><p> - by Refsnes Data. All Rights Reserved.</p><p>All content and graphics on this web site are the property of the company Refsnes Data.</p></details><p><b>注意:</b>目前只有 Chrome 和 Safari 6 支持 summary 标签。</p></body></html> 9、HTML <table> 标签 <table> 标签用来定义 HTML 表格,一个简单的 HTML 表格应该包括两行两列,如下述示例所示: <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool教程(w3cschool.cn)</title> </head><body><table border="1"><tr><th>Month</th><th>Savings</th></tr><tr><td>January</td><td>$100</td></tr><tr><td>February</td><td>$80</td></tr></table></body></html> 10、HTML <textarea> 标签 <textarea> 标签表示多行纯文本编辑控件,用户可在其文本区域中写入文本,请参考下述示例: <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool 在线教程(w3cschool.cn)</title> </head><body><textarea rows="10" cols="30">我是一个文本框。</textarea></body></html> 11、HTML <tt> 标签 - HTML5 不支持 <tt> 标签用来改变字体样式,使标签中的文本显示为打字机文本,请参考下述例子: <!DOCTYPE html><html><body><p>This text is normal.</p><p><tt>This text is teletype text.</tt></p></body></html> 12、HTML <u> 标签 <u> 标签可以用来对标签内的文本实现下划线样式,请参考下述示例: <!DOCTYPE html><html><body><p>This is a <u>parragraph</u>.</p></body></html> 13、HTML <ul> 标签 <ul> 标签表示HTML页面中项目的无序列表,一般会以项目符号列表呈现,请参考下述例子: <!DOCTYPE html><html><head><meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><h4>无序列表:</h4><ul><li>咖啡</li><li>茶</li><li>牛奶</li></ul></body></html> 14、HTML <video> 标签 <video> 标签可以将视频内容嵌入到HTML文档中,请参考下述示例: <!DOCTYPE html><html><body><video width="320" height="240" controls><source src="/statics/demosource/movie.mp4" type="video/mp4"><source src="/statics/demosource/movie.ogg" type="video/ogg">您的浏览器不支持 HTML5 video 标签。</video></body></html> 15、HTML <ol> 标签 <ol> 标签在 HTML 中表示有序列表,是 ordered lists 的缩写。您可以自定义有序列表的初始序号,请参考下面的实例: <!DOCTYPE html><html><head><meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><ol><li>咖啡</li><li>茶</li><li>牛奶</li></ol><ol start="50"><li>咖啡</li><li>茶</li><li>牛奶</li></ol></body></html> 16、HTML <noframes> 标签HTML5不支持该标签 <noframes> 标签用于支持不支持 <frame> 元素的浏览器,请参考下面的示例: <html><head><meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><frameset cols="25%,50%,25%"><frame src="/statics/demosource/frame_a.htm"><frame src="/statics/demosource/frame_b.htm"><frame src="/statics/demosource/frame_c.htm"><noframes>抱歉,您的浏览器不支持 frame 属性!</noframes></frameset></html> 17、HTML <hr> 标签 <hr> 标签表示段落级元素之间的主题划分。例如,在下面的实例中我们对具有主题变化的内容使用了 <hr> 标签: <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><h1>HTML</h1><p>HTML 是用于描述 web 页面的一种语言。</p><hr><h1>CSS</h1><p>CSS 定义如何显示 HTML 元素。</p></body></html> 18、HTML <h1> - <h6> 标签 <h1> - <h6> 标签用来定义 HTML 标题,表示了 HTML 网页中六个级别的标题。您可以通过下面的这个实例来看看每个级别的标题有什么区别: <!DOCTYPE html><html><head><meta charset="utf-8"><title>W3Cschool(w3cschool.cn)</title></head><body><h1>这是标题1</h1><h2>这是标题2</h2><h3>这是标题 3</h3><h4>这是标题 4</h4><h5>这是标题 5</h5><h6>这是标题 6</h6></body></html> 19、HTML <center> 标签 - HTML 5 不支持 <center> 标签控制文本的居中显示,不能在 HTML5 中使用。 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><p>这是一些文本。</p><center>这个文本居中对齐。</center><p>这是一些文本</p></body></html> 20、HTML <button> 标签 <button> 标签用来设置 HTML 中的按钮。 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><button type="button" onclick="alert('Hello world!')">Click Me!</button></body></html> 21、HTML <br> 标签 <br> 标签是空标签,可插入一个简单的换行符。 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><p>使用br元素<br>在文本中<br>换行。</p></body></html> 22、HTML <dt> 标签 <dt> 标签只能够作为 <dl> 标签的一个子元素出现,常常后跟一个 <dd> 标签。 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><dl><dt>咖啡</dt><dd>黑色的热饮</dd><dt>牛奶</dt><dd>白色的冷饮</dd></dl></body></html> 23、HTML <fieldset> 标签 <fieldset> 标签内的一组表单元素会在 WEB 浏览器中以特殊的方式显示,比如不同样式的边界、3D效果等。 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><form><fieldset><legend>个人信息:</legend>姓名: <input type="text"><br>邮箱: <input type="text"><br>生日: <input type="text"></fieldset></form></body></html> 24、HTML <embed> 标签 <embed> 标签用来定义在页面中嵌入的内容,比如插件。比如,在下面的实例中我们嵌入了一个 flash 动画: <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><embed src="/statics/demosource/helloworld.swf" tppabs="http://W3Cschool.com/tags/helloworld.swf"></body></html> 25、HTML <font> 标签 - HTML5 不支持 <font> 标签的使用示例如下所示,该标签已经过时,因此我们不建议您使用该标签。 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><p><font size="3" color="red">这是一些文本!</font></p><p><font size="2" color="blue">这是一些文本!</font></p><p><font face="verdana" color="green">这是一些文本!</font></p></body></html> 26、HTML <label> 标签 <label> 标签是一种常见的表单控件,触发对应表单控件功能,让用户在使用表单的时候能够有更好的体验。参考下述的实例: <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>W3Cschool(w3cschool.cn)</title> </head><body><p>点击其中一个文本标签选中选项:</p><form action="/statics/demosource/demo-form.php"><label for="male">Male</label><input type="radio" name="sex" id="male" value="male"><br><label for="female">Female</label><input type="radio" name="sex" id="female" value="female"><br><br><input type="submit" value="提交"></form></body></html> 记录一些重要标签! 本篇文章为转载内容。原文链接:https://blog.csdn.net/chehec2010/article/details/85060460。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-11 23:43:21
296
转载
转载文章
...络响应慢,数据和画面展示慢、 6.过渡动画生硬。 7.界面不可交互,卡死,等等现象。 卡顿是如何发生的 卡顿产生的原因一般都比较复杂,如CPU内存大小,IO操作,锁操作,低效的算法等都会引起卡顿。 站在开发的角度看: 通常我们讲,屏幕刷新率是60fps,需要在16ms内完成所有的工作才不会造成卡顿。 为什么是16ms,不是17,18呢? 下面我们先来理清在UI绘制中的几个概念: SurfaceFlinger: SurfaceFlinger作用是接受多个来源的图形显示数据Surface,合成后发送到显示设备,比如我们的主界面中:可能会有statusBar,侧滑菜单,主界面,这些View都是独立Surface渲染和更新,最后提交给SF后,SF根据Zorder,透明度,大小,位置等参数,合成为一个数据buffer,传递HWComposer或者OpenGL处理,最终给显示器。 在显示过程中使用到了bufferqueue,surfaceflinger作为consumer方,比如windowmanager管理的surface作为生产方产生页面,交由surfaceflinger进行合成。 VSYNC Android系统每隔16ms发出VSYNC信号,触发对UI进行渲染,VSYNC是一种在PC上很早就有应用,可以理解为一种定时中断技术。 tearing 问题: 早期的 Android 是没有 vsync 机制的,CPU 和 GPU 的配合也比较混乱,这也造成著名的 tearing 问题,即 CPU/GPU 直接更新正在显示的屏幕 buffer 造成画面撕裂。 后续 Android 引入了双缓冲机制,但是 buffer 的切换也需要一个比较合适的时机,也就是屏幕扫描完上一帧后的时机,这也就是引入 vsync 的原因。 早先一般的屏幕刷新率是 60fps,所以每个 vsync 信号的间隔也是 16ms,不过随着技术的更迭以及厂商对于流畅性的追求,越来越多 90fps 和 120fps 的手机面世,相对应的间隔也就变成了 11ms 和 8ms。 VSYNC信号种类: 1.屏幕产生的硬件VSYNC:硬件VSYNC是一种脉冲信号,起到开关和触发某种操作的作用。 2.由SurfaceFlinger将其转成的软件VSYNC信号,经由Binder传递给Choreographer Choreographer: 编舞者,用于注册VSYNC信号并接收VSYNC信号回调,当内部接收到这个信号时最终会调用到doFrame进行帧的绘制操作。 Choreographer在系统中流程: 如何通过Choreographer计算掉帧情况:原理就是: 通过给Choreographer设置FrameCallback,在每次绘制前后看时间差是16.6ms的多少倍,即为前后掉帧率。 使用方式如下: //Application.javapublic void onCreate() {super.onCreate();//在Application中使用postFrameCallbackChoreographer.getInstance().postFrameCallback(new FPSFrameCallback(System.nanoTime()));}public class FPSFrameCallback implements Choreographer.FrameCallback {private static final String TAG = "FPS_TEST";private long mLastFrameTimeNanos = 0;private long mFrameIntervalNanos;public FPSFrameCallback(long lastFrameTimeNanos) {mLastFrameTimeNanos = lastFrameTimeNanos;mFrameIntervalNanos = (long)(1000000000 / 60.0);}@Overridepublic void doFrame(long frameTimeNanos) {//初始化时间if (mLastFrameTimeNanos == 0) {mLastFrameTimeNanos = frameTimeNanos;}final long jitterNanos = frameTimeNanos - mLastFrameTimeNanos;if (jitterNanos >= mFrameIntervalNanos) {final long skippedFrames = jitterNanos / mFrameIntervalNanos;if(skippedFrames>30){//丢帧30以上打印日志Log.i(TAG, "Skipped " + skippedFrames + " frames! "+ "The application may be doing too much work on its main thread.");} }mLastFrameTimeNanos=frameTimeNanos;//注册下一帧回调Choreographer.getInstance().postFrameCallback(this);} } UI绘制全路径分析: 有了前面几个概念,这里我们让SurfaceFlinger结合View的绘制流程用一张图来表达整个绘制流程: 生产者:APP方构建Surface的过程。 消费者:SurfaceFlinger UI绘制全路径分析卡顿原因: 接下来,我们逐个分析,看看都会有哪些原因可能造成卡顿: 1.渲染流程 1.Vsync 调度:这个是起始点,但是调度的过程会经过线程切换以及一些委派的逻辑,有可能造成卡顿,但是一般可能性比较小,我们也基本无法介入; 2.消息调度:主要是 doframe Message 的调度,这就是一个普通的 Handler 调度,如果这个调度被其他的 Message 阻塞产生了时延,会直接导致后续的所有流程不会被触发 3.input 处理:input 是一次 Vsync 调度最先执行的逻辑,主要处理 input 事件。如果有大量的事件堆积或者在事件分发逻辑中加入大量耗时业务逻辑,会造成当前帧的时长被拉大,造成卡顿,可以尝试通过事件采样的方案,减少 event 的处理 4.动画处理:主要是 animator 动画的更新,同理,动画数量过多,或者动画的更新中有比较耗时的逻辑,也会造成当前帧的渲染卡顿。对动画的降帧和降复杂度其实解决的就是这个问题; 5.view 处理:主要是接下来的三大流程,过度绘制、频繁刷新、复杂的视图效果都是此处造成卡顿的主要原因。比如我们平时所说的降低页面层级,主要解决的就是这个问题; 6.measure/layout/draw:view 渲染的三大流程,因为涉及到遍历和高频执行,所以这里涉及到的耗时问题均会被放大,比如我们会降不能在 draw 里面调用耗时函数,不能 new 对象等等; 7.DisplayList 的更新:这里主要是 canvas 和 displaylist 的映射,一般不会存在卡顿问题,反而可能存在映射失败导致的显示问题; 8.OpenGL 指令转换:这里主要是将 canvas 的命令转换为 OpenGL 的指令,一般不存在问题 9.buffer 交换:这里主要指 OpenGL 指令集交换给 GPU,这个一般和指令的复杂度有关 10.GPU 处理:顾名思义,这里是 GPU 对数据的处理,耗时主要和任务量和纹理复杂度有关。这也就是我们降低 GPU 负载有助于降低卡顿的原因; 11.layer 合成:Android P 修改了 Layer 的计算方法 , 把这部分放到了 SurfaceFlinger 主线程去执行, 如果后台 Layer 过多, 就会导致 SurfaceFlinger 在执行 rebuildLayerStacks 的时候耗时 , 导致 SurfaceFlinger 主线程执行时间过长。 可以选择降低Surface层级来优化卡顿。 12.光栅化/Display:这里暂时忽略,底层系统行为; Buffer 切换:主要是屏幕的显示,这里 buffer 的数量也会影响帧的整体延迟,不过是系统行为,不能干预。 2.系统负载 内存:内存的吃紧会直接导致 GC 的增加甚至 ANR,是造成卡顿的一个不可忽视的因素; CPU:CPU 对卡顿的影响主要在于线程调度慢、任务执行的慢和资源竞争,比如 1.降频会直接导致应用卡顿; 2.后台活动进程太多导致系统繁忙,cpu \ io \ memory 等资源都会被占用, 这时候很容易出现卡顿问题 ,这种情况比较常见,可以使用dumpsys cpuinfo查看当前设备的cpu使用情况: 3.主线程调度不到 , 处于 Runnable 状态,这种情况比较少见 4.System 锁:system_server 的 AMS 锁和 WMS 锁 , 在系统异常的情况下 , 会变得非常严重 , 如下图所示 , 许多系统的关键任务都被阻塞 , 等待锁的释放 , 这时候如果有 App 发来的 Binder 请求带锁 , 那么也会进入等待状态 , 这时候 App 就会产生性能问题 ; 如果此时做 Window 动画 , 那么 system_server 的这些锁也会导致窗口动画卡顿 GPU:GPU 的影响见渲染流程,但是其实还会间接影响到功耗和发热; 功耗/发热:功耗和发热一般是不分家的,高功耗会引起高发热,进而会引起系统保护,比如降频、热缓解等,间接的导致卡顿。 如何监控卡顿 线下监控: 我们知道卡顿问题的原因错综复杂,但最终都可以反馈到CPU使用率上来 1.使用dumpsys cpuinfo命令 这个命令可以获取当时设备cpu使用情况,我们可以在线下通过重度使用应用来检测可能存在的卡顿点 A8S:/ $ dumpsys cpuinfoLoad: 1.12 / 1.12 / 1.09CPU usage from 484321ms to 184247ms ago (2022-11-02 14:48:30.793 to 2022-11-02 14:53:30.866):2% 1053/scanserver: 0.2% user + 1.7% kernel0.6% 934/system_server: 0.4% user + 0.1% kernel / faults: 563 minor0.4% 564/signserver: 0% user + 0.4% kernel0.2% 256/ueventd: 0.1% user + 0% kernel / faults: 320 minor0.2% 474/surfaceflinger: 0.1% user + 0.1% kernel0.1% 576/vendor.sprd.hardware.gnss@2.0-service: 0.1% user + 0% kernel / faults: 54 minor0.1% 286/logd: 0% user + 0% kernel / faults: 10 minor0.1% 2821/com.allinpay.appstore: 0.1% user + 0% kernel / faults: 1312 minor0.1% 447/android.hardware.health@2.0-service: 0% user + 0% kernel / faults: 1175 minor0% 1855/com.smartpos.dataacqservice: 0% user + 0% kernel / faults: 755 minor0% 2875/com.allinpay.appstore:pushcore: 0% user + 0% kernel / faults: 744 minor0% 1191/com.android.systemui: 0% user + 0% kernel / faults: 70 minor0% 1774/com.android.nfc: 0% user + 0% kernel0% 172/kworker/1:2: 0% user + 0% kernel0% 145/irq/24-70900000: 0% user + 0% kernel0% 575/thermald: 0% user + 0% kernel / faults: 300 minor... 2.CPU Profiler 这个工具是AS自带的CPU性能检测工具,可以在PC上实时查看我们CPU使用情况。 AS提供了四种Profiling Model配置: 1.Sample Java Methods:在应用程序基于Java的代码执行过程中,频繁捕获应用程序的调用堆栈 获取有关应用程序基于Java的代码执行的时间和资源使用情况信息。 2.Trace java methods:在运行时对应用程序进行检测,以在每个方法调用的开始和结束时记录时间戳。收集时间戳并进行比较以生成方法跟踪数据,包括时序信息和CPU使用率。 请注意与检测每种方法相关的开销会影响运行时性能,并可能影响性能分析数据。对于生命周期相对较短的方法,这一点甚至更为明显。此外,如果您的应用在短时间内执行大量方法,则探查器可能会很快超过其文件大小限制,并且可能无法记录任何进一步的跟踪数据。 3.Sample C/C++ Functions:捕获应用程序本机线程的示例跟踪。要使用此配置,您必须将应用程序部署到运行Android 8.0(API级别26)或更高版本的设备。 4.Trace System Calls:捕获细粒度的详细信息,使您可以检查应用程序与系统资源的交互方式 您可以检查线程状态的确切时间和持续时间,可视化CPU瓶颈在所有内核中的位置,并添加自定义跟踪事件进行分析。在对性能问题进行故障排除时,此类信息可能至关重要。要使用此配置,您必须将应用程序部署到运行Android 7.0(API级别24)或更高版本的设备。 使用方式: Debug.startMethodTracing("");// 需要检测的代码片段...Debug.stopMethodTracing(); 优点:有比较全面的调用栈以及图像化方法时间显示,包含所有线程的情况 缺点:本身也会带来一点的性能开销,可能会带偏优化方向 火焰图:可以显示当前应用的方法堆栈: 3.Systrace Systrace在前面一篇分析启动优化的文章讲解过 这里我们简单来复习下: Systrace用来记录当前应用的系统以及应用(使用Trace类打点)的各阶段耗时信息包括绘制信息以及CPU信息等。 使用方式: Trace.beginSection("MyApp.onCreate_1");alt(200);Trace.endSection(); 在命令行中: python systrace.py -t 5 sched gfx view wm am app webview -a "com.chinaebipay.thirdcall" -o D:\trac1.html 记录的方法以及CPU中的耗时情况: 优点: 1.轻量级,开销小,CPU使用率可以直观反映 2.右侧的Alerts能够根据我们应用的问题给出具体的建议,比如说,它会告诉我们App界面的绘制比较慢或者GC比较频繁。 4.StrictModel StrictModel是Android提供的一种运行时检测机制,用来帮助开发者自动检测代码中不规范的地方。 主要和两部分相关: 1.线程相关 2.虚拟机相关 基础代码: private void initStrictMode() {// 1、设置Debug标志位,仅仅在线下环境才使用StrictModeif (DEV_MODE) {// 2、设置线程策略StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectCustomSlowCalls() //API等级11,使用StrictMode.noteSlowCode.detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems.penaltyLog() //在Logcat 中打印违规异常信息// .penaltyDialog() //也可以直接跳出警报dialog// .penaltyDeath() //或者直接崩溃.build());// 3、设置虚拟机策略StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()// 给NewsItem对象的实例数量限制为1.setClassInstanceLimit(NewsItem.class, 1).detectLeakedClosableObjects() //API等级11.penaltyLog().build());} } 线上监控: 线上需要自动化的卡顿检测方案来定位卡顿,它能记录卡顿发生时的场景。 自动化监控原理: 采用拦截消息调度流程,在消息执行前埋点计时,当耗时超过阈值时,则认为是一次卡顿,会进行堆栈抓取和上报工作 首先,我们看下Looper用于执行消息循环的loop()方法,关键代码如下所示: / Run the message queue in this thread. Be sure to call {@link quit()} to end the loop./public static void loop() {...for (;;) {Message msg = queue.next(); // might blockif (msg == null) {// No message indicates that the message queue is quitting.return;// This must be in a local variable, in case a UI event sets the loggerfinal Printer logging = me.mLogging;if (logging != null) {// 1logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);}...try {// 2 msg.target.dispatchMessage(msg);dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;} finally {if (traceTag != 0) {Trace.traceEnd(traceTag);} }...if (logging != null) {// 3logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);} 在Looper的loop()方法中,在其执行每一个消息(注释2处)的前后都由logging进行了一次打印输出。可以看到,在执行消息前是输出的">>>>> Dispatching to “,在执行消息后是输出的”<<<<< Finished to ",它们打印的日志是不一样的,我们就可以由此来判断消息执行的前后时间点。 具体的实现可以归纳为如下步骤: 1、首先,我们需要使用Looper.getMainLooper().setMessageLogging()去设置我们自己的Printer实现类去打印输出logging。这样,在每个message执行的之前和之后都会调用我们设置的这个Printer实现类。 2、如果我们匹配到">>>>> Dispatching to "之后,我们就可以执行一行代码:也就是在指定的时间阈值之后,我们在子线程去执行一个任务,这个任务就是去获取当前主线程的堆栈信息以及当前的一些场景信息,比如:内存大小、电脑、网络状态等。 3、如果在指定的阈值之内匹配到了"<<<<< Finished to ",那么说明message就被执行完成了,则表明此时没有产生我们认为的卡顿效果,那我们就可以将这个子线程任务取消掉。 这里我们使用blockcanary来做测试: BlockCanary APM是一个非侵入式的性能监控组件,可以通过通知的形式弹出卡顿信息。它的原理就是我们刚刚讲述到的卡顿监控的实现原理。 使用方式: 1.导入依赖 implementation 'com.github.markzhai:blockcanary-android:1.5.0' Application的onCreate方法中开启卡顿监控 // 注意在主进程初始化调用BlockCanary.install(this, new AppBlockCanaryContext()).start(); 3.继承BlockCanaryContext类去实现自己的监控配置上下文类 public class AppBlockCanaryContext extends BlockCanaryContext {....../ 指定判定为卡顿的阈值threshold (in millis), 你可以根据不同设备的性能去指定不同的阈值 @return threshold in mills/public int provideBlockThreshold() {return 1000;}....} 4.在Activity的onCreate方法中执行一个耗时操作 try {Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();} 5.结果: 可以看到一个和LeakCanary一样效果的阻塞可视化堆栈图 那有了BlockCanary的方法耗时监控方式是不是就可以解百愁了呢,呵呵。有那么容易就好了 根据原理:我们拿到的是msg执行前后的时间和堆栈信息,如果msg中有几百上千个方法,就无法确认到底是哪个方法导致的耗时,也有可能是多个方法堆积导致。 这就导致我们无法准确定位哪个方法是最耗时的。如图中:堆栈信息是T2的,而发生耗时的方法可能是T1到T2中任何一个方法甚至是堆积导致。 那如何优化这块? 这里我们采用字节跳动给我们提供的一个方案:基于 Sliver trace 的卡顿监控体系 Sliver trace 整体流程图: 主要包含两个方面: 检测方案: 在监控卡顿时,首先需要打开 Sliver 的 trace 记录能力,Sliver 采样记录 trace 执行信息,对抓取到的堆栈进行 diff 聚合和缓存。 同时基于我们的需要设置相应的卡顿阈值,以 Message 的执行耗时为衡量。对主线程消息调度流程进行拦截,在消息开始分发执行时埋点,在消息执行结束时计算消息执行耗时,当消息执行耗时超过阈值,则认为产生了一次卡顿。 堆栈聚合策略: 当卡顿发生时,我们需要为此次卡顿准备数据,这部分工作是在端上子线程中完成的,主要是 dump trace 到文件以及过滤聚合要上报的堆栈。分为以下几步: 1.拿到缓存的主线程 trace 信息并 dump 到文件中。 2.然后从文件中读取 trace 信息,按照数据格式,从最近的方法栈向上追溯,找到当前 Message 包含的全部 trace 信息,并将当前 Message 的完整 trace 写入到待上传的 trace 文件中,删除其余 trace 信息。 3.遍历当前 Message trace,按照(Method 执行耗时 > Method 耗时阈值 & Method 耗时为该层堆栈中最耗时)为条件过滤出每一层函数调用堆栈的最长耗时函数,构成最后要上报的堆栈链路,这样特征堆栈中的每一步都是最耗时的,且最底层 Method 为最后的耗时大于阈值的 Method。 之后,将 trace 文件和堆栈一同上报,这样的特征堆栈提取策略保证了堆栈聚合的可靠性和准确性,保证了上报到平台后堆栈的正确合理聚合,同时提供了进一步分析问题的 trace 文件。 可以看到字节给的是一整套监控方案,和前面BlockCanary不同之处就在于,其是定时存储堆栈,缓存,然后使用diff去重的方式,并上传到服务器,可以最大限度的监控到可能发生比较耗时的方法。 开发中哪些习惯会影响卡顿的发生 1.布局太乱,层级太深。 1.1:通过减少冗余或者嵌套布局来降低视图层次结构。比如使用约束布局代替线性布局和相对布局。 1.2:用 ViewStub 替代在启动过程中不需要显示的 UI 控件。 1.3:使用自定义 View 替代复杂的 View 叠加。 2.主线程耗时操作 2.1:主线程中不要直接操作数据库,数据库的操作应该放在数据库线程中完成。 2.2:sharepreference尽量使用apply,少使用commit,可以使用MMKV框架来代替sharepreference。 2.3:网络请求回来的数据解析尽量放在子线程中,不要在主线程中进行复制的数据解析操作。 2.4:不要在activity的onResume和onCreate中进行耗时操作,比如大量的计算等。 2.5:不要在 draw 里面调用耗时函数,不能 new 对象 3.过度绘制 过度绘制是同一个像素点上被多次绘制,减少过度绘制一般减少布局背景叠加等方式,如下图所示右边是过度绘制的图片。 4.列表 RecyclerView使用优化,使用DiffUtil和notifyItemDataSetChanged进行局部更新等。 5.对象分配和回收优化 自从Android引入 ART 并且在Android 5.0上成为默认的运行时之后,对象分配和垃圾回收(GC)造成的卡顿已经显著降低了,但是由于对象分配和GC有额外的开销,它依然又可能使线程负载过重。 在一个调用不频繁的地方(比如按钮点击)分配对象是没有问题的,但如果在在一个被频繁调用的紧密的循环里,就需要避免对象分配来降低GC的压力。 减少小对象的频繁分配和回收操作。 好了,关于卡顿优化的问题就讲到这里,下篇文章会对卡顿中的ANR情况的处理,这里做个铺垫。 如果喜欢我的文章,欢迎关注我的公众号。 点击这看原文链接: 参考 Android卡顿检测及优化 一文读懂直播卡顿优化那些事儿 “终于懂了” 系列:Android屏幕刷新机制—VSync、Choreographer 全面理解! 深入探索Android卡顿优化(上) 西瓜卡顿 & ANR 优化治理及监控体系建设 5376)] 参考 Android卡顿检测及优化 一文读懂直播卡顿优化那些事儿 “终于懂了” 系列:Android屏幕刷新机制—VSync、Choreographer 全面理解! 深入探索Android卡顿优化(上) 西瓜卡顿 & ANR 优化治理及监控体系建设 本篇文章为转载内容。原文链接:https://blog.csdn.net/yuhaibing111/article/details/127682399。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-26 08:05:57
214
转载
转载文章
... 担任什么角色,平时开发流程 之类的,然后J哥 就说大概在公司开发了有5款APP,自己私下接过一款私活,然后自己没事也做了两款应用,然后J哥 把应用展示给他看,他看了连连称赞不错啊。。。(lalala,其实都是J哥网上巴拉的项目啦。) (然后大体给他介绍了 项目基本框架,是 v4包里的 SlidingPaneLayout 嵌套了实现了轮询效果 自定义的viewpager 。然后 具体界面是用的瀑布流,项目的关键就是 对 图片的处理,因为有N张 图片,但是并没有卡顿,所以就说了 自己用 了开源的imagedownloader 和 volley 以及自己定义的 lrucache 缓存 bitmap 对象,这里大家一定要把图片的三级缓存 自己了解清楚,基本面试会问到。) 其实 当面试问你如何避免oom,内存泄露导致的原因,以及如何处理大图片等等,其实都是 如何优化内存。 可以按照我自己总结的回答,你可以说,这个问题 ,跟 oom以及 内存泄露,其实是一样的,关键 就是 如何 优化内存,避免不必要的 内存泄露, 而 内存泄露 的原因 ,我总结了 4点, 1. 匿名内部类,和非静态内部类, 举个栗子:我们用handler 进行线程间 假如 我们在activity中这样定义 handler : [java] view plain copy print ? Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mImageView.setImageBitmap(mBitmap); } } 然后,我们用 右键 选中工程 运行 lint工具 , android tools---run lint ,就会提示我们这样一个warning: In Android, Handler classes should be static or leaks might occur.。 就是 ,推荐我们 把handler 定义成static,具体 看这里解释的很详细:http://www.linuxidc.com/Linux/2013-12/94065.htm 类似的还有 匿名子线程。 2.还是 拿网上的 栗子来说, [java] view plain copy print ? Vector v = new Vector( 10 ); for ( int i = 1 ;i < 100 ; i ++ ){ Object o = new Object(); v.add(o); o = null ; } 即便是 我们把 o 对象 置为 null,但是 vector 集合中还有有o的引用,所以 集合 没有被清空,这一部分内存 还是不能被释放,这就导致了内存泄露。 3, 当我们操作数据库的时候,我们在执行完 相应的crud 方法后,我们没有关闭 cursor .close()或者 db.close(),也同样会占用内存、因为只有关闭连接后,才会被GC 回收。 4.继续举个栗子 [java] view plain copy print ? Set<Person> set = new HashSet<Person>(); Person p1 = new Person("唐僧","pwd1",25); Person p2 = new Person("孙悟空","pwd2",26); Person p3 = new Person("猪八戒","pwd3",27); set.add(p1); set.add(p2); set.add(p3); System.out.println("总共有:"+set.size()+" 个元素!"); //结果:总共有:3 个元素! p3.setAge(2); //修改p3的年龄,此时p3元素对应的hashcode值发生改变 set.remove(p3); //此时remove不掉,造成内存泄漏 set.add(p3); //重新添加,居然添加成功 System.out.println("总共有:"+set.size()+" 个元素!"); //结果:总共有:4 个元素! J哥 亲自 实践了下,发现问题了,这个网上的栗子 是错的。实际上是可以remove掉得、真是个悲伤地故事。这个栗子是不正确的。。网上好有一片这样的文章,都是这个栗子。。 这里 看下其他网站上的总结吧 :强烈推荐http://developer.51cto.com/art/201111/302465.htm。很详细。 OK。还有最后一点,就是关于图片的,bitmap对象的及时释放,这里 就不细说了,等在图片三级缓存一起去总结。 此时 感觉 对面的android 小哥 已经被我吸引了。好像很认真的在听我讲课一样。 然后, 他问我问题。我大体总结了一下。 面试官01问:有没有自定义过view。 J哥回答:这个很常见,我自己定义过很多,比如 下拉刷新,上拉加载更多数据的listview,类似github 上面的pulltorefreshlistview。 还有图片轮询播放的viewpager,也是 继承viewpager,然后自己开启一个线程,去控制 切换的。还比如,跑马灯效果的textview ,scrollview与 listview 相互嵌套 导致 listview 高度计算不正确,我也是 自定义listview,复写了 onmeaure方法,然后解决冲突的。在比如 一些开源的 可以放大缩小的图片,我也是做过,主要是对onmeasure 方法,onlayout方法,ondraw 方法的复写。以及复写一下 view 自己的 touch事件等等,奥 对了,我们公司当时有需求 做一个 锁屏软件,侧滑解锁的,我也是自己定义的,然后展示给他看了一下,当时 那篇文章在这里。传送门http://blog.csdn.net/u011733020/article/details/41863861。 面试官01问:listview的优化、 J哥回答:(PS:这种问题,基本上 都快被问烂了,但是没办法 还是要回答。)listview作为最常见的 用来显示数据的view ,一般 从四个方面 去优化。 1 ,复用convertview, 不然假如有1000条数据,那么我们滑动,就会 产生1000个convertview ,这对内存是很大的浪费,所以 我们一定要复用。 2. 减少 findviewbyid 的次数, 因为 每次 去 执行 findviewbyid 也是要消耗资源的,我们要尽可能的减少,通常 我们定义一个viewholder,去管理 这些id ,然后通过tag 去直接拿到 id。 3, 分页加载,延迟加载 预加载。 这个在我们以前项目,有一个榜单,数据量很大,一次请求过来的数据量很大,这样有两个问题,一个是请求网络 时间可能会很长,另一个展示数据 上面 体验对不是很好,所以 我们做了 第一次加载 20条,然后每次请求 再去 加载10条新数据。 4.就是 对 listview 中一些 类似头像, 图片的 优化。这里 类似 三级缓存,推荐大家看一下 开源 的universal-image-loader 的源码。或者 这篇文章http://www.jb51.net/article/38162.htm,J哥有时间 专门写一篇过于 图片缓存的。 面试官01问: 看你简历上面 做过 社交,通信这块是怎么做的。 J哥回答:我看 咱们公司 也用到了 聊天,咱们公司是 自己做的 还是 用的第三方的类似 环信的。结果被J哥猜中,他说 是集成的环信(但是 有丢包现象,所以打算自己做通信)。 OK,J哥说 ,我们 项目中聊天 是基于xmpp协议的做的,在没有android以前 ,java有个开源的 smack ,android 上 现在有一个asmack ,其实 就是移植到android 中来了, 服务端是基于 openfire的 ,我们就是做的 openfire+asmack 的 聊天,这个原理主要 就是 绑定 ip 拿到 connection 然后 connect ,然后进行通信,我说,这个 跟http请求 其实原理上一样,都是 绑定ip,然后 设置一些property,然后通过类似流进行通信的, asmack,其实底层 就是xml通信的。 面试官01问: touch 事件的传递机制,还特意画了,一个 就是 button LinearLayout 嵌套 。 J哥回答:就是这个, 这也难不倒我。因为J哥觉得 这个问题肯定会问到 所以 早有准备,这里 我就大体说下结论,详细原理 给你传送门。 我回答,这个很简单,只要你继承一下 button 和 linearlayout 复写一下 三个方法 dispatchtouchEvent onInterceptTouchEvent 和onTouchEvent .就能很清楚的明白 传递的过程,我给你总的说下结论的,点击这个button,一般是 外面的父控件 先响应这个down 事件,然后 往子类里面传递,让子类 在往子类的下一级子类去传递,让最终的孩子去决定是不要要消费掉这个点击事件,如果消费掉,那么父类将不会响应,如果子类不消费,那么会退回到次级子类,然后看是否要消费,这样,一句话 就是父传子, 子决定要不要,不要 然后传回去。 这里有很详细 很详细的介绍, 包裹事件的分发。所以我就不罗嗦,http://blog.csdn.net/yanbober/article/details/45887547?ref=myread 面试官01问: 项目中图片的优化。 J哥回答:我给他展示的项目 其中有一款app 是有很多图片 ,但是 很流畅,也没有oom。关于图片 优化,一般我们采用三级缓存,1 。内存加载 2.本地加载 3 网络加载。 首先 我们看 内存中有没有,有直接拿来用,这里 我项目里是这样做的,我先获取一下 分配给我们应用的可用内存是多少,然后 拿1/4 或者 1/8做一个 lrucache. 把我们的bitmap对象添加进去。有些比较常用的图片,我会保存到本地,避免每次重复联网下载。结合 开源的 afinal universalimageloader 以及 13年谷歌官方推荐的volley(号称是 asynchttpclient 和universalimageloader)的结合、 所以 在我的项目中基本没有遇到过图片导致的oom 问题,对于单张的 大图片,我也会利用bitmapFactory,进行计算大小,然后 计算手机分辨率,进行定量的 压缩 处理。 面试官问: GC的回收 J哥回答:我说。GC 回收 应该不只是按照一种方式,应该有多种不同的算法,我看过谷歌 官网介绍的一点,有这样一块区域,他分为 latest(最近) middle(中等)permanent(永久的),这样三块子区域。里面分别存放,刚刚被创建的,以及 时间 靠后的,很久的,对象,不断地新对象 往latest里面添加,当达到相应对象区域的阀值的时候,就会触发GC,GC 进行回收的时候,对于latest 中回收的速度是最快的,而permanent 相对是最久的,而时间 也跟 每块区域中对象的个数有关系, 还有一种算法,是根据最近被引用的时间,或者 被引用的次数 去进行 GC的、、这里随便扯就是了。GC 回收并不是立即执行的。是不定时的。GC回收的时候 会阻塞线程,所以代码中要避免创建不必要的对象,例如for循环中 创建大量对象 就会容易引起GC。 当我们也可以主动 在方法中执行system.gc() 去手动释放一些资源。 面试官01问: 怎么避免 viewpager 预加载 fragment的、 J哥回答:这个问题 我也碰到过,我们都知道,viewpager 它本身会预加载 左右两个 和当前一个对象、而 我们viewpager setOffscreenPageLimit(0) 不生效因为看源码知道,这个方法默认最少也要加载一个。所以 这个fragment 还没有被当前页面显示出来,已经夹在好了,有可能数据不是最新的,我是在 setuservisibilityhint() 这个方法中跟参数 动态去判断 要不要刷新的。 问了一圈,这个哥们大概没什么问的了,然后 就让我等一下,说让他们技术总监过来 。 我就等。。。 然后等了几分钟,进来一小姑娘,坐下,看了我简历,我以为是人事,来跟我谈人生理想。结果,没说几句话,让我讲一下我的项目。我qu,惊呆我了。我问,你也是做android的,我去,是这样的、、把J哥吓到, 然后问了J哥几个问题。 Android 小姑娘问: 看你项目中的listview 中item类型 是统一的,而加入 item 差别挺大的 你怎么复用。 J哥回答:J哥装作很牛的样子说,我暂时想到两种方法,1.给这个对象 加一个type 然后 根据 type 去复用,或者 把这几种类型 一起加载,然后控制显示隐藏。然后 我反问小姑娘,假如 我这里 有一百条数据,这一百条是无序的,包含了 10种 item类型,你有没有什么好方法 去处理这个问题, 小姑娘说,你不是定义了类型吗,我们就是 通过type 去判断的。 Android 小姑娘问: onAttch onDetach还是onAttachedToWindow,onDetachedFromWindow J哥回答:其实 那个小姑娘忘记这两个方法了。我说什么方法,她说onAttachIntent() 和 onDetachIntent(). 反正 J哥是没听说过, 我只见过 onAttach ,但是 这个方法 我也没用过。我就问她,这两个方法是做什么的,小姑娘跟我说 是 把子view绑定到界面上的,那么的话 应该是onAttachedToWindow,onDetachedFromWindow方法了,小姑娘说: 在这个方法 可以计算子 view的高度宽度,在 oncreate 里面不能计算,其实虽然刚开始 在oncreate里面是不能计算,但是还是有方法计算的,(本人觉得面试 问你 API 是 最2的了,忍不住吐槽下,我遇到过,Camera 拍照,问我获取 一个图片,还是 视频的 方法,我去百度 一下,随便就知道,真是不懂 为什么会问方法。随便一个程序员 都会百度。。) 跟小姑娘聊得其他问题 不太记得了,感觉这个女程序员啊。。就问方法 给我的印象不太好,不管方法用没用到,我觉得面试 直接问你方法 好2 好2... 然后技术总监 有进来跟我聊了,后技术总监 有进来跟我聊了、技术总监 年龄30出头吧,到是没有问我什么技术问题, 总监: 问我 做没做过通信这块,能不能做这一块。 J哥回答:,我说做过,通信有几种协议的,我们用的 是xmpp协议的 ,服务器 是 基于apache的 openfire 搭建的,客户端 是用的asmack。还有一些 其他协议的 ,比如我知道有些项目中用的 soap协议的,还有ip 协议的。PS:反正就是扯 我说 通信 客户端这一块 我没问题,但是 服务端 我 从工作以来 一直偏向 android 移动端开发,后台这一块,如果数据量大了,还要考虑并发之类的,我是做不了,让我做个tomcat搭建的demo 我可能可以。 其他也是随便聊了下,然后 就说,让人事来跟我谈理想了。 总监: 问我 什么时候能上班 J哥回答:我说 这个看公司需求啦。 其他也是随便聊了下,然后 就说,让人事来跟我谈理想了。 这里 感觉应该没问题了。差不多能拿下了。 人事1:一进来,就问东问西。问加班看法啊,他们公司技术 一般都八九点走啊。说七点基本没有走的啊、、、 J哥回答:我说,一般遇到项目加功能 ,版本升级,等等 这些加班都没什么,只要不是一直在加班。。。。这里每个人自己看法就好了、、 反正人事 是一直跟我强调这个,她不停强调 我就暗暗下决心,薪资 我是不会要低了。 人事1:看你还年轻啊,还能拼一拼啊、、、、 J哥回答:我说现在 这几年对我人生规划也算比较重要的时期,也是过一年少一年了,其实她的意思 还是侧面强调加班。。。。日了UZI了。 中间一堆废话,然后我问了她 公司一般上下班时间啊。。之类的有没有技术交流啊,之类的。。。 最后到关键问题上啦,最关心的,薪资问题。 人事1:期望薪资 J哥回答:我说16K左右吧。她问 你以前公司多少 握手 15K。她说她们公司 是 14薪。反正 我还是说16K。她说 那好,你等下,然后就出去了。 不知道 跟什么人 讨论了许久,然后又来一个 可能是人事吧。又进来,问了一遍,也问了薪资。。哥还是说16K 。 。。估计是她们公司想要我,但是又觉得有点超出她们薪资期望吧,当场被没有给什么offer。然后就有点婉拒的说,两天给我答复,心里很气愤,饿着肚子 面试到三点,竟然婉拒、、、 反正我是很生气,我说,好,然后我就走。结果,没过一个小时,人事又打电话来,非要约我 见一下她们CEO。这是什么鬼,难道她们CEO要给我煲汤 了?我说可以,然后时间定在后天了,,反正心灵鸡汤对我是没用了、 OK ,这家面试 先写到这里,下面下午还有一家,等下在写。准备睡觉。今天面试回来,累的就睡着了,晚上十点多才醒过来,想了想还是 把今天面试的过程总结一下。 ------------------------------待续------------------------- 第二弹http://blog.csdn.net/u011733020/article/details/46058273 本篇文章为转载内容。原文链接:https://blog.csdn.net/haluoluo211/article/details/51010955。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-06-19 17:42:52
336
转载
转载文章
...tity的描述,向你展示它所提供的一些高级特性。我将演示,你可以扩展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
283
转载
转载文章
在深入理解了Java中this关键字在Android开发中的具体应用以及Android系统中Context机制之后,开发者们可以进一步关注以下几方面的 首先,对于Android开发的新动态,Google在Android 12版本中对Context的使用引入了一些新特性与优化。例如,为了提高隐私和安全,限制了通过Context获取设备信息的能力,要求开发者更明确地声明权限。此外,针对Context的生命周期管理,Google也推出了一些最佳实践指南,以帮助开发者更好地遵循架构组件设计原则,避免内存泄漏等问题。 其次,深入探究Android组件间的交互方式,尤其是Activity、Service和BroadcastReceiver等组件如何通过Context进行通信,是提升Android开发技能的重要一环。近期有关消息传递机制(如Jetpack库中的WorkManager、LiveData)的博客文章和技术分享,能为开发者提供更加高效且符合现代Android架构规范的Context使用范例。 再者,从设计模式角度解读Context在MVC、MVP、MVVM等不同架构中的角色转变,有助于理解其在整个应用架构中的核心地位。一些经典的软件设计书籍和专家解析文章对此有独到见解,值得深入研读。 最后,结合实际项目案例分析,了解大型项目中Context的最佳实践及常见问题处理方案。许多技术社区和开源项目会分享他们在处理多模块间Context共享、Context引用导致的内存泄漏等问题时的具体解决方案和经验总结,这对于开发者来说具有极高的实战参考价值。
2023-09-27 17:37:26
93
转载
转载文章
...ng;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.;import java.net.URLEncoder;import java.util.Optional;/ @Description 文件切片下载 @ClassName DownLoadController @Author 康世行 @Date 20:58 2023/2/22 @Version 1.0/@Controller@Slf4jpublic class DownLoadController {private final static String utf8 = "utf-8";@RequestMapping("/down")public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {// 设置编码格式response.setCharacterEncoding(utf8);//获取文件路径String fileName=request.getParameter("fileName");String drive=request.getParameter("drive");//参数校验log.info(fileName,drive);//完整路径(路径拼接待优化-前端传输优化-后端从新格式化 )String pathAll=drive+":\\"+fileName;log.info("pathAll{}",pathAll);Optional<String> pathFlag = Optional.ofNullable(pathAll);File file=null;if (pathFlag.isPresent()){//根据文件名,读取file流file = new File(pathAll);log.info("文件路径是{}",pathAll);if (!file.exists()){log.warn("文件不存在");return;} }else {//请输入文件名log.warn("请输入文件名!");return;}InputStream is = null;OutputStream os = null;try {//分片下载long fSize = file.length();//获取长度response.setContentType("application/x-download");String file_Name = URLEncoder.encode(file.getName(),"UTF-8");response.addHeader("Content-Disposition","attachment;filename="+fileName);//根据前端传来的Range 判断支不支持分片下载response.setHeader("Accept-Range","bytes");//获取文件大小//response.setHeader("fSize",String.valueOf(fSize));response.setHeader("fName",file_Name);//定义断点long pos = 0,last = fSize-1,sum = 0;//判断前端需不需要分片下载if (null != request.getHeader("Range")){response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);String numRange = request.getHeader("Range").replaceAll("bytes=","");String[] strRange = numRange.split("-");if (strRange.length == 2){pos = Long.parseLong(strRange[0].trim());last = Long.parseLong(strRange[1].trim());//若结束字节超出文件大小 取文件大小if (last>fSize-1){last = fSize-1;} }else {//若只给一个长度 开始位置一直到结束pos = Long.parseLong(numRange.replaceAll("-","").trim());} }long rangeLenght = last-pos+1;String contentRange = new StringBuffer("bytes").append(pos).append("-").append(last).append("/").append(fSize).toString();response.setHeader("Content-Range",contentRange);// response.setHeader("Content-Lenght",String.valueOf(rangeLenght));os = new BufferedOutputStream(response.getOutputStream());is = new BufferedInputStream(new FileInputStream(file));is.skip(pos);//跳过已读的文件(重点,跳过之前已经读过的文件)byte[] buffer = new byte[1024];int lenght = 0;//相等证明读完while (sum < rangeLenght){lenght = is.read(buffer,0, (rangeLenght-sum)<=buffer.length? (int) (rangeLenght - sum) :buffer.length);sum = sum+lenght;os.write(buffer,0,lenght);}log.info("下载完成");}finally {if (is!= null){is.close();}if (os!=null){os.close();} }} } 启动成功 Vue <html xmlns:th="http://www.thymeleaf.org"><head><meta charset="utf-8"/><title>狂神说Java-ES仿京东实战</title><link rel="stylesheet" th:href="@{/css/style.css}"/></head><body class="pg"><div class="page" id="app"><div id="mallPage" class=" mallist tmall- page-not-market "><!-- 头部搜索 --><div id="header" class=" header-list-app"><div class="headerLayout"><div class="headerCon "><!-- Logo--><h1 id="mallLogo"><img th:src="@{/images/jdlogo.png}" alt=""></h1><div class="header-extra"><!--搜索--><div id="mallSearch" class="mall-search"><form name="searchTop" class="mallSearch-form clearfix"><fieldset><legend>天猫搜索</legend><div class="mallSearch-input clearfix"><div class="s-combobox" id="s-combobox-685"><div class="s-combobox-input-wrap"><input v-model="keyword" type="text" autocomplete="off" value="java" id="mq"class="s-combobox-input" aria-haspopup="true"></div></div><button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button></div></fieldset></form><ul class="relKeyTop"><li><a>狂神说Java</a></li><li><a>狂神说前端</a></li><li><a>狂神说Linux</a></li><li><a>狂神说大数据</a></li><li><a>狂神聊理财</a></li></ul></div></div></div></div></div><el-button @click="download" id="download">下载</el-button><!-- <el-button @click="concurrenceDownload" >并发下载测试</el-button>--><el-button @click="stop">停止</el-button><el-button @click="start">开始</el-button>{ {fileFinalOffset} }{ {contentList} }<el-progress type="circle" :percentage="percentage"></el-progress></div><!--前端使用Vue,实现前后端分离--><script th:src="@{/js/axios.min.js}"></script><script th:src="@{/js/vue.min.js}"></script><!-- 引入样式 --><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"><!-- 引入组件库 --><script src="https://unpkg.com/element-ui/lib/index.js"></script><script>new Vue({ el: 'app',data: {keyword: '', //搜索关键字results: [] ,//搜索结果percentage: 0, // 下载进度filesCurrentPage:0,//文件开始偏移量fileFinalOffset:0, //文件最后偏移量stopRecursiveTags:true, //停止递归标签,默认是true 继续进行递归contentList: [], // 文件流数组breakpointResumeTags:false, //断点续传标签,默认是false 不进行断点续传temp:[],fileMap:new Map(),timer:null, //定时器名称},methods: {//根据关键字搜索商品信息searchKey(){var keyword=this.keyword;axios.get('/search/JD/search/'+keyword+"/1/10").then(res=>{this.results=res.data;//绑定数据console.log(this.results)console.table(this.results)})},//停止下载stop(){//改变递归标签为falsethis.stopRecursiveTags=false;},//开始下载start(){//重置递归标签为true 最后进行合并this.stopRecursiveTags=true;//重置断点续传标签this.breakpointResumeTags=true;//重新调用下载方法this.download();},// 分段下载需要后端配合download() {// 下载地址const url = "/down?fileName="+this.keyword.trim()+"&drive=E";console.log(url)const chunkSize = 1024 1024 50; // 单个分段大小,这里测试用100Mlet filesTotalSize = chunkSize; // 安装包总大小,默认100Mlet filesPages = 1; // 总共分几段下载//计算百分比之前先清空上次的if(this.percentage==100){this.percentage=0;}let sentAxios = (num) => {let rande = chunkSize;//判断是否开启了断点续传(断点续传没法并行-需要上次请求的结果作为参数)if (this.breakpointResumeTags){rande = ${Number(this.fileFinalOffset)+1}-${num chunkSize + 1};}else {if (num) {rande = ${(num - 1) chunkSize + 2}-${num chunkSize + 1};} else {// 第一次0-1方便获取总数,计算下载进度,每段下载字节范围区间rande = "0-1";} }let headers = {range: rande,};axios({method: "get",url: url.trim(),async: true,data: {},headers: headers,responseType: "blob"}).then((response) => {if (response.status == 200 || response.status == 206) {//检查了下才发现,后端对文件流做了一层封装,所以将content指向response.data即可const content = response.data;//截取文件总长度和最后偏移量let result= response.headers["content-range"].split("/");// 获取文件总大小,方便计算下载百分比filesTotalSize =result[1];//获取最后一片文件位置,用于断点续传this.fileFinalOffset=result[0].split("-")[1]// 计算总共页数,向上取整filesPages = Math.ceil(filesTotalSize / chunkSize);// 文件流数组this.contentList.push(content);// 递归获取文件数据(判断是否要继续递归)if (this.filesCurrentPage < filesPages&&this.stopRecursiveTags==true) {this.filesCurrentPage++;//计算下载百分比 当前下载的片数/总片数this.percentage=Number((this.contentList.length/filesPages)100).toFixed(2);sentAxios(this.filesCurrentPage);//结束递归return;}//递归标签为true 才进行下载if (this.stopRecursiveTags){// 文件名称const fileName =decodeURIComponent(response.headers["fname"]);//构造一个blob对象来处理数据const blob = new Blob(this.contentList);//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性//IE10以上支持blob但是依然不支持downloadif ("download" in document.createElement("a")) {//支持a标签download的浏览器const link = document.createElement("a"); //创建a标签link.download = fileName; //a标签添加属性link.style.display = "none";link.href = URL.createObjectURL(blob);document.body.appendChild(link);link.click(); //执行下载URL.revokeObjectURL(link.href); //释放urldocument.body.removeChild(link); //释放标签} else {//其他浏览器navigator.msSaveBlob(blob, fileName);} }} else {//调用暂停方法,记录当前下载位置console.log("下载失败")} }).catch(function (error) {console.log(error);});};// 第一次获取数据方便获取总数sentAxios(this.filesCurrentPage);this.$message({message: '文件开始下载!',type: 'success'});} }})</script></body></html> 本篇文章为转载内容。原文链接:https://blog.csdn.net/kangshihang1998/article/details/129407214。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-19 08:12:45
546
转载
HTML
...台,它的网站主要使用HTML代码来建立。以下是一段简单的HTML代码,说明了传智书城的网站顶部信息: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>传智书城</title> <link rel="stylesheet" href="style.css"> </head> <body> 上面的代码中,第一行“DOCTYPE html”表示页面是按照HTML5规范编写的。第二行“html”标签是HTML页面的基础标签,它容纳了整个HTML页面的内容。第三行“head”标签表示页面顶部信息的开始,其中“meta charset”表示页面使用的文本编码是UTF-8,这是一种全球通用的编码规范,兼容多语种的文本展示。在第四行中,“title”标签设定了页面的标题,“link rel”标签链接了网站使用的CSS文件“style.css”。 下面是页面的主要内容,代码如下所示: <div id="main"> <div class="banner"> <img src="banner.jpg" alt="banner"> </div> <div class="books"> <h2>热门图书</h2> <ul> <li><a href="../book/1.html">Python初级到高级</a></li> <li><a href="../book/2.html">Java编程理念</a></li> <li><a href="../book/3.html">Node.js开发教程</a></li> </ul> </div> </div> 在页面主要内容中,“div”标签用来设定页面中不同的区域,例如上面的“main”和“banner”区域。在“banner”区域中,“img”标签用来展示网站头部的宣传图片。“books”区域展示了网站的热门图书,其中“h2”标签用来设定标题,而“ul”和“li”标签用于列表的展示和链接。 总之,HTML是建立网站的重要基石,传智书城网站的HTML代码适当地组合和使用页面元素,实现了网站的美观和实用性。
2023-08-22 12:19:23
463
算法侠
Tomcat
...Tomcat中的 java.lang.IllegalMonitorStateException: 深度解析与解决之道 一、引言 在开发过程中,我们常常与各种异常打交道,它们是程序健壮性和调试过程中的重要组成部分。今天,我们将聚焦于一个特定的异常——java.lang.IllegalMonitorStateException,它在使用Tomcat等Java应用服务器时可能遇到。这个异常通常出现在不当的监视器状态下调用监视器方法的情景下。哎呀,兄弟,搞清楚这捣蛋玩意儿的来龙去脉,还有它到底怎么闹腾的,以及咱得怎么对付它,这事儿可关键了!能帮咱们更好地守着咱们的Java程序,让它运行得更顺溜,性能更高昂,你说是不是?别忘了,咱的目标是让代码不仅跑得快,还得健健康康的,对吧?所以,咱们得仔细琢磨琢磨,找到那个问题的根子,然后想出个好办法,把它搞定! 二、异常定义与背景 java.lang.IllegalMonitorStateException异常表明调用了一个在当前线程不拥有监视器锁的情况下被保护的方法。哎呀,你知道的,这种情况经常出现在我们用电脑同时做好多事情的时候。比如说你一边在浏览器上刷微博,一边在同一个电脑上运行一个程序,结果就可能会出问题。问题就是,一个程序的部分(我们叫它“线程”)想用一些共同的数据(比如一个共享的记事本),但是它没拿到这个数据的“钥匙”。这就像是你想去拿别人的书包里的东西,但是你手上没钥匙开不了包,结果就乱了套了。这种时候,电脑就得小心处理,防止出现混乱或者错误的结果。 三、示例代码分析 为了更好地理解这个异常,让我们通过一个简单的示例来演示它可能出现的情况: java import java.util.concurrent.locks.ReentrantLock; public class LockDemo { private static final ReentrantLock lock = new ReentrantLock(); private static int counter = 0; public static void main(String[] args) { // 锁住资源 lock.lock(); try { System.out.println("开始操作..."); // 这里是你的业务逻辑 doSomething(); } finally { lock.unlock(); // 不要忘记解锁 } } private static void doSomething() { synchronized (LockDemo.class) { // 锁定当前类的对象 counter++; System.out.println("计数器值:" + counter); } } } 这段代码展示了如何正确地使用锁来保护共享资源。哎呀,兄弟!你要是不小心在没锁门的情况下闯进了别人的私人空间,那肯定得吃大亏啊!就像这样,在编程的世界里,如果你不巧在没锁定的情况下就去碰那些受保护的资源,那可就等着被系统给你来个“非法监视状态异常”吧!这可不是闹着玩的,得小心点! 错误示例: java import java.util.concurrent.locks.ReentrantLock; public class LockDemoError { private static final ReentrantLock lock = new ReentrantLock(); private static int counter = 0; public static void main(String[] args) { System.out.println("开始操作..."); // 这里尝试访问受保护的资源,但没有锁定 doSomething(); } private static void doSomething() { synchronized (LockDemoError.class) { counter++; System.out.println("计数器值:" + counter); } } } 运行上述错误示例,将会抛出 java.lang.IllegalMonitorStateException 异常,因为 doSomething() 方法在没有获取锁的情况下直接访问了共享资源。 四、预防与解决策略 为了避免这类异常,确保所有对共享资源的操作都遵循以下原则: 1. 始终锁定 在访问任何共享资源之前,务必先获得相应的锁。 2. 正确释放锁 在完成操作后,无论成功与否,都应确保释放锁。 3. 避免死锁 检查锁的顺序和持有锁的时间,防止出现死锁情况。 五、总结 java.lang.IllegalMonitorStateException 异常提醒我们在多线程编程中注意锁的使用,确保每次操作都处于安全的监视器状态。通过正确的锁管理实践,我们可以有效预防这类异常,并提高应用程序的稳定性和性能。哎呀,亲!在咱们做程序开发的时候,多线程编程那可是个大功臣!要想让咱们的系统跑得又快又稳,学好这个技术,不断摸索最佳实践,那简直就是必须的嘛!这不光能让程序运行效率翻倍,还能确保系统稳定,用户用起来也舒心。所以啊,小伙伴们,咱们得勤于学习,多加实践,让自己的技能库再添一把火,打造出既高效又可靠的神级系统!
2024-08-07 16:07:16
53
岁月如歌
转载文章
在Java编程中,ArrayList作为一种常用的动态数组实现,在实际项目开发与算法设计中扮演着重要角色。最近,随着Java 16的发布,集合框架中的优化措施以及对JDK新特性的支持,使得ArrayList等集合类的使用更加高效和便捷。例如,对于ArrayList的扩容机制,Java团队持续进行优化以减少在大量插入操作时的空间浪费和性能损耗。 同时,为了满足现代并发环境下的需求,开发者们需要注意ArrayList并非线程安全的数据结构,因此在多线程环境下推荐使用CopyOnWriteArrayList或者通过Collections.synchronizedList方法封装得到的安全版本。此外,深入探讨ArrayList与LinkedList之间的性能差异也至关重要,尤其是在涉及到频繁增删元素和随机访问场景下,选择合适的数据结构能显著提升程序性能。 进一步研究,ArrayList在实际应用场景中的拓展性不言而喻。近期,某大型电商系统在重构其用户订单处理模块时,就巧妙地运用了ArrayList结合HashSet实现了商品快速检索与订单状态变更的功能,充分展示了ArrayList在复杂业务逻辑中的灵活性。 另外,ArrayList作为基础数据结构在各类算法竞赛和面试题目中亦是常客,比如在LeetCode题库中,有多道题目需要利用ArrayList进行动态数组操作来解决问题。掌握ArrayList的底层原理和API特性,有助于开发者更好地应对各种编程挑战。 综上所述,理解并熟练运用ArrayList是每个Java开发者必备的技能之一,与时俱进地关注其最新发展动态和最佳实践案例,将有助于我们在实际开发中游刃有余、事半功倍。
2024-02-19 12:24:39
583
转载
Java
Java 开发之旅:Spring Boot 返回 JSP 无效——多模块、Web 启动项与 view.suffix 配置解析 一、引言 作为Java开发者,我们时常需要处理前后端分离的项目架构,其中Spring Boot以其简洁易用性和高度自动化的特点,成为了构建现代Web应用的理想选择。然而,在实际做开发的时候,特别是在捣鼓那些老派的JSP视图渲染,还有跨模块配置这些事儿,咱们有时会遇到一些让人挠头的问题。就比如这次提到的,你设置了spring.mvc.view.suffix这个参数却没见生效的情况,是不是挺让人头疼的?接下来,我们将深入剖析这个现象,并给出针对性的解决方案。 二、背景与问题描述 假设我们正在使用Spring Boot构建一个多模块的应用,其中一个模块专门负责Web服务提供,使用了Spring MVC作为控制器及其视图层的框架。为了让HTML模板与Java逻辑更加清晰地分隔,我们在项目的布局中采用了如下结构: 1. module-core: 应用的核心业务逻辑和服务模块 2. module-web: 启动项,主要包含Web相关的配置与控制层逻辑,依赖于module-core 3. module-views: 存放JSP视图文件,用于前端展示 在此场景下,为确保正确识别并加载JSP视图,我们需要在module-web的配置文件中指定JSP后缀名(spring.mvc.view.suffix),例如: properties spring: mvc: view: prefix: /WEB-INF/views/ suffix: .jsp 然而,当运行程序并尝试访问Controller中带有相关视图名称的方法(如@GetMapping("/home")映射到WEB-INF/views/homePage.jsp)时,浏览器却无法显示出预期的JSP页面内容,且并未抛出任何异常,而是默认返回了空响应或者错误状态码。 三、问题分析与排查 面对这一看似简单的配置失效问题,我们首先需要进行如下几个方面的排查: 1. 检查视图解析器配置 确保视图解析器org.springframework.web.servlet.view.InternalResourceViewResolver已被正确注册并设置了prefix与suffix属性。检查Spring Boot启动类(如WebMvcConfig.java或Application.java中的WebMvcConfigurer实现): java @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); registry.viewResolver(resolver); } } 2. 模块间依赖与资源路径映射 确认module-web是否正确引入了module-views的相关JSP文件,并指定了正确的资源路径。查看module-web的pom.xml或build.gradle文件中对视图资源模块的依赖路径: xml com.example module-views 1.0.0 war runtime classes // Gradle dependencies { runtimeOnly 'com.example:module-views:1.0.0' } 以及主启动类(如Application.java)中的静态资源映射配置: java @SpringBootApplication public class Application { @Bean TomcatServletWebServerFactory tomcat() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); factory.addContextCustomizer((TomcatWebServerContext context) -> { // 将模块视图目录映射到根URL下 context.addWelcomeFile("index.jsp"); WebResourceRoot resourceRoot = new TomcatWebResourceRoot(context, "static", "/"); resourceRoot.addDirectory(new File("src/main/resources/static")); context.setResources(resourceRoot); }); return factory; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } 3. 检查JSP引擎配置 确保Tomcat服务器配置已启用JSP支持。在module-web对应的application.properties或application.yml文件中配置JSP引擎: properties server.tomcat.jsp-enabled=true server.tomcat.jsp.version=2.3 或者在module-web的pom.xml或build.gradle文件中为Tomcat添加Jasper依赖: xml org.apache.tomcat.embed tomcat-embed-jasper provided // Gradle dependencies { implementation 'org.apache.tomcat.embed:tomcat-embed-jasper:9.0.54' } 4. 控制器与视图名称匹配验证 在完成上述配置后,请务必核实Controller中返回的视图名称与其实际路径是否一致。如果存在命名冲突或者拼写错误,将会导致Spring MVC无法找到预期的JSP视图: java @GetMapping("/home") public String home(Model model) { return "homePage"; // 视图名称应更改为"WEB-INF/views/homePage.jsp" } 四、总结与解决办法 综上所述,Spring Boot返回JSP无效的问题可能源于多个因素的叠加效应,包括但不限于视图解析器配置不完整、模块间依赖关系未正确处理、JSP引擎支持未开启、或Controller与视图名称之间的不对应等。要解决这个问题,需从以上几个方面进行逐一排查和修正。 切记,在面对这类问题时,要保持冷静并耐心地定位问题所在,仔细分析配置文件、源代码和日志输出,才能准确找出症结所在,进而成功解决问题。这不仅让我们实实在在地磨炼了编程功夫,更是让咱们对Spring Boot这家伙的工作内幕有了更深的洞察。这样一来,我们在实际项目中遇到问题时,调试和应对的能力都像坐火箭一样嗖嗖提升啦!
2024-02-17 11:18:11
271
半夏微凉_t
Python
...ulSoup库来解析HTML文档。以下是导入所需库的代码: python import requests from bs4 import BeautifulSoup 2. 发送HTTP请求 使用requests库的get方法向指定URL发送GET请求,获取返回的HTML文档。以下是发送HTTP请求的代码: python url = "https://www.xxx.com/基金列表" response = requests.get(url) 3. 解析HTML文档 使用BeautifulSoup库对获取的HTML文档进行解析,提取出我们需要的数据。以下是一个简单的解析HTML文档的例子: python soup = BeautifulSoup(response.text, 'html.parser') fund_list = soup.find_all('div', class_='fund-name') 找到所有基金名称所在的div元素 for fund in fund_list: print(fund.text) 打印出每个基金的名称 三、编写完整的Python爬虫程序 有了以上基础知识,我们就可以编写一个完整的Python爬虫程序了。以下是一个简单的例子,每天从某个网站上抓取基金的最新净值并打印出来: python import requests from bs4 import BeautifulSoup import datetime 定义要爬取的网址 url = "https://www.xxx.com/基金列表" while True: 发送HTTP请求 response = requests.get(url) 解析HTML文档 soup = BeautifulSoup(response.text, 'html.parser') fund_list = soup.find_all('div', class_='fund-name') for fund in fund_list: 提取基金名称和净值 name = fund.find('span', class_='fund-name').text value = fund.find('span', class_='value').text 格式化日期 date_str = datetime.datetime.now().strftime('%Y-%m-%d') 打印出每只基金的名称、净值和日期 print(f"{date_str}: {name} - {value}") 四、总结 通过本文的讲解,你应该已经了解到如何使用Python编写一个简单的基金每日爬取程序。这个啊,其实就是个最基础、最入门级别的小例子啦,真正实战中的爬虫程序,那可复杂多了,会碰到各种让人挠头的问题。比如说网站为了防止被爬取而设置的反爬机制,还有那种内容不是一次性加载完,而是随着你滚动页面慢慢出现的动态加载情况,这些都是实际开发中可能遇到的大挑战!但是,只要你把基本的Python编程技能学到手,再对网络爬虫有个大概摸底,你就完全有能力亲手写出一个符合自己需求的爬虫程序来。就像是学会了烹饪基础和食材知识,就能按照自己的口味炒出一盘好菜一样。
2023-04-21 09:18:01
96
星河万里-t
转载文章
...on 3.7 龙行 个人随笔 2019-6-6 3451 0评论 centos7版本默认安装的是python2.7,对于强迫症的我来说,忍受不了啊. 注意下,应为很多的依赖包基本命令什么的都是基于python2的,比如yum。所以旧版本不要删了,新旧可以共存 1.安装编译环境包(防止出现安装错误)yum install gcc-c++ gcc make cmake zlib-devel bzip2-devel openssl-devel ncurse-devel libffi-devel -y 2.在线下载Python3.7源码包进入tmp目录 cd /tmp 下载python3.7.3 wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz 3.解压并配置解压 tar Jxvf Python-3.7.3.tar.xz 进入python3.7.3目录 cd Python-3.7.3 创建目录 mkdir -p /usr/local/python3 配置(指定安装目录) ./configure --prefix=/usr/local/python3 --enable-optimizations 4. 编译及安装make && make install 5.更换系统默认Python版本 1).备份原系统旧版本pythonmv /usr/bin/python /usr/bin/python.bak mkdir /usr/bin/pip mv /usr/bin/pip /usr/bin/pip.bak 2).配置环境变量:创建新版本Python和pip的软链接ln -s /usr/local/python3/bin/python3.7 /usr/bin/python ln -s /usr/local/python3/bin/pip3 /usr/bin/pip 3).查看Python版本python -V 6.修改yum功能 因为yum的功能依赖Pyhon2,现在更改默认Python版本后会导致yum无法正常工作,所以进行以下3处修复 第1处:vim /usr/bin/yum 把最顶部的 改成:! /usr/bin/python2.7 第2处: vim /usr/libexec/urlgrabber-ext-down 把最顶部的 改成:! /usr/bin/python2.7 /usr/sbin/firewalld /usr/bin/firewall-cmd 这两个也改下 评论一下 赞助站长 赞助站长X 版权申明:此文如未标注转载均为本站原创,自由转载请表明出处《龙行博客》。 本文网址:https://www.liaotaoo.cn/243.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_39974223/article/details/110081791。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-23 10:44:41
284
转载
Dubbo
...巴巴开源的一个高性能Java RPC框架,一直备受青睐。不过嘛,在实际用起来的时候,服务一多啊,咱们就难免要跟分布式追踪系统打交道,各种问题接踵而至。这篇文章主要是想聊聊Dubbo怎么和Zipkin、Jaeger这些分布式追踪系统打交道,以及怎么优化它们的合作。我们会用一些真实的例子来说明,怎样才能更好地应对分布式追踪中遇到的各种问题。 1. 分布式追踪系统的重要性 首先,让我们来谈谈为什么需要分布式追踪系统。想想看,当你得照顾一大堆微服务组成的复杂系统时,每个请求都像是个大冒险,得穿梭在好几个服务之间打交道。在这种情况下,要准确地定位问题所在变得极其困难。而分布式追踪系统就像一双眼睛,能够帮助我们清晰地看到每一次请求的完整路径,包括它经过了哪些服务、耗时多少、是否有错误发生等关键信息。这对于提升系统性能、快速定位故障以及优化用户体验都至关重要。 2. Dubbo集成分布式追踪系统的初步探索 Dubbo本身并不直接支持分布式追踪功能,但可以通过集成第三方工具来实现这一目标。比如说Zipkin吧,这是Twitter推出的一个开源工具,专门用来追踪应用程序在分布式环境中的各种请求路径和数据流动情况。用它就像是给你的系统搭建了一个超级详细的导航地图,让你能一眼看清楚每个请求走过了哪些地方。接下来,我们将通过几个步骤来演示如何在Dubbo项目中集成Zipkin。 2.1 添加依赖 首先,我们需要向项目的pom.xml文件中添加Zipkin客户端的依赖。这步超级重要,因为得靠它让我们的Dubbo服务乖乖地把追踪信息发给Zipkin服务器,不然出了问题我们可找不到北啊。 xml io.zipkin.java zipkin-reporter-brave 2.7.5 2.2 配置Dubbo服务端 然后,在Dubbo服务端配置文件(如application.properties)中加入必要的配置项,让其知道如何连接到Zipkin服务器。 properties dubbo.application.qos-enable=false dubbo.registry.address=multicast://224.5.6.7:1234 指定Zipkin服务器地址 spring.zipkin.base-url=http://localhost:9411/ 使用Brave作为追踪库 brave.sampler.probability=1.0 这里,spring.zipkin.base-url指定了Zipkin服务器的URL,而brave.sampler.probability=1.0则表示所有请求都会被追踪。 2.3 编写服务接口与实现 假设我们有一个简单的服务接口,用于处理用户订单: java public interface OrderService { String placeOrder(String userId); } 服务实现类如下: java @Service("orderService") public class OrderServiceImpl implements OrderService { @Override public String placeOrder(String userId) { // 模拟业务逻辑 System.out.println("Order placed for user: " + userId); return "Your order has been successfully placed!"; } } 2.4 启动服务并测试 完成上述配置后,启动Dubbo服务端。你可以试试调用placeOrder这个方法,然后看看在Zipkin的界面上有没有出现相应的追踪记录。 3. 深入探讨 从Dubbo到Jaeger的转变 虽然Zipkin是一个优秀的解决方案,但在某些场景下,你可能会发现它无法满足你的需求。例如,如果你需要更高级别的数据采样策略或是对追踪数据有更高的控制权。这时,Jaeger就成为一个不错的选择。Jaeger是Uber开源的分布式追踪系统,它提供了更多的定制选项和更好的性能表现。 将Dubbo与Jaeger集成的过程与Zipkin类似,主要区别在于依赖库的选择和一些配置细节。这里就不详细展开,但你可以按照类似的思路去尝试。 4. 结语 持续优化与未来展望 集成分布式追踪系统无疑为我们的Dubbo服务增添了一双“慧眼”,使我们能够在复杂多变的分布式环境中更加从容不迫。然而,这只是一个开始。随着技术日新月异,咱们得不停地充电,学些新工具新技能,才能跟上这变化的脚步嘛。别忘了时不时地检查和调整你的追踪方法,确保它们跟得上你生意的发展步伐。 希望这篇文章能为你提供一些有价值的启示,让你在Dubbo与分布式追踪系统的世界里游刃有余。记住,每一次挑战都是成长的机会,勇敢地迎接它们吧!
2024-11-16 16:11:57
54
山涧溪流
转载文章
...P60)【优极限】 HTML+CSS+JavaScript+jQuery前端必学教程,小白教学,前端基础全套完成版_哔哩哔哩_bilibili 菜鸟教程网址:HTML 教程 | 菜鸟教程 (runoob.com) 一、获取表单 <!-- 获取表单(前两种常用)1. document.getElementById("id属性值");通过form标签的id属性值获取表单对象2.document.表单的nane属性值:通过表单的name属性值获取表单对象3.document.forms[下标]: 通过指定下标获取表单元素4.document.forms[表单的name属性值];通过表单的name属性值获取表单对象document.forms:获取HTML文档中所有的表单对象--> <form id="myform1" name= "myform1" action=""></form><form id="myform2" name= "myform2" action=""></form><script type="text/javascript">// 1. document.getElementById("id属性值");console.log(document.getElementById("myform1"));// 2. document.表单的name属性值; console.log(document.myform2);console.log("----------------");//获取所有的表单对象console.log(document.forms); // 3. document.forms[下标];console.log(document.forms[0]);// 4. document.forms[表单的name属性值]; console.log(document.forms["myform2"]);</script> 运行效果截图: 二、获取表单元素 获取表单元素1.获取input元素1. document.getElementById("id属性值"): 通过元素的id属性值获取表单元素对象2.表单对象.表单元素的name属性值;通过表单对象中对应的元素的name属性值获取3. document.getELementsByName("name属性值");通过表单元素的name属性值获取4. document.getELementsByTagName("标签名/元素名");通过标签名获取表单元素对象2.获取单选按钮注:相同的一组单选按钮,需要设置相同的name属性值1. document.getElementByName("name属性值");通过name属性值获取2.判断单选按钮是否选中checked选中状态在JS代码中checked=true表示选中checked=false表示不选中在HTML标签中checked=checked或checked表示选中不设置checked属性表示不选中3.获取单选按钮的值元表.value;3.获取多选按钮与单选按钮相同4.获取下拉选项1.获取下拉框对象var对象 = document.getElementById("id属性值");2.获取下拉框的下拉选项列表var options = 下拉框对象.options;3.获取下拉框被选中项的索引var index = 下拉框对象.selectedIndex;4.获取下拉框被选中项的值var 值 = 下拉框对象.value;5.通过选中项的下标获取下拉框被选中项的值var 值 = 下拉框对象.options[index].value;6.获取下拉框被选中项的文本var文本值一下拉框对象.options[index].text;注:1.获取下拉框选中项的值时: (value)如果option标签设置了value属性值,则获取value属性对应的值;如果option标签未设置value属性值,则获取的是option双标签中的文本值2.下拉框的选中状态:选中状态: selected = selected、 selected、 selected = true未选中状态:不设置selected属性、 selected=false; <form id='myform' name="myform" action="" method="get">姓名:<input type="text" id="uname" name="uname" value="zs"/><br />密码:<input type= "password" id="upwd" name="upwd" value= "1234"/><br /><input type="hidden" id= "uno" name="uno" value="隐藏域"/>个人说明:<textarea name="intro" ></textarea><br><button type="button" onclick="getTxt();" >获取元素内容</button><hr><br><input type="text" name="inputName" class="test" value="aaa" /><input type="radio" name="rad" class="test" value="1" /> 男<input type="radio" name="rad" class="test" value="2" /> 女<button type="button" onclick="getRadio()">获取单选按钮</button><br><hr><br>全选/全不选: <input type="checkbox" id="control" onclick="checkAllOrNot()" /><button type="button" onclick= "checkFan()">反选</button><br><input type="checkbox" name= "hobby" value="sing" />唱歌<input type="checkbox" name= "hobby" value="dance" />跳舞<input type="checkbox" name= "hobby" value="rap" />说唱<button type="button" onclick="getCheckBox()">获取多选按钮</button><br><hr><br>来自:<select id="ufrom" name= "ufrom" ><option value = "" >请选择</option><option value = "Beijing" selected="selected" >北京</option><option value = "Shanghai">上海</option><option value = "Hangzhou">杭州</option></select><button type="button" onclick= "getSelect()" >获取下拉选项</button></form><script type=" text/javascript">function getTxt() {// 1. document.getElementById("id属性值");var uname = document.getElementById("uname").value;console.log(uname);// 2.表单对象.表单元表的name属性值;var pwd = document.getElementById("myform").upwd.value;console.log(pwd);// 3. document.getELementsByName("name属性值");var uno = document.getElementsByName("uno")[0].value;console.log(uno);// 4. document.getELementsByTagName("标签名/元素名");var intro = document.getElementsByTagName("textarea")[0].value;console.log(intro);}function getSelect() {//获取下拉框对象var ufrom = document.getElementById("ufrom");console.log(ufrom);//获取下拉框的下拉选项列表var opts = ufrom.options;console.log(opts);//获取下拉框被选中项的索引var index = ufrom.selectedIndex;console.log("选中项的下标:" + index);//获取下拉框被选中项的值var val = ufrom.value;console.log("被选中项的值:" + val);//通过选中项的下标获取下拉框被选中项的值var val2 = ufrom.options[index].value;console.log("被选中项的值:"+ val2);//获取下拉框被选中项的文本var txt=ufrom.options[index].text; console.log("被选中项的文本:"+ txt);}</script> 运行效果截图: 三、提交表单 提交表单一、使用普通按钮type="button"1.给按钮绑定click点击事件,绑定函数2.在函数中,进行表单校验(非空校验、 合法性校验等)3.如果校验通过,则手动提交表单表单对象.submit();二、使用提交按钮type="submit"1.给按钮绑定click点击事件,绑定函数2.函数需要有返回值,返回true或false (如果return false, 则表单不会提交:如果return true,则提交表单)onclick="return 函数名()"3.在函数中,进行表单校验(非空校验、 合法性校验等)4.如果校验通过,返回true;如果校验不通过,则返回false, 则表单不会提交:如果return true,则提交表单)三、使用提交按钮type="submit"1.给表单form元素绑定submit提交事件,绑定函数2.函数需要有返回值,返回true或false (如果return false, 则表单不会提交;如果return trueonsubmit="return函数名()" 3.在函数中,进行表单校验(非空校验、 合法性校验等)4.如果校验通过,返回true;如果校验不通过,则返回false <!--使用普逍按钮 type= "button"--><form id= 'myform' name= "myform" action="http://www.baidu.com" method="get" >姓名: <input name= "uname" id="uname"/> <span id = "msg" style="font-s1ze: 12px; color: red;"></span><br /><button type="button" onclick="submitForm1()">提交</button></form><!--使用提交按钮 type= "submit"--><form id= 'myform2' name= "myform2" action="http://www.baidu.com" method="get" >姓名: <input name= "uname2" id="uname2"/> <span id = "msg2" style="font-s1ze: 12px; color: red;"></span><br /><button type="submit" onclick="return submitForm2()">提交</button></form><!--使用提交按钮 type= "submit"--><form id= 'myform3' name= "myform3" action="http://www.baidu.com" method="get" onsubmit="return submitForm3()">姓名: <input name= "uname3" id="uname3"/> <span id = "msg3" style="font-s1ze: 12px; color: red;"></span><br /><button type="submit">提交</button></form><script type="text/javascript">// 表单校验// 提交表单function submitForm1() {//得到文本框的值var uname = document.getElementById("uname").value;//判断是否为空if (isEmpty(uname)) { //为空//设置提示信息(设置span元素的值)document.getElementById("msg").innerHTML="性名不能为空!" ;//阻止表单提交return;}//手动提交表单document.getElementById("myform").submit(); }function submitForm2() {//得到文本框的值var uname2 = document.getElementById("uname2").value;//判断是否为空if (isEmpty(uname2)) { //为空//设置提示信息(设置span元素的值)document.getElementById("msg2").innerHTML="性名不能为空!" ;//阻止表单提交return false;}return true;}function submitForm3() {//得到文本框的值var uname3 = document.getElementById("uname3").value;//判断是否为空if (isEmpty(uname3)) { //为空//设置提示信息(设置span元素的值)document.getElementById("msg3").innerHTML="性名不能为空!" ;//阻止表单提交return false;}return true;}/ 判断字符串是否为空如果为空,返回true如果非空,返回falsetrim() :字符串方法, 去除字符串前后空格@param {Object} str/function isEmpty(str) {//判断是否为空if (str == null || str.trim() == "") {return true;}return false;}</script> 运行效果截图: 四、原生Ajax实现流程 <!-- Ajax 异步无刷新技术原生Ajax的实现流程1.得到XMLHttpRequest对象var xhr = new XMLHttpRequest();2.打开请求xhr.open(method, uri, async) ;method:请求方式,通常是GEI|POSTurl:请求地址async:是否异步。如果是true表示异步,false表示同步3.发送请求xhr.send(params);params:请求时需要传递的参数如果是GET请求,设置nu11。 (GET请求的参数设置在url后面)如果是POST请求,无参数设置为null,有参数则设置参数4.接收响应xhr.status响应状态(200=响应成功, 404=资源末找到,500=服务器异常)xhr.responseText 得到响应结果 --> <script type="text/javascript">// 同步请求function text01() {// 1.得到XMLHttpRequest对象var xhr = new XMLHttpRequest();// 2.打开请求xhr.open("get", "js/date.json", false);// 3.发送请求xhr.send(null);// 4.判断响应状态if (xhr.status == 200) {console.log("响应成功");} else {console.log("状态码:" + xhr.status + ",原因:" + xhr.responseText)}console.log("同步请求...");}text01();// 异步请求function text02() {// 1.得到XMLHttpRequest对象var xhr = new XMLHttpRequest();// 2.打开请求xhr.open("get", "js/date.json", true);// 3.发送请求xhr.send(null);// 由于是异步请求,所以需要知道后台已经将请求处理完毕,才能获取响应结果// 遇过监听readyState的变化来得知后面的处理状态 4=完全处理xhr.onreadystatechange = function(){if(xhr.readyState == 4){// 4.判断响应状态if (xhr.status == 200) {// 得到响应结果 console.log(xhr.responseText);} else {console.log("状态码:" + xhr.status + ",原因:" + xhr.responseText)} }}console.log("异步请求...");}text02();</script> 运行效果截图: 本篇文章为转载内容。原文链接:https://blog.csdn.net/m0_61507413/article/details/122895643。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-22 17:32:41
521
转载
转载文章
...应内容。 最近在学习java的爬虫技术,学的是黑马的视频资源,由于是几年前的视频啦,京东页面有些许变化,在此记录我遇到的问题,使用的爬虫技术是httpClient和jsoup,项目搭建使用的springboot+ jpa。 首先给出主页的代码: @Componentpublic classItemTask { @AutowiredprivateHttpUtils httpUtils; @AutowiredprivateItemService itemService;public static final ObjectMapper MAPPER = newObjectMapper();//设置定时任务执行完成后,再间隔100秒执行一次 @Scheduled(fixedDelay = 1000 100)public void process() throwsException {//分析页面发现访问的地址,页码page从1开始,下一页page加2 String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&suggest=1.his.0.0&wq=%E6%89%8B%E6%9C%BA&s=121&click=0&page=";//遍历执行,获取所有的数据 for (int i = 1; i < 10; i = i + 2) {//发起请求进行访问,获取页面数据,先访问第一页 String html = this.httpUtils.getHtml(url +i);//解析页面数据,保存数据到数据库中 this.parseHtml(html); } System.out.println("执行完成"); }//解析页面,并把数据保存到数据库中 private void parseHtml(String html) throwsException {//使用jsoup解析页面 Document document =Jsoup.parse(html);//获取商品数据 Elements spus = document.select("divJ_goodsList > ul > li");//遍历商品spu数据 for(Element spuEle : spus) {//获取商品spu String attr = spuEle.attr("data-spu");long spu = Long.parseLong(attr.equals("")?"0":attr);//Long spu = Long.parseLong(spuEle.attr("data-spu"));//获取商品sku数据 Elements skus = spuEle.select("li.ps-item img");for(Element skuEle : skus) {//获取商品sku Long sku = Long.parseLong(skuEle.attr("data-sku"));//判断商品是否被抓取过,可以根据sku判断 Item param = newItem(); param.setSku(sku); List list = this.itemService.findAll(param);//判断是否查询到结果 if (list.size() > 0) {//如果有结果,表示商品已下载,进行下一次遍历 continue; }//保存商品数据,声明商品对象 Item item = newItem();//商品spu item.setSpu(spu);//商品sku item.setSku(sku);//商品url地址 item.setUrl("https://item.jd.com/" + sku + ".html");//创建时间 item.setCreated(newDate());//修改时间 item.setUpdated(item.getCreated());//获取商品标题 String itemHtml = this.httpUtils.getHtml(item.getUrl()); String title= Jsoup.parse(itemHtml).select("div.sku-name").text(); item.setTitle(title);//获取商品价格 String priceUrl = "https://p.3.cn/prices/mgets?skuIds=J_"+sku; String priceJson= this.httpUtils.getHtml(priceUrl);//解析json数据获取商品价格 double price = MAPPER.readTree(priceJson).get(0).get("p").asDouble(); item.setPrice(price);//获取图片地址 String pic = "https:" + skuEle.attr("data-lazy-img").replace("/n9/","/n1/"); System.out.println(pic);//下载图片 String picName = this.httpUtils.getImage(pic); item.setPic(picName);//保存商品数据 this.itemService.save(item); } } } } 分享一下我学习中遇到的问题: 1.爬取数据为null,需要登录京东 看到这段代码应该就明白了吧,就是京东发现并非人为操作,需要登陆账号了。解决办法也很简单,只需要自己模拟浏览器登陆即可 在HttpUttils加上这段,两个方法中的HTTPGet对象都需要设置一下。 //设置请求头模拟浏览器 httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0"); 2.java.lang.NumberFormatException: For input string: "",获取的spu为空串,加上一个前置空串判断即可 解决如下: //获取商品spu String attr = spuEle.attr("data-spu");//判断是否为空串 long spu = Long.parseLong(attr.equals("")?"0":attr); 以上两个bug是我学习遇到的,现已解决,爬取数据如下: 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_32161697/article/details/114506244。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-13 10:48:12
104
转载
转载文章
...-14179038.html >>> a = [1, 2, 3, 4, 5]>>> np.pad(a, (2, 3), 'reflect')array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2]) 个人感觉使用reflect操作,而不是之间的填充0是为了在边缘去噪的时候更平滑一些。镜像填充后的图如下: 输入网络后,得到预测结果。最后进行裁剪,得到去噪后的图像。 prediction = prediction[:, :, :H, :W] 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_42948594/article/details/124712116。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-06-13 14:44:26
128
转载
转载文章
...d.png') 执行JavaScript语句 执行JavaScript语句driver.execute_script('window.scrollTo(0,0);')执行js的api,通过js来操作滚动条,滚动到最上面 关闭与退出: 当开启多个页面时,关闭当前页面driver.close()退出并关闭所有页面驱动driver.quit() from selenium import webdriverdriver=webdriver.Chrome()driver.get("http://ui.imdsx.cn/uitester/")driver.maximize_window()将窗口放大driver.execute_script('window.scrollTo(0,0);')执行js的apidriver.find_element_by_css_selector('[href="/new-index/"]').click()handles=driver.window_handles返回所有打开server的浏览器句柄print(handles)返回listdriver.switch_to.window(handles[1])driver.find_element_by_css_selector('newtag').send_keys(1111)找到新页面上的元素driver.close()关闭当前tab页 from selenium import webdriverdriver=webdriver.Chrome()driver.get("http://ui.imdsx.cn/uitester/")driver.maximize_window()将窗口放大driver.execute_script('window.scrollTo(0,0);')执行js的apidriver.find_element_by_css_selector('[href="/new-index/"]').click()handles=driver.window_handlesprint(handles)driver.switch_to.window(handles[1])driver.find_element_by_css_selector('newtag').send_keys(1111)driver.quit() 关闭所有页面,结束服务 其他 返回页面源码driver.page_source 返回tag标题driver.title 返回当前Urldriver.current_url 获取浏览器名称 如:chromedriver.name ElementApi接口 根据标签属性名称,获取属性valueelement.get_attribute('style') 向输入框输入字符串 如果input的type为file类型 可以输入文件绝对路径上传文件element.send_keys() 清除文本内容element.clear() 鼠标左键点击操作element.click() 通过属性名称获取属性element.get_property('id') 返回元素是否可见 True or Falseelement.is_displayed() 返回元素是否被选中 True or Falseelement.is_selected() 返回标签元素的名字element.tag_name 获取当前标签的宽和高element.size 获取元素的文本内容element.text 模仿回车按钮 提交数据element.submit() 获取当前元素的坐标element.location 截取图片element.screenshot() from selenium import webdriverdriver=webdriver.Chrome()driver.get("http://ui.imdsx.cn/uitester/")driver.maximize_window()将窗口放大driver.execute_script('window.scrollTo(0,0);')执行js的apie=driver.find_element_by_css_selector('i1')e.send_keys(1111)import timetime.sleep(1)e.clear() 清除文本框内内容 转载于:https://www.cnblogs.com/wxcx/p/8934540.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_34377065/article/details/94686128。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-03 12:51:11
45
转载
转载文章
...极了。 题外话:就我个人而言,掌握一门技术并合理使用它的最好办法就是深入理解这项技术背后的工作原理。通常情况 下,一项新技术的诞生常常会伴随着媒体的大肆宣传和炒作,这使得用户很难看清技术的本质。更确切地说,新技术总是会发明一些新的术语或者隐喻词来帮助宣 传,这在初期是非常有帮助的,但是这给技术的原理蒙上了一层砂纸,不利于用户在后期掌握技术的真谛。 Git就是一个很好的例子。我之前不能够很好的使用Git,于是我花了一段时间去学习Git的原理,直到这时,我才真正明白了Git的用法。我坚信只有真正理解Git内部原理的人才能够掌握这个工具。 Image Definition 镜像(Image)就是一堆只读层(read-only layer)的统一视角,也许这个定义有些难以理解,下面的这张图能够帮助读者理解镜像的定义。 从左边我们看到了多个只读层,它们重叠在一起。除了最下面一层,其它层都会有一个指针指向下一层。这些层是Docker内部的实现细节,并且能够 在主机(译者注:运行Docker的机器)的文件系统上访问到。统一文件系统(union file system)技术能够将不同的层整合成一个文件系统,为这些层提供了一个统一的视角,这样就隐藏了多层的存在,在用户的角度看来,只存在一个文件系统。 我们可以在图片的右边看到这个视角的形式。 你可以在你的主机文件系统上找到有关这些层的文件。需要注意的是,在一个运行中的容器内部,这些层是不可见的。在我的主机上,我发现它们存在于/var/lib/docker/aufs目录下。 sudo tree -L 1 /var/lib/docker/ /var/lib/docker/├── aufs├── containers├── graph├── init├── linkgraph.db├── repositories-aufs├── tmp├── trust└── volumes7 directories, 2 files Container Definition 容器(container)的定义和镜像(image)几乎一模一样,也是一堆层的统一视角,唯一区别在于容器的最上面那一层是可读可写的。 细心的读者可能会发现,容器的定义并没有提及容器是否在运行,没错,这是故意的。正是这个发现帮助我理解了很多困惑。 要点:容器 = 镜像 + 可读层。并且容器的定义并没有提及是否要运行容器。 接下来,我们将会讨论运行态容器。 Running Container Definition 一个运行态容器(running container)被定义为一个可读写的统一文件系统加上隔离的进程空间和包含其中的进程。下面这张图片展示了一个运行中的容器。 正是文件系统隔离技术使得Docker成为了一个前途无量的技术。一个容器中的进程可能会对文件进行修改、删除、创建,这些改变都将作用于可读写层(read-write layer)。下面这张图展示了这个行为。 我们可以通过运行以下命令来验证我们上面所说的: docker run ubuntu touch happiness.txt 即便是这个ubuntu容器不再运行,我们依旧能够在主机的文件系统上找到这个新文件。 find / -name happiness.txt /var/lib/docker/aufs/diff/860a7b...889/happiness.txt Image Layer Definition 为了将零星的数据整合起来,我们提出了镜像层(image layer)这个概念。下面的这张图描述了一个镜像层,通过图片我们能够发现一个层并不仅仅包含文件系统的改变,它还能包含了其他重要信息。 元数据(metadata)就是关于这个层的额外信息,它不仅能够让Docker获取运行和构建时的信息,还包括父层的层次信息。需要注意,只读层和读写层都包含元数据。 除此之外,每一层都包括了一个指向父层的指针。如果一个层没有这个指针,说明它处于最底层。 Metadata Location: 我发现在我自己的主机上,镜像层(image layer)的元数据被保存在名为”json”的文件中,比如说: /var/lib/docker/graph/e809f156dc985.../json e809f156dc985...就是这层的id 一个容器的元数据好像是被分成了很多文件,但或多或少能够在/var/lib/docker/containers/<id>目录下找到,<id>就是一个可读层的id。这个目录下的文件大多是运行时的数据,比如说网络,日志等等。 全局理解(Tying It All Together) 现在,让我们结合上面提到的实现细节来理解Docker的命令。 docker create <image-id> docker create 命令为指定的镜像(image)添加了一个可读写层,构成了一个新的容器。注意,这个容器并没有运行。 docker start <container-id> Docker start命令为容器文件系统创建了一个进程隔离空间。注意,每一个容器只能够有一个进程隔离空间。 docker run <image-id> 看到这个命令,读者通常会有一个疑问:docker start 和 docker run命令有什么区别。 从图片可以看出,docker run 命令先是利用镜像创建了一个容器,然后运行这个容器。这个命令非常的方便,并且隐藏了两个命令的细节,但从另一方面来看,这容易让用户产生误解。 题外话:继续我们之前有关于Git的话题,我认为docker run命令类似于git pull命令。git pull命令就是git fetch 和 git merge两个命令的组合,同样的,docker run就是docker create和docker start两个命令的组合。 docker ps docker ps 命令会列出所有运行中的容器。这隐藏了非运行态容器的存在,如果想要找出这些容器,我们需要使用下面这个命令。 docker ps –a docker ps –a命令会列出所有的容器,不管是运行的,还是停止的。 docker images docker images命令会列出了所有顶层(top-level)镜像。实际上,在这里我们没有办法区分一个镜像和一个只读层,所以我们提出了top-level 镜像。只有创建容器时使用的镜像或者是直接pull下来的镜像能被称为顶层(top-level)镜像,并且每一个顶层镜像下面都隐藏了多个镜像层。 docker images –a docker images –a命令列出了所有的镜像,也可以说是列出了所有的可读层。如果你想要查看某一个image-id下的所有层,可以使用docker history来查看。 docker stop <container-id> docker stop命令会向运行中的容器发送一个SIGTERM的信号,然后停止所有的进程。 docker kill <container-id> docker kill 命令向所有运行在容器中的进程发送了一个不友好的SIGKILL信号。 docker pause <container-id> docker stop和docker kill命令会发送UNIX的信号给运行中的进程,docker pause命令则不一样,它利用了cgroups的特性将运行中的进程空间暂停。具体的内部原理你可以在这里找到:https://www.kernel.org/doc/Doc ... m.txt,但是这种方式的不足之处在于发送一个SIGTSTP信号对于进程来说不够简单易懂,以至于不能够让所有进程暂停。 docker rm <container-id> docker rm命令会移除构成容器的可读写层。注意,这个命令只能对非运行态容器执行。 docker rmi <image-id> docker rmi 命令会移除构成镜像的一个只读层。你只能够使用docker rmi来移除最顶层(top level layer)(也可以说是镜像),你也可以使用-f参数来强制删除中间的只读层。 docker commit <container-id> docker commit命令将容器的可读写层转换为一个只读层,这样就把一个容器转换成了不可变的镜像。 docker build docker build命令非常有趣,它会反复的执行多个命令。 我们从上图可以看到,build命令根据Dockerfile文件中的FROM指令获取到镜像,然后重复地1)run(create和start)、2)修改、3)commit。在循环中的每一步都会生成一个新的层,因此许多新的层会被创建。 docker exec <running-container-id> docker exec 命令会在运行中的容器执行一个新进程。 docker inspect <container-id> or <image-id> docker inspect命令会提取出容器或者镜像最顶层的元数据。 docker save <image-id> docker save命令会创建一个镜像的压缩文件,这个文件能够在另外一个主机的Docker上使用。和export命令不同,这个命令为每一个层都保存了它们的元数据。这个命令只能对镜像生效。 docker export <container-id> docker export命令创建一个tar文件,并且移除了元数据和不必要的层,将多个层整合成了一个层,只保存了当前统一视角看到的内容(译者注:expoxt后 的容器再import到Docker中,通过docker images –tree命令只能看到一个镜像;而save后的镜像则不同,它能够看到这个镜像的历史镜像)。 docker history <image-id> docker history命令递归地输出指定镜像的历史镜像。 参考: http://www.cnblogs.com/bethal/p/5942369.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/u010098331/article/details/53485539。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-11-26 15:47:20
538
转载
转载文章
...m_pytorch.html ps: TVM supports PyTorch 1.7 and 1.4. Other versions may be unstable.import tvmfrom tvm import relayfrom tvm.contrib.download import download_testdataimport numpy as np PyTorch importsimport torchimport torchvision Load a pretrained PyTorch model -------------------------------model_name = "resnet18"model = getattr(torchvision.models, model_name)(pretrained=True) or model = torchvision.models.resnet18(pretrained=True) or pth_file = 'resnet18-f37072fd.pth' model = torchvision.models.resnet18() ckpt = torch.load(pth_file) model.load_state_dict(ckpt)model = model.eval() We grab the TorchScripted model via tracinginput_shape = [1, 3, 224, 224]input_data = torch.randn(input_shape)scripted_model = torch.jit.trace(model, input_data).eval() Load a test image ----------------- Classic cat example!from PIL import Image img_url = "https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true" img_path = download_testdata(img_url, "cat.png", module="data")img_path = 'cat.png'img = Image.open(img_path).resize((224, 224)) Preprocess the image and convert to tensorfrom torchvision import transformsmy_preprocess = transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])img = my_preprocess(img)img = np.expand_dims(img, 0) Import the graph to Relay ------------------------- Convert PyTorch graph to Relay graph. The input name can be arbitrary.input_name = "input0"shape_list = [(input_name, img.shape)]mod, params = relay.frontend.from_pytorch(scripted_model, shape_list) Relay Build ----------- Compile the graph to llvm target with given input specification.target = tvm.target.Target("llvm", host="llvm")dev = tvm.cpu(0)with tvm.transform.PassContext(opt_level=3):lib = relay.build(mod, target=target, params=params) Execute the portable graph on TVM --------------------------------- Now we can try deploying the compiled model on target.from tvm.contrib import graph_executordtype = "float32"m = graph_executor.GraphModule(lib["default"](dev)) Set inputsm.set_input(input_name, tvm.nd.array(img.astype(dtype))) Executem.run() Get outputstvm_output = m.get_output(0) Look up synset name ------------------- Look up prediction top 1 index in 1000 class synset. synset_url = "".join( [ "https://raw.githubusercontent.com/Cadene/", "pretrained-models.pytorch/master/data/", "imagenet_synsets.txt", ] ) synset_name = "imagenet_synsets.txt" synset_path = download_testdata(synset_url, synset_name, module="data") https://raw.githubusercontent.com/Cadene/pretrained-models.pytorch/master/data/imagenet_synsets.txtsynset_path = 'imagenet_synsets.txt'with open(synset_path) as f:synsets = f.readlines()synsets = [x.strip() for x in synsets]splits = [line.split(" ") for line in synsets]key_to_classname = {spl[0]: " ".join(spl[1:]) for spl in splits} class_url = "".join( [ "https://raw.githubusercontent.com/Cadene/", "pretrained-models.pytorch/master/data/", "imagenet_classes.txt", ] ) class_name = "imagenet_classes.txt" class_path = download_testdata(class_url, class_name, module="data") https://raw.githubusercontent.com/Cadene/pretrained-models.pytorch/master/data/imagenet_classes.txtclass_path = 'imagenet_classes.txt'with open(class_path) as f:class_id_to_key = f.readlines()class_id_to_key = [x.strip() for x in class_id_to_key] Get top-1 result for TVMtop1_tvm = np.argmax(tvm_output.numpy()[0])tvm_class_key = class_id_to_key[top1_tvm] Convert input to PyTorch variable and get PyTorch result for comparisonwith torch.no_grad():torch_img = torch.from_numpy(img)output = model(torch_img) Get top-1 result for PyTorchtop1_torch = np.argmax(output.numpy())torch_class_key = class_id_to_key[top1_torch]print("Relay top-1 id: {}, class name: {}".format(top1_tvm, key_to_classname[tvm_class_key]))print("Torch top-1 id: {}, class name: {}".format(top1_torch, key_to_classname[torch_class_key])) 2. 配置vscode 安装两个vscode远程连接所需的两个插件,具体如下图所示: 安装完成之后,在左侧工具栏会出现一个图标,点击图标进行ssh配置: ssh yourname@yourip -A 然后右键选择在当前窗口进行连接: 除此之外,还可以设置免费登录,具体可参考这篇文章。 当然,也可以使用windows本地的WSL2,vscode连接WSL还需要安装WSL和Dev Containers这两个插件。 在服务器端执行code .会自动安装vscode server,安装位置在用户的根目录下: 3. 安装FFI Navigator 由于TVM是由Python和C++混合开发,且大多数的IDE仅支持在同一种语言中查找函数定义,因此对于跨语言的FFI 调用,即Python跳转到C++或者C++跳转到Python,vscode是做不到的。虽然解决这个问题在技术上可能非常具有挑战性,但我们可以通过构建一个与FFI注册码模式匹配并恢复必要信息的项目特定分析器来解决这个问题,FFI Navigator就这样诞生了,作者仍然是陈天奇博士。 安装方式如下: 建议使用源码安装git clone https://github.com/tqchen/ffi-navigator.git 安装python依赖cd ffi-navigator/pythonpython setyp.py install vscode需要安装FFI Navigator插件,直接搜索安装即可(安装到服务器端)。 最后需要在.vscode/setting.json进行配置,内容如下: {"python.analysis.extraPaths": ["${workspaceFolder}/python"], // 添加额外导入路径, 告诉pylance自定义的python库在哪里"ffi_navigator.pythonpath": "/home/liyanpeng/anaconda3/envs/tvmenv/bin/python", // 配置FFI Navigator"python.defaultInterpreterPath": "/home/liyanpeng/anaconda3/envs/tvmenv/bin/python","files.associations": {"type_traits": "cpp","fstream": "cpp","thread": "cpp",".tcc": "cpp"} } 更详细内容可以参考项目链接。 结束语 对于vscode的使用技巧及C/C++相关的配置,这里不再详细的介绍了,感兴趣的小伙伴们可以了解下。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_42730750/article/details/126723224。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-12 20:04:26
87
转载
转载文章
...e.js 作者尤雨溪开发的现代化前端构建工具,它利用浏览器原生的 ES 模块导入功能实现快速热更新和按需编译,显著提升了开发者的工作效率。在本文中,作者使用 Vite 配合 Vue3 和 TypeScript 进行项目搭建,并通过引入相应的插件支持 tsx 语法糖。 TailwindCSS , TailwindCSS 是一种实用的原子化 CSS 框架,采用实用类名(utility-first)的方法为开发者提供了一系列预设的样式类,可快速应用于 HTML 元素以实现响应式布局、间距调整、颜色定制等常见样式需求。在该文章中,作者推荐了 TailwindCSS 用于后台管理系统项目的样式构建,以降低编写 CSS 样式的复杂度,提高开发效率。 Pinia , Pinia 是专为 Vue3 设计的状态管理库,用于在大型或复杂应用中管理和共享组件之间的状态数据。相较于 Vuex,Pinia 在设计上更加简洁易用,提供了灵活且强大的状态管理解决方案。在模板项目中,作者集成了 Pinia 来帮助团队成员更好地组织和维护应用中的全局状态与逻辑。 Jest , Jest 是一个流行的 JavaScript 测试框架,具有丰富的断言库和模拟功能,能够支持单元测试、集成测试等多种测试场景。在文中,作者配置了 Jest 作为项目的单元测试工具,确保代码质量与稳定性,通过编写测试用例来验证代码逻辑的正确性以及预期功能的实现。 Eslint 和 Prettier , Eslint 是一款静态代码检查工具,用于识别并报告 JavaScript 和 TypeScript 代码中的潜在错误、不一致性和不良编码习惯;Prettier 则是一款代码格式化工具,可以自动按照一套统一的规则格式化代码,确保团队间的代码风格一致性。在这篇文章中,作者介绍了如何结合 Eslint 和 Prettier 设置项目规范,以提升代码质量和团队协作效率。
2023-10-05 12:27:41
116
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
fg %jobnumber
- 将后台作业切换至前台运行。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"