两个用户登录,session id问题

据我现在的知识来说,session是针对浏览器的,对于不同的浏览器,服务器会创建不同的sesionid。
我想问一下,如果是同一个浏览器,一开始是a用户登陆,这时服务器会创建一个sessionid(这里
会把sessionid存储到cookie中)。此时a用户退出,cookie中还是保留之前的sessionid。
那么如果用户b登录,那么按道理会从cookie中取出之前的那个sessionid,然后传给服务器,然后服务器端会识别这个sessionid,取出对应session的信息,那这样岂不是会造成:a用户存储在session中的信息,会被b用户看到。。。

各位大大,不知道我上述的描述有没有错误。。感觉应该对的。。但是实在想不通啊。。还求各位大大赐教~~~

有点尴尬了,发现自己没金币了。。。纯学术讨论。。谢谢了

zcx_hello
耶啵的酷盖 这个问题解决了吗。。。同求答案。。。
5 个月之前 回复
weixin_38355831
T0nMing 遇到了这个问题,同一个浏览器中打开两个窗口,登陆不同的用户,第二个用户登陆的时候会显示第一个用户的值,难受
大约一年之前 回复

7个回答

此时a用户退出,cookie中还是保留之前的sessionid
你的退出指什么东西?
如果是关闭浏览器,sessionid的cookie是内存的,关闭浏览器会就会删除。
如果只是关闭标签页,没有关闭浏览器,对于标签浏览器来说cookie是继续有效的,如果a离开了没关闭浏览器b用这个浏览器继续查看网页就是a的信息

如果是点击链接请求服务器销毁了session,虽然cookie存在,但是服务器端session内容已经销毁也是获取不到的,之后重新登录系统读取用户系统初始化session才会有值。

stone_yw
淹不死的水 cookie设置持久化了。。直接保存为临时文件了,也就是说cookie中有sessionid信息。。
接近 3 年之前 回复

每一个用户,服务器都会分配 不同的sessionId,并 保存 在 自己的 cookie中

stone_yw
淹不死的水 这个知道啊。。。但是我说的是浏览器,应该是对于不同的浏览器分配不同的session吧
接近 3 年之前 回复

不同用户不同的sessionID就算相同的用户不同的时间登录也是不同的session,其实对于登录可以使用shiro来进行权限控制

stone_yw
淹不死的水 我测试了一下。。比如都是用谷歌浏览器,a登录时,sessionid是100,然后a退出。。然后b登录登录,b会拿着刚才那个sessionid=100去的
接近 3 年之前 回复

同一个浏览器,同一个sessionid.
服务器只会检查sessionID,并不知道是谁用这个sessionid登录的,看到信息也很正常啊.
不知我说的对不,各位Java牛人

stone_yw
淹不死的水 我也觉得是这样。。但是这样的话,用户信息不就乱了么。。a可以看到b,b可以看到a么
接近 3 年之前 回复

你提到这个问题的关键点在于**用户a有没有退出**。

如果a没有退出,浏览器中还保存用户a的登录状态(sessionId),此时不管是谁访问网站,只要是用同一个浏览器,网站都会认为是a在登录。

如果a已经退出,这里的退出有两种方式,一是清掉浏览器端的登录状态,也就是清除登录cookie,二是清除网站服务端的session,只要清除两者任何一个,就会使浏览器和网站失去关联,即用户a退出。如果此时b再访问,要么浏览器没有了cookie,要么cookie中的sessionId在网站服务端找不到对应的session,都会使得b重新登录

stone_yw
淹不死的水 这样确实可以。。a退出时,session.isvalidate//。。。
接近 3 年之前 回复

今天有女朋友的去过520了,没有女朋友的假装自己去过520了,谁会来讨论啊!

同楼上,如果调用过session清除方法清除过session,用户b自然看不到登录信息。
但如果清除的不彻底的话,用户b登录存入session时候,也会顶替掉原session中的值。
如果重启过浏览器,session中的值也会随浏览器的关闭而销毁
.(个人理解,有问题请各位多多建议)

stone_yw
淹不死的水 session保存在cookie中了。。应该是清楚session
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
session的传递与丢失问题
[img]http://dl.iteye.com/upload/attachment/275755/7041880a-ce50-34e1-9cbb-9836d0b2c9e4.jpg[/img] 我编写了两个JSP页面:A页和B页。A显示数据列,有一个删除链接,点击删除链接,跳转B页删除数据再跳到A。 问题是:每点击删除,跳转都一直提示未登陆。为此我在AB上使用了session.getAttribute,结果AB都能显示用户ID,但跳转继续提示未登陆。 截图如下: [img]http://dl.iteye.com/upload/attachment/275755/7041880a-ce50-34e1-9cbb-9836d0b2c9e4.jpg[/img] A的JSP代码如下: [code="java"] <h2>用户:&nbsp<font color="red"><%=session.getAttribute("userid")%></font></h2> ...... if (session.getAttribute("userid") != null) { //判断用户ID // 取到用户ID后,执行以下操作 ...... <a href="delete.jsp">删除</a> ...... } else { // 用户未登录, 跳转 response.setHeader ("refresh", "2;URL=login.html") ; } [/code] B的JSP代码如下 [code="java"] <h2>用户:&nbsp<font color="red"><%=session.getAttribute("userid")%></font></h2> ...... if (session.getAttribute("userid") != null) { //判断用户ID // 取到用户ID,执行删除操作 response.setHeader("refresh", "2;URL=list.jsp") ; // 删除成功,自动跳转到A页 else { // 用户未登录,提示用户登录,并跳转 response.setHeader("refresh", "10;URL=login.html") ; } [/code]
session无法在两个JSP页面中传值???????
<% String id = request.getParameter("course_id"); if(id!=null) { session.setAttribute("id",id); response.sendRedirect("center.jsp"); } else { out.println("输入错误"); } %> 第一个JSP [图片说明](https://img-ask.csdn.net/upload/201807/03/1530608006_502141.jpg) 第二个JSP 你已选课成功,课程编号为:<%=session.getAttribute("id") %> [图片说明](https://img-ask.csdn.net/upload/201807/03/1530608028_681456.jpg) 结果显示 [图片说明](https://img-ask.csdn.net/upload/201807/03/1530608054_2359.jpg)
从数据库查询大量数据效率太低
现在在做一个背记英语单词的项目,使用的是mysql数据库,单词记录有一万五千多条,用户学习单词时要根据record记录表(包含用户id和单词id)查询出所有用户未学习过的单词和已学习过的单词。有两个功能需要实现,一个是展示10个用户没有学习过的单词,另一个是展示用户学习过的单词和未学习过的单词各5个。因为数据库中单词记录较多,到需要展示的时候再去查询就需要等好几秒,用户体验极差。该怎样去提高用户体验呢?我自己的解决方案是:因为查询单词必须用到用户id,所以不能在服务器启动的时候去查询数据,我是在用户登录成功跳转到主页之前将用户学习过的单词和未学习过的单词查询出来保存到两个List集合中(当然,这里查询的单词只是查出单词id而已),然后将两个集合保存到session域中,需要用到的时候直接取出就可以。这个方案存在两个很大的问题:一,登录时间延长了好几秒,用户体验差;二,将两个集合保存到session域中,虽然我也不知道会不会出什么问题,但总感觉不好(知道的还烦请指教一下)。各位有没有什么比较好的解决方案,还望不吝赐教
Java如何实现跨域传参
现在有两个前端项目 在其中一个项目中 使用url引用了另外一个项目的页面, 两个项目共用一个后台 ,后台使用的spring mvc,现在我需要把我登录的用户ID传到 另外一个项目上,使用的session存储的用户信息。但是拿不到,因为两个不是同一个项目请求不同。求解。大神们help me....
关于使用 cas做sso登录退出重复登录的问题
最近使用 cas 做sso 的时候遇到一个问题,客户反映说,在进入系统后点击退出登录后, 会回到登录页面,但是这个时候输入用户密码登录后,用户无法正常登录,登录页面知识做了刷新操作没有正常提交表单数据,这时候客户又必须重新输入密码再次点击登录,就没问题了,这用的问题不是经常发生,但是点击10次的话会出现2次左右, 后来跟踪cas 的源代码,发现cas 登录使用的是spring 的 webflow。 最终调试发现代码抛出: org.springframework.webflow.conversation.NoSuchConversationException: No conversation could be found with id '3' -- perhaps this conversation has ended? 具体问题我也晓得原因是什么,但是我不知道如何解决,网上又人说是session过时,但是我session-timeout 设置的是240分钟,应该不会,有人说是webflow中execution (即后台中的flowExecutionKey)这个无效的,这个我同意,但是问题是这个我都是从后台回去的,应该不存在无效啊,除非后台生成后,又把这个给删除了?? 所以搞不通懂,本人研究源码没有太深入,所以各位大神有没没有碰到类似的问题,帮忙解决下这个要求多次输入用户名密码的登录的问题。 可能问题描述的不是很清楚,因问题发生在内网,内外网是独立的两个网络无法互通,所以就没办法把代码贴出来,见谅。。
http头中uuid_tt_dd和dc_session_id的关系和区别是什么?
![wireshark抓包](https://img-blog.csdnimg.cn/20190414132127498.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BhY2tldF9MZWU=,size_16,color_FFFFFF,t_70) 最近在研究cookie,发现http头中用两个id,uuid_tt_dd和dc_session_id。很想知道他们的关系和区别?我浅薄的认识是第一个是用户的id,第二个就是cookie,有了第二个cookie为什么还要第一个uid呢?uid是token吗?
asp.net的session对象购物车
我刚学asp.net,要做购物车,不用数据库的那种,只是session对象,现在代码写好了,就是我第二次点击购买的时候,我希望购物车里有两次记录要怎么做,就比如同一件商品,我点击两次购买,购物车里有两个订单 代码如下: <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Button1_Click(object sender, EventArgs e) { Session["a"] = Label1.Text; Session["g"] = Label7.Text +1 +"</br>"; Response.Redirect("~/Default2.aspx"); } protected void Button2_Click(object sender, EventArgs e) { Session["b"] = Label2.Text; Session["h"] = Label8.Text +"</br>"; Response.Redirect("~/Default2.aspx"); } protected void Button3_Click(object sender, EventArgs e) { Session["c"] = Label3.Text; Session["i"] = Label9.Text +"</br>"; Response.Redirect("~/Default2.aspx"); } protected void Button4_Click(object sender, EventArgs e) { Session["d"] = Label4.Text; Session["j"] = Label10.Text +"</br>"; Response.Redirect("~/Default2.aspx"); } protected void Button5_Click(object sender, EventArgs e) { Session["e"] = Label5.Text; Session["k"] = Label11.Text +"</br>"; Response.Redirect("~/Default2.aspx"); } protected void Button6_Click(object sender, EventArgs e) { Session["f"] = Label6.Text; Session["l"] = Label12.Text +"</br>"; Response.Redirect("~/Default2.aspx"); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .style1 { text-align: left; } .style2 { text-align: center; font-weight: 700; } .style3 { font-weight: 700; text-align: center; } .style4 { font-weight: 700; text-align: center; } .style5 { font-weight: 700; text-align: center; } .style6 { font-weight: 700; text-align: center; } .style7 { font-weight: 700; text-align: center; } .style8 { height: 21px; } .style9 {} #form1 { text-align: left; } </style> </head> <body> <form id="form1" runat="server"> <div> </div> <asp:Image ID="Image2" runat="server" Height="234px" ImageUrl="~/图片/时代广场的蟋蟀.jpg" Width="234px" /> &nbsp;&nbsp;&nbsp; &nbsp; <asp:Image ID="Image3" runat="server" Height="234px" ImageUrl="~/图片/查理和巧克力工厂.jpg" Width="234px" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Image ID="Image4" runat="server" Height="234px" ImageUrl="~/图片/了不起的狐狸爸爸.jpg" Width="234px" /> <p class="style1"> <asp:Label ID="Label1" runat="server" CssClass="style2" Text="时代广场的蟋蟀" Width="243px"></asp:Label> &nbsp;&nbsp; &nbsp; <asp:Label ID="Label2" runat="server" CssClass="style4" Text="查理和巧克力工厂" Width="234px"></asp:Label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Label ID="Label3" runat="server" CssClass="style3" Text="北京遇上西雅图" Width="234px"></asp:Label> </p> <p class="style1"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="购买" CssClass="style8" UseSubmitBehavior="False" /> &nbsp;&nbsp;<asp:Label ID="Label7" runat="server" Text="19.00元"></asp:Label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="购买" UseSubmitBehavior="False" /> &nbsp;<asp:Label ID="Label8" runat="server" Text="18.00元"></asp:Label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Button ID="Button3" runat="server" Text="购买" onclick="Button3_Click" /> &nbsp;<asp:Label ID="Label9" runat="server" Text="16.00元"></asp:Label> </p> <asp:Image ID="Image5" runat="server" Height="234px" ImageUrl="~/图片/爱德华的奇妙之旅.jpg" Width="234px" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Image ID="Image6" runat="server" Height="234px" ImageUrl="~/图片/小时候就想做的事.jpg" Width="234px" /> &nbsp;&nbsp; <asp:Image ID="Image7" runat="server" Height="234px" ImageUrl="~/图片/天蓝色的彼岸.jpg" Width="234px" /> <br /> <br /> <asp:Label ID="Label4" runat="server" CssClass="style7" Text="爱德华的奇妙之旅" Width="234px"></asp:Label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Label ID="Label5" runat="server" CssClass="style6" Text="小时候就在想的事" Width="234px"></asp:Label> &nbsp;&nbsp; <asp:Label ID="Label6" runat="server" CssClass="style5" Text="天蓝色的彼岸" Width="234px"></asp:Label> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Button ID="Button4" runat="server" Text="购买" Onclick="Button4_Click" /> &nbsp;&nbsp;<asp:Label ID="Label10" runat="server" Text="17.00元"></asp:Label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Button ID="Button5" runat="server" Text="购买" onclick="Button5_Click" /> &nbsp;<asp:Label ID="Label11" runat="server" Text="15.00元"></asp:Label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Button ID="Button6" runat="server" Text="购买" onclick="Button6_Click" /> &nbsp;<asp:Label ID="Label12" runat="server" Text="18.00元"></asp:Label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:LinkButton ID="LinkButton1" runat="server" CssClass="style9" PostBackUrl="~/Default2.aspx">去购物车</asp:LinkButton> </form> </body> </html> <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { Session["Buy"] = Convert.ToInt32(Session["Buy"]); Response.Write(Session["a"]); Response.Write(Session["g"]); Response.Write(Session["b"]); Response.Write(Session["h"]); Response.Write(Session["c"]); Response.Write(Session["i"]); Response.Write(Session["d"]); Response.Write(Session["j"]); Response.Write(Session["e"]); Response.Write(Session["k"]); Response.Write(Session["f"]); Response.Write(Session["l"]); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .style1 { height: 111px; } #form1 { height: 65px; width: 932px; } </style> </head> <body class="style1"> <form id="form1" runat="server"> <div> </div> <br /> <br /> <asp:LinkButton ID="LinkButton1" runat="server">去收银台</asp:LinkButton> &nbsp;&nbsp; <asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl="~/Default1.aspx" >继续购物</asp:LinkButton> </form> </body> </html> 要怎么做呢?
Hibernate在中的 session 管理问题
我用Hibernate生成的HibernateSessionFactory 获得session 写了一个得到数据库数据的方法 用的是Hibernate的 query 结果连接各两三次就包错了 看看是不是写错了 public List getByAll(String hql) { Session session = HibernateSessionFactory.getSession(); List list = new ArrayList(); Query query = session.createQuery(hql); Transaction tx = session.beginTransaction(); try{ list = query.list(); tx.commit(); }catch(Exception e){ e.printStackTrace(); }finally{ } return list; } [b]问题补充:[/b] 我把一场贴出来 报的是Query接口的错误 在List list = query.list()那错了 org.hibernate.exception.JDBCConnectionException: could not execute query at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.loader.Loader.doList(Loader.java:2148) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2029) at org.hibernate.loader.Loader.list(Loader.java:2024) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:375) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:308) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:153) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1106) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79) at SessionDao.getAllDate(SessionDao.java:14) at logon.doPost(logon.java:40) at logon.doGet(logon.java:25) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445) at java.lang.Thread.run(Unknown Source) Caused by: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.net.SocketException MESSAGE: Software caused connection abort: recv failed STACKTRACE: java.net.SocketException: Software caused connection abort: recv failed at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(Unknown Source) at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:75) at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:94) at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:122) at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1842) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2292) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2788) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1534) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1625) at com.mysql.jdbc.Connection.execSQL(Connection.java:2297) at com.mysql.jdbc.Connection.execSQL(Connection.java:2226) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1812) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1657) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139) at org.hibernate.loader.Loader.getResultSet(Loader.java:1669) at org.hibernate.loader.Loader.doQuery(Loader.java:662) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224) at org.hibernate.loader.Loader.doList(Loader.java:2145) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2029) at org.hibernate.loader.Loader.list(Loader.java:2024) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:375) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:308) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:153) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1106) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79) at SessionDao.getAllDate(SessionDao.java:14) at logon.doPost(logon.java:40) at logon.doGet(logon.java:25) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445) at java.lang.Thread.run(Unknown Source) ** END NESTED EXCEPTION ** at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2504) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2788) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1534) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1625) at com.mysql.jdbc.Connection.execSQL(Connection.java:2297) at com.mysql.jdbc.Connection.execSQL(Connection.java:2226) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1812) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1657) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139) at org.hibernate.loader.Loader.getResultSet(Loader.java:1669) at org.hibernate.loader.Loader.doQuery(Loader.java:662) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224) at org.hibernate.loader.Loader.doList(Loader.java:2145) ... 24 more [b]问题补充:[/b] 后来我关闭了session。 可是用着用着还是报错了 我用了 懒加载的 是不是数据量大了 session出错了 数据库是mysql 小弟急死了 [b]问题补充:[/b] 这个是 Hibernate的执行语句 Hibernate: select vmark0_.id as id6_, vmark0_.fk_zone_id as fk2_6_, vmark0_.mark_name as mark3_6_, vmark0_.mark_address as mark4_6_, vmark0_.mark_content as mark5_6_, vmark0_.mark_status as mark6_6_, vmark0_.mark_type as mark7_6_ from numdum.v_mark vmark0_ 这个是我写的hql语句 from VMark 这个是VMark的映射文件 <hibernate-mapping> <class name="com.entity.VMark" table="v_mark" catalog="numdum"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="increment" /> </id> <many-to-one name="VZone" class="com.entity.VZone" fetch="select"> <column name="fk_zone_id" unique="true" /> </many-to-one> <property name="markName" type="java.lang.String"> <column name="mark_name" length="50" /> </property> <property name="markAddress" type="java.lang.String"> <column name="mark_address" length="200" /> </property> <property name="markContent" type="java.lang.String"> <column name="mark_content" length="500" /> </property> <property name="markStatus" type="java.lang.String"> <column name="mark_status" length="20" /> </property> <property name="markType" type="java.lang.String"> <column name="mark_type" length="50" /> </property> <set name="VCompanies" inverse="true"> <key> <column name="fk_mark_id" unique="true" /> </key> <one-to-many class="com.entity.VCompany" /> </set> <set name="VShops" inverse="true"> <key> <column name="fk_mark_id" unique="true" /> </key> <one-to-many class="com.entity.VShop" /> </set> </class> </hibernate-mapping> [b]问题补充:[/b] 把改进后的Dao也贴出来 这是操作数据库方法 public List getAllDate(String hql){ List list = new ArrayList(); try{ Session session = HibernateSessionFactory.getSession(); Query query = session.createQuery(hql); list = query.list(); HibernateSessionFactory.closeSession(); }catch(Exception e){ e.printStackTrace(); }finally{ } return list; } [b]问题补充:[/b] 手动关闭,用session.close()关闭后 报 session is ready close 的错 郁闷 [b]问题补充:[/b] 我改了 没用事物了 session.isConnected()是true true Hibernate: select vproducts0_.id as id14_, vproducts0_.fk_protype_id as fk2_14_, vproducts0_.fk_brand_id as fk3_14_, vproducts0_.fk_shop_id as fk4_14_, vproducts0_.pro_name as pro5_14_, vproducts0_.pro_picture as pro6_14_, vproducts0_.pro_inventory as pro7_14_, vproducts0_.pro_total as pro8_14_, vproducts0_.pro_retail as pro9_14_, vproducts0_.pro_wholesale as pro10_14_, vproducts0_.pro_retail_number as pro11_14_, vproducts0_.pro_wholesale_number as pro12_14_, vproducts0_.pro_date as pro13_14_, vproducts0_.pro_status as pro14_14_, vproducts0_.pro_content as pro15_14_, vproducts0_.pro_color as pro16_14_, vproducts0_.pro_if as pro17_14_, vproducts0_.pro_lockup as pro18_14_, vproducts0_.pro_hit as pro19_14_, vproducts0_.pro_if_sale as pro20_14_, vproducts0_.pro_if_inshop as pro21_14_, vproducts0_.pro_sale_date as pro22_14_ from numdum.v_products vproducts0_ org.hibernate.exception.JDBCConnectionException: could not execute query at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.loader.Loader.doList(Loader.java:2148) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2029) at org.hibernate.loader.Loader.list(Loader.java:2024) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:375) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:308) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:153) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1106) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79) at SessionDao.getAllDate(SessionDao.java:17) at logon.doPost(logon.java:36) at logon.doGet(logon.java:25) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445) at java.lang.Thread.run(Unknown Source) Caused by: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.io.EOFException STACKTRACE: java.io.EOFException at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1845) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2292) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2788) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1534) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1625) at com.mysql.jdbc.Connection.execSQL(Connection.java:2297) at com.mysql.jdbc.Connection.execSQL(Connection.java:2226) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1812) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1657) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139) at org.hibernate.loader.Loader.getResultSet(Loader.java:1669) at org.hibernate.loader.Loader.doQuery(Loader.java:662) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224) at org.hibernate.loader.Loader.doList(Loader.java:2145) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2029) at org.hibernate.loader.Loader.list(Loader.java:2024) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:375) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:308) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:153) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1106) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79) at SessionDao.getAllDate(SessionDao.java:17) at logon.doPost(logon.java:36) at logon.doGet(logon.java:25) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445) at java.lang.Thread.run(Unknown Source) ** END NESTED EXCEPTION ** at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2504) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2788) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1534) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1625) at com.mysql.jdbc.Connection.execSQL(Connection.java:2297) at com.mysql.jdbc.Connection.execSQL(Connection.java:2226) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1812) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1657) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139) at org.hibernate.loader.Loader.getResultSet(Loader.java:1669) at org.hibernate.loader.Loader.doQuery(Loader.java:662) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224) at org.hibernate.loader.Loader.doList(Loader.java:2145) ... 24 more [b]问题补充:[/b] 弱弱的问一句 会不会是因为session中管理的数据多了 或着是数据库的问题 我用的是懒加载
关于session过期时间的问题 在线等! 急急急!
我在web.xml文件里面配置了session过期时间,过期以后会弹出一个新的登陆页面,但是他会显示在第一次的页面里面 ![图片说明](https://img-ask.csdn.net/upload/201703/23/1490260021_590727.jpg) web.xml:<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>SJConsole</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/db/applicationContext-hibernate.xml, /WEB-INF/spring/proxy/system.xml, /WEB-INF/spring/proxy/base.xml, /WEB-INF/spring/proxy/mchnt.xml, /WEB-INF/spring/proxy/pos.xml, /WEB-INF/spring/proxy/risk.xml, /WEB-INF/spring/proxy/error.xml, /WEB-INF/spring/proxy/settle.xml, /WEB-INF/spring/proxy/mchtSrv.xml, /WEB-INF/spring/proxy/rout.xml, /WEB-INF/spring/proxy/epos.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> com.huateng.startup.listener.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> com.huateng.startup.listener.SystemListener </listener-class> </listener> <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class> org.directwebremoting.servlet.DwrServlet </servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>scriptCompressed</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>crossDomainSessionSecurity</param-name> <param-value>false</param-value> </init-param> </servlet> <servlet> <description>PrintImage</description> <display-name>PrintImage</display-name> <servlet-name>PrintImage</servlet-name> <servlet-class>com.huateng.system.util.PrintImage</servlet-class> </servlet> <listener> <listener-class> com.huateng.startup.listener.MyServerListener </listener-class> </listener> <filter> <filter-name>EncodeFilter</filter-name> <filter-class> com.huateng.system.util.EncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>ignore</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodeFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 统一认证 <filter> <filter-name>SAMLAuthFilter</filter-name> <filter-class>samlsso.servlet.SAMLAuthFilter</filter-class> <init-param> <param-name>redirectURL</param-name> <param-value>http://idp.uat.spdb.com</param-value> </init-param> <init-param> <param-name>token-type</param-name> <param-value>SAML.Assertion</param-value> </init-param> <init-param> <param-name>realm-name</param-name> <param-value>myrealm</param-value> </init-param> </filter> <filter-mapping> <filter-name>SAMLAuthFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> --> <listener> <listener-class> com.huateng.system.util.SessionListener </listener-class> </listener> <filter> <filter-name>RoleFilter</filter-name> <filter-class> com.huateng.system.util.RoleFilter </filter-class> </filter> <filter-mapping> <filter-name>RoleFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter> <filter-name>SysFilter</filter-name> <filter-class> com.huateng.system.util.SysFilter </filter-class> </filter> <filter-mapping> <filter-name>SysFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <error-page> <error-code>404</error-code> <location>/page/system/error404.jsp</location> </error-page> <error-page> <exception-type>java.lang.NullPointerException</exception-type> <location>/page/system/error404.jsp</location> </error-page> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>PrintImage</servlet-name> <url-pattern>/PrintImage</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/page/system/login.jsp</welcome-file> </welcome-file-list> <session-config> <session-timeout>30</session-timeout> </session-config> <security-constraint> <web-resource-collection> <web-resource-name>OGNLconsole</web-resource-name> <!-- 禁止访问 --> <url-pattern>/struts/webconsole.html</url-pattern> </web-resource-collection> <auth-constraint/> </security-constraint> </web-app> 过滤器代码: /* @(#) * * Project:PFConsole * * Modify Information: * ============================================================================= * Author Date Description * ------------ ---------- --------------------------------------------------- * PanShuang 2011-9-16 first release * * * Copyright Notice: * ============================================================================= * Copyright 2011 Huateng Software, Inc. All rights reserved. * * This software is the confidential and proprietary information of * Shanghai HUATENG Software Co., Ltd. ("Confidential Information"). * You shall not disclose such Confidential Information and shall use it * only in accordance with the terms of the license agreement you entered * into with Huateng. * * Warning: * ============================================================================= * */ package com.huateng.system.util; import java.io.IOException; import java.util.HashSet; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import com.huateng.common.Constants; /** * Title: * * Description: * * Copyright: Copyright (c) 2011-9-16 * * Company: Shanghai Huateng Software Systems Co., Ltd. * * @version 1.0 */ public class RoleFilter implements Filter{ private static Logger log = Logger.getLogger(RoleFilter.class); public void destroy() { } @SuppressWarnings("unchecked") public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)arg0; HttpServletResponse response = (HttpServletResponse)arg1; String url = request.getRequestURL().toString(); String res = CommonFunction.urlToRoleId(url); if(res.matches("T\\d+$")) { //1.判断请求来源 if (null == request.getHeader("referer")) { //判断是否为子页面,该系统定义子页面为编号+两位数字 //这里将子页面自动放行,适用于window.open()方式打开的窗口 if (res.length() != 8 || !res.substring(6, 8).matches("[0-9]{2}$")) { log.info("illegal access(referer)!"); response.sendRedirect(request.getContextPath()+"/redirect.asp"); } } //2.判断请求合法性 HttpSession session = request.getSession(); HashSet<String> set = (HashSet<String>)session.getAttribute(Constants.USER_AUTH_SET); if(set == null || (!set.contains(res.substring(1,6)))) { log.info("illegal access!"); response.sendRedirect(request.getContextPath()+"/redirect.asp"); } else { arg2.doFilter(request, response); } } else arg2.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { } }
Hibernate上一个很诡异的问题
User.hbm.xml: <set cascade="all" inverse="true" name="activeFriends" sort="unsorted"> <key column="concernedUserId"/> <one-to-many class="Friends"/> </set> <set cascade="all" inverse="true" name="passiveFriends" sort="unsorted"> <key column="userId"/> <one-to-many class="Friends"/> </set>` Friends.hbm.xml: <composite-id> <key-many-to-one name="activeUser" column="userId" class="User"></key-many-to-one> <key-many-to-one name="passiveUser" column="concernedUserId" class="User"></key-many-to-one> </composite-id> DaoImpl: /** * 添加用户关注 */ public void userAddConcern(int userId,int concernedUserId) { Session session=null; User activeUser=null; User passiveUser=null; try{ session = HibernateUtil.getSession(); session.getTransaction().begin(); activeUser=(User)session.createQuery("from User user where user.id=:id").setInteger("id",userId).uniqueResult(); passiveUser=(User)session.createQuery("from User user where user.id=:id").setInteger("id",concernedUserId).uniqueResult(); if(activeUser==null||passiveUser==null) { return; } Friends friend=new Friends(); friend.setActiveUser(activeUser); friend.setPassiveUser(passiveUser); activeUser.getPassiveFriends().add(friend); session.getTransaction().commit(); }catch(Exception e){ e.printStackTrace(); session.getTransaction().rollback(); }finally{ session.close(); } } /** * 取消用户关注 */ public void userRemoveConcern(int userId, int concernedUserId) { Session session=null; User activeUser=null; User passiveUser=null; try{ session = HibernateUtil.getSession(); session.getTransaction().begin(); activeUser=(User)session.createQuery("from User user where user.id=:id").setInteger("id",userId).uniqueResult(); passiveUser=(User)session.createQuery("from User user where user.id=:id").setInteger("id",concernedUserId).uniqueResult(); if(activeUser==null||passiveUser==null) { return; } Friends friend=new Friends(); friend.setActiveUser(activeUser); friend.setPassiveUser(passiveUser); activeUser.getPassiveFriends().remove(friend); session.getTransaction().commit(); }catch(Exception e){ e.printStackTrace(); session.getTransaction().rollback(); }finally{ session.close(); } } 这两个函数功能大致是模仿微博上用户关注的功能 问题是第一个函数功能正常,第二个函数没反应。 第二个函数主要功能是取消关注,对象activeUser打印后,确实在passiveFriend集合里面将那个关注的关系删掉了,但是commit没有作用。这是为什么??
两个list如何合并成一个数组
public Object[] query(Object[] a){ Session session=sessionFactory.getCurrentSession(); Query query =session.createQuery("from subject"); if(query.list().isEmpty()){ List<Integer> list1=new ArrayList<Integer>(); List<subject> list=query.list(); for (subject subject : list) { Integer id= subject.getId(); Query query1=session.createQuery("from option where subjectid =:id"); query1.setString("id", ""+id+""); Integer preson =(Integer) query1.uniqueResult(); list1.add(preson); } } } 我想把list和list1合并成一个请问下怎么合并
tensorflow模型推理,两个列表串行,输出结果是第一个列表的循环,新手求教
tensorflow模型推理,两个列表串行,输出结果是第一个列表的循环,新手求教 ``` from __future__ import print_function import argparse from datetime import datetime import os import sys import time import scipy.misc import scipy.io as sio import cv2 from glob import glob import multiprocessing os.environ["CUDA_VISIBLE_DEVICES"] = "0" import tensorflow as tf import numpy as np from PIL import Image from utils import * N_CLASSES = 20 DATA_DIR = './datasets/CIHP' LIST_PATH = './datasets/CIHP/list/val2.txt' DATA_ID_LIST = './datasets/CIHP/list/val_id2.txt' with open(DATA_ID_LIST, 'r') as f: NUM_STEPS = len(f.readlines()) RESTORE_FROM = './checkpoint/CIHP_pgn' # Load reader. with tf.name_scope("create_inputs") as scp1: reader = ImageReader(DATA_DIR, LIST_PATH, DATA_ID_LIST, None, False, False, False, None) image, label, edge_gt = reader.image, reader.label, reader.edge image_rev = tf.reverse(image, tf.stack([1])) image_list = reader.image_list image_batch = tf.stack([image, image_rev]) label_batch = tf.expand_dims(label, dim=0) # Add one batch dimension. edge_gt_batch = tf.expand_dims(edge_gt, dim=0) h_orig, w_orig = tf.to_float(tf.shape(image_batch)[1]), tf.to_float(tf.shape(image_batch)[2]) image_batch050 = tf.image.resize_images(image_batch, tf.stack([tf.to_int32(tf.multiply(h_orig, 0.50)), tf.to_int32(tf.multiply(w_orig, 0.50))])) image_batch075 = tf.image.resize_images(image_batch, tf.stack([tf.to_int32(tf.multiply(h_orig, 0.75)), tf.to_int32(tf.multiply(w_orig, 0.75))])) image_batch125 = tf.image.resize_images(image_batch, tf.stack([tf.to_int32(tf.multiply(h_orig, 1.25)), tf.to_int32(tf.multiply(w_orig, 1.25))])) image_batch150 = tf.image.resize_images(image_batch, tf.stack([tf.to_int32(tf.multiply(h_orig, 1.50)), tf.to_int32(tf.multiply(w_orig, 1.50))])) image_batch175 = tf.image.resize_images(image_batch, tf.stack([tf.to_int32(tf.multiply(h_orig, 1.75)), tf.to_int32(tf.multiply(w_orig, 1.75))])) ``` 新建网络 ``` # Create network. with tf.variable_scope('', reuse=False) as scope: net_100 = PGNModel({'data': image_batch}, is_training=False, n_classes=N_CLASSES) with tf.variable_scope('', reuse=True): net_050 = PGNModel({'data': image_batch050}, is_training=False, n_classes=N_CLASSES) with tf.variable_scope('', reuse=True): net_075 = PGNModel({'data': image_batch075}, is_training=False, n_classes=N_CLASSES) with tf.variable_scope('', reuse=True): net_125 = PGNModel({'data': image_batch125}, is_training=False, n_classes=N_CLASSES) with tf.variable_scope('', reuse=True): net_150 = PGNModel({'data': image_batch150}, is_training=False, n_classes=N_CLASSES) with tf.variable_scope('', reuse=True): net_175 = PGNModel({'data': image_batch175}, is_training=False, n_classes=N_CLASSES) # parsing net parsing_out1_050 = net_050.layers['parsing_fc'] parsing_out1_075 = net_075.layers['parsing_fc'] parsing_out1_100 = net_100.layers['parsing_fc'] parsing_out1_125 = net_125.layers['parsing_fc'] parsing_out1_150 = net_150.layers['parsing_fc'] parsing_out1_175 = net_175.layers['parsing_fc'] parsing_out2_050 = net_050.layers['parsing_rf_fc'] parsing_out2_075 = net_075.layers['parsing_rf_fc'] parsing_out2_100 = net_100.layers['parsing_rf_fc'] parsing_out2_125 = net_125.layers['parsing_rf_fc'] parsing_out2_150 = net_150.layers['parsing_rf_fc'] parsing_out2_175 = net_175.layers['parsing_rf_fc'] # edge net edge_out2_100 = net_100.layers['edge_rf_fc'] edge_out2_125 = net_125.layers['edge_rf_fc'] edge_out2_150 = net_150.layers['edge_rf_fc'] edge_out2_175 = net_175.layers['edge_rf_fc'] # combine resize parsing_out1 = tf.reduce_mean(tf.stack([tf.image.resize_images(parsing_out1_050, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out1_075, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out1_100, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out1_125, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out1_150, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out1_175, tf.shape(image_batch)[1:3,])]), axis=0) parsing_out2 = tf.reduce_mean(tf.stack([tf.image.resize_images(parsing_out2_050, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out2_075, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out2_100, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out2_125, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out2_150, tf.shape(image_batch)[1:3,]), tf.image.resize_images(parsing_out2_175, tf.shape(image_batch)[1:3,])]), axis=0) edge_out2_100 = tf.image.resize_images(edge_out2_100, tf.shape(image_batch)[1:3,]) edge_out2_125 = tf.image.resize_images(edge_out2_125, tf.shape(image_batch)[1:3,]) edge_out2_150 = tf.image.resize_images(edge_out2_150, tf.shape(image_batch)[1:3,]) edge_out2_175 = tf.image.resize_images(edge_out2_175, tf.shape(image_batch)[1:3,]) edge_out2 = tf.reduce_mean(tf.stack([edge_out2_100, edge_out2_125, edge_out2_150, edge_out2_175]), axis=0) raw_output = tf.reduce_mean(tf.stack([parsing_out1, parsing_out2]), axis=0) head_output, tail_output = tf.unstack(raw_output, num=2, axis=0) tail_list = tf.unstack(tail_output, num=20, axis=2) tail_list_rev = [None] * 20 for xx in range(14): tail_list_rev[xx] = tail_list[xx] tail_list_rev[14] = tail_list[15] tail_list_rev[15] = tail_list[14] tail_list_rev[16] = tail_list[17] tail_list_rev[17] = tail_list[16] tail_list_rev[18] = tail_list[19] tail_list_rev[19] = tail_list[18] tail_output_rev = tf.stack(tail_list_rev, axis=2) tail_output_rev = tf.reverse(tail_output_rev, tf.stack([1])) raw_output_all = tf.reduce_mean(tf.stack([head_output, tail_output_rev]), axis=0) raw_output_all = tf.expand_dims(raw_output_all, dim=0) pred_scores = tf.reduce_max(raw_output_all, axis=3) raw_output_all = tf.argmax(raw_output_all, axis=3) pred_all = tf.expand_dims(raw_output_all, dim=3) # Create 4-d tensor. raw_edge = tf.reduce_mean(tf.stack([edge_out2]), axis=0) head_output, tail_output = tf.unstack(raw_edge, num=2, axis=0) tail_output_rev = tf.reverse(tail_output, tf.stack([1])) raw_edge_all = tf.reduce_mean(tf.stack([head_output, tail_output_rev]), axis=0) raw_edge_all = tf.expand_dims(raw_edge_all, dim=0) pred_edge = tf.sigmoid(raw_edge_all) res_edge = tf.cast(tf.greater(pred_edge, 0.5), tf.int32) # prepare ground truth preds = tf.reshape(pred_all, [-1,]) gt = tf.reshape(label_batch, [-1,]) weights = tf.cast(tf.less_equal(gt, N_CLASSES - 1), tf.int32) # Ignoring all labels greater than or equal to n_classes. mIoU, update_op_iou = tf.contrib.metrics.streaming_mean_iou(preds, gt, num_classes=N_CLASSES, weights=weights) macc, update_op_acc = tf.contrib.metrics.streaming_accuracy(preds, gt, weights=weights) # # Which variables to load. # restore_var = tf.global_variables() # # Set up tf session and initialize variables. # config = tf.ConfigProto() # config.gpu_options.allow_growth = True # # gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.7) # # config=tf.ConfigProto(gpu_options=gpu_options) # init = tf.global_variables_initializer() # evaluate prosessing parsing_dir = './output' # Set up tf session and initialize variables. config = tf.ConfigProto() config.gpu_options.allow_growth = True ``` 以上是初始化网络和初始化参数载入模型,下面定义两个函数分别处理val1.txt和val2.txt两个列表内部的数据。 ``` # 处理第一个列表函数 def humanParsing1(): # Which variables to load. restore_var = tf.global_variables() init = tf.global_variables_initializer() with tf.Session(config=config) as sess: sess.run(init) sess.run(tf.local_variables_initializer()) # Load weights. loader = tf.train.Saver(var_list=restore_var) if RESTORE_FROM is not None: if load(loader, sess, RESTORE_FROM): print(" [*] Load SUCCESS") else: print(" [!] Load failed...") # Create queue coordinator. coord = tf.train.Coordinator() # Start queue threads. threads = tf.train.start_queue_runners(coord=coord, sess=sess) # Iterate over training steps. for step in range(NUM_STEPS): # parsing_, scores, edge_ = sess.run([pred_all, pred_scores, pred_edge])# , update_op parsing_, scores, edge_ = sess.run([pred_all, pred_scores, pred_edge]) # , update_op print('step {:d}'.format(step)) print(image_list[step]) img_split = image_list[step].split('/') img_id = img_split[-1][:-4] msk = decode_labels(parsing_, num_classes=N_CLASSES) parsing_im = Image.fromarray(msk[0]) parsing_im.save('{}/{}_vis.png'.format(parsing_dir, img_id)) coord.request_stop() coord.join(threads) # 处理第二个列表函数 def humanParsing2(): # Set up tf session and initialize variables. config = tf.ConfigProto() config.gpu_options.allow_growth = True # gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.7) # config=tf.ConfigProto(gpu_options=gpu_options) # Which variables to load. restore_var = tf.global_variables() init = tf.global_variables_initializer() with tf.Session(config=config) as sess: # Create queue coordinator. coord = tf.train.Coordinator() sess.run(init) sess.run(tf.local_variables_initializer()) # Load weights. loader = tf.train.Saver(var_list=restore_var) if RESTORE_FROM is not None: if load(loader, sess, RESTORE_FROM): print(" [*] Load SUCCESS") else: print(" [!] Load failed...") LIST_PATH = './datasets/CIHP/list/val1.txt' DATA_ID_LIST = './datasets/CIHP/list/val_id1.txt' with open(DATA_ID_LIST, 'r') as f: NUM_STEPS = len(f.readlines()) # with tf.name_scope("create_inputs"): with tf.name_scope(scp1): tf.get_variable_scope().reuse_variables() reader = ImageReader(DATA_DIR, LIST_PATH, DATA_ID_LIST, None, False, False, False, coord) image, label, edge_gt = reader.image, reader.label, reader.edge image_rev = tf.reverse(image, tf.stack([1])) image_list = reader.image_list # Start queue threads. threads = tf.train.start_queue_runners(coord=coord, sess=sess) # Load weights. loader = tf.train.Saver(var_list=restore_var) if RESTORE_FROM is not None: if load(loader, sess, RESTORE_FROM): print(" [*] Load SUCCESS") else: print(" [!] Load failed...") # Iterate over training steps. for step in range(NUM_STEPS): # parsing_, scores, edge_ = sess.run([pred_all, pred_scores, pred_edge])# , update_op parsing_, scores, edge_ = sess.run([pred_all, pred_scores, pred_edge]) # , update_op print('step {:d}'.format(step)) print(image_list[step]) img_split = image_list[step].split('/') img_id = img_split[-1][:-4] msk = decode_labels(parsing_, num_classes=N_CLASSES) parsing_im = Image.fromarray(msk[0]) parsing_im.save('{}/{}_vis.png'.format(parsing_dir, img_id)) coord.request_stop() coord.join(threads) if __name__ == '__main__': humanParsing1() humanParsing2() ``` 最终输出结果一直是第一个列表里面的循环,代码上用了 self.queue = tf.train.slice_input_producer([self.images, self.labels, self.edges], shuffle=shuffle),队列的方式进行多线程推理。最终得到的结果一直是第一个列表的循环,求大神告诉问题怎么解决。
两个list如何 合并成为一个数组,我想讲list和list1合并成为一个数组
public Object[] query(Object[] a){ Session session=sessionFactory.getCurrentSession(); Query query =session.createQuery("from subject"); if(query.list().isEmpty()){ List<Integer> list1=new ArrayList<Integer>(); List<subject> list=query.list(); for (subject subject : list) { Integer id= subject.getId(); Query query1=session.createQuery("from option where subjectid =:id"); query1.setString("id", ""+id+""); Integer preson =(Integer) query1.uniqueResult(); list1.add(preson); } } }
iframe 这样刷新系统,不能保持session有效吗?
想实现功能:只要网页不关闭,session永远不过期; <br /> <br />实现方法: <br /> <br />1.在系统主页中,加入一个iframe,引用刷新页面: <br />&lt;iframe id="iframe_00" frameborder="no" border="0" style="width:0;height:0" src="/html/refresh.jsp"&gt;&lt;/iframe&gt; <br /> <br />2.刷新页面的内容如下,每15分钟重新刷新一次,加载本页面; <br />refresh.jsp的内容如下: <br /> <br />&lt;html&gt; <br /> &lt;head&gt; <br /> &lt;title&gt;refresh&lt;/title&gt; <br /> &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; <br /> &lt;script type="text/javascript"&gt; <br /> function _refresh(){//alert('test'); <br /> window.location.reload(); <br /> } <br /> var timer = window.setTimeout(_refresh,15*60*1000); <br /> &lt;/script&gt; <br /> &lt;/head&gt; <br /> &lt;body&gt; <br /> <div style="display: none;"> <br /> &lt;% <br />String uid=cn.com.web.SessionHelper.getSessionUserId(request); <br />//System.err.println("session user id == "+uid); <br /> %&gt; <br /> </div> <br /> &lt;/body&gt; <br />&lt;/html&gt; <br /> <br /> <br />问题: <br /> <br />1.刷新页面肯定有执行,我有打印出内容查看,打印出来的登录名也是正确的; <br /> <br />2.系统到了web.xml中设定的session失效时间后,session依然失效,跳转到登录页面; <br /> &lt;session-config&gt; <br /> &lt;session-timeout&gt;300&lt;/session-timeout&gt; <br /> &lt;/session-config&gt; <br /> <br />真是找不到解释的理由了,,大家帮我看看.... <br /> <br />谢谢<br /><strong>问题补充:</strong><br />针对各位朋友的答案: <br /> <br />补充一下:: <br /> <br />1.我详细对比了比的请求的sessionId,值是一样的; <br /> <br />2.我单机服务器使用的是weblogic814,不会产生这种问题; <br /> <br />3.部署到生产机,,使用weblogic814集群,有两台服务器,才产生失效的问题; <br /> <br />4.加入以下测试代码: <br /> <br />long last=session.getLastAccessedTime(); <br />long now=new java.util.Date().getTime(); <br />int max=session.getMaxInactiveInterval(); <br /> <br />java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); <br />System.err.println("MaxInactiveInterval=="+session.getMaxInactiveInterval()+"  LastAccessedTime=="+sdf.format(new java.util.Date(last))+"  now time=="+sdf.format(new java.util.Date(now))+"  invaid time == "+(max-((now-last)/1000)));//个人认为,最后一个时间是,离session失效的时间.,打印出来的结果是,,还需要115秒才失效,,可是,,前台已经失效了; <br /> <br />打印出的结果是: <br /> <br />&gt;&gt;MaxInactiveInterval==120  LastAccessedTime==2009-01-07 15:33:19  now time==2009-01-07 15:33:25  invaid time == 115 <br />&gt;&gt;MaxInactiveInterval==120  LastAccessedTime==2009-01-07 15:33:25  now time==2009-01-07 15:33:30  invaid time == 115 <br />&gt;&gt;MaxInactiveInterval==120  LastAccessedTime==2009-01-07 15:33:30  now time==2009-01-07 15:33:35  invaid time == 115 <br />&gt;&gt;MaxInactiveInterval==120  LastAccessedTime==2009-01-07 15:33:35  now time==2009-01-07 15:33:40  invaid time == 115 <br />&gt;&gt;MaxInactiveInterval==120  LastAccessedTime==2009-01-07 15:33:40  now time==2009-01-07 15:33:45  invaid time == 115 <br />&gt;&gt;MaxInactiveInterval==120  LastAccessedTime==2009-01-07 15:33:45  now time==2009-01-07 15:33:50  invaid time == 115 <br />&gt;&gt;MaxInactiveInterval==120  LastAccessedTime==2009-01-07 15:33:50  now time==2009-01-07 15:33:55  invaid time == 115 <br /> <br /> <br />还没有答案,,,真是奇怪... <br /> <br /> <br /> <br /><strong>问题补充:</strong><br />&lt;session-config&gt; <br />&lt;session-timeout&gt;300&lt;/session-timeout&gt; <br />&lt;/session-config&gt; <br /> <br />单位应该是,分钟,,,300/60.应该5小时.?<br /><strong>问题补充:</strong><br />不好意思,,,为了做测试:: <br /> <br />我现在改了配置文件,,,以上的打印结果是基于新配置文件的... <br /> <br /> <br /> &lt;session-config&gt; <br /> &lt;session-timeout&gt;2&lt;/session-timeout&gt; <br /> &lt;/session-config&gt; <br />//2分钟 <br /> <br /> function _refresh(){ <br />    window.location.reload(); <br /> } <br /> var timer = window.setTimeout(_refresh,5*1000); <br /> <br />//5秒钟刷新一次 <br /> <br />说明一下,,后来的打印一却都是自己需要的结果,,,打印的都是正确的.... <br /> <br />但是,,2分钟时间到了,,照样跳转出登录页面; <br /> <br /> <br />集群,session复制问题: <br /> <br />集群我不太熟悉,,是别的公司配置的,,采用的是array,,(我没用过,呵呵,,一点不懂),,,,他现在的算法是,,一个IP,一定时间内的访问都固定在一台服务上,,这样想过去,,应该不存在session复制问题., <br /><br /><strong>问题补充:</strong><br />集群,使用Array的负载均衡. <br /> <br />因为客观原因,分流配置是别的公司做的.. <br /> <br />我们这里不太了解这个东西.. <br /> <br />要沟通,,需要找比较有效的证剧,,证明和它们有关系,,,比较麻烦..<br /><strong>问题补充:</strong><br />他们采用的算法是,, <br /> <br />比如,,A IP 这次访问请求,,在此10小时内访问,,都是固定在server 1,, <br /> <br />没有session 的复制,,,减小系统开支.. <br /> <br />照这样看的话,,应该就不存在因为服务器session不同步而产生这个问题,, <br /> <br />日志的打印结果也证明,,打印的内容,,比如保存在session中的用户的登录账号,,一直都是正确的...<br /><strong>问题补充:</strong><br /><div class="quote_title">引用</div><div class="quote_div">两个服务器,分别添加一个测试页面; 看看是否客户端,随机访问了2台服务器,而不是按照Session的保持关系.</div> <br /> <br />这个可以肯定,,确实随机访问了其中一台服务,,直到这个这个请求终止,,都是这台服务在响应.<br /><strong>问题补充:</strong><br /><div class="quote_title">引用</div><div class="quote_div">1.在你本地机器测试,看是否有问题; <br />2.在服务器测试,看是否只有Array的情况下有问题; <br />3.如果不是Array也有问题,那就是集群的配置问题; </div> <br /> <br />本地是没问题的; <br /> <br />array,和集群问题因为不熟悉,不好测试,, <br />单起一台服务也是会超时; <br /> <br /><br /><strong>问题补充:</strong><br /><div class="quote_title">引用</div><div class="quote_div">直接JS 写一个刷新的不就行了, 为什么不改下服务器的session周期</div> <br /> <br />写JS刷新效果是一样的,, <br /> <br />到于改session周期,,真是一言难尽,,,不知道改多大为好.. <br /> <br />这样的需求属于客户要求问题,,我改了5小时了,,,他一晚上不关机,,,照样超时,,我要是改成12小时,,,他要是周未不关机怎么办?? <br /> <br />那我总不能改成无穷大吧????<img src="/images/smiles/icon_redface.gif" /> <br /> <br />想不明白呀,,,不知道怎么调试了....<img src="/images/smiles/icon_cry.gif" /> <br /><strong>问题补充:</strong><br />问题解决:原因是系统中引用了第三方的JAR包,跟踪后,发现这个JAR包中有个方法会在session超时时间到后,,自动去清除会话,而不管你这个session的last access time.... <br /> <br />将这个JAR包去除后,,,系统正常.... <br /> <br />具体原因还是不清楚,,感觉不可思议..... <br /> <br />为什么本机开发的时候不会出这个问题呢???weblogic的部署模式有关系吗??? <br /> <br />是和操作系统有关系吗? <br /> <br />待以后了解...
wininet API多线程 访问问题
使用wininet API函数登录 一个HTTPS应用程序服务器 1个线程 1个帐号登录操作 一切正常 当第二个帐号登录后 第一个帐号就会失效 提示“会话过期”,应该服务器有判断会话ID 开两个进程 分开登录 也会出现 “会话过期”提示 查了下资料貌似说 wininetAPI 自己管理了cookies和session 各位大神 给点建议 如果想实现同时正常登录不同帐号 并保持会话 怎么实现 能不能通过哪个方法用API实现和HTTPclinet或者tidhttp那样的独立会话和保持 代码不贴了 很简单的几个API InternetOpenA InternetConnectA HttpOpenRequestA HttpSendRequestA InternetReadFile HttpQueryInfoA HttpAddRequestHeaders InternetSetOptionA
Application startup failed
``` 2019-11-14 10:13:09,698 ERROR 9667 --- [ main] o.springframework.boot.SpringApplication : Application startup failed org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.dtdream.eta.web.EGGovUaaWebDubboApplication]; nested exception is org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'shiroAutoConfiguration' for bean class [com.dtdream.eta.web.auth.autoconfigure.ShiroAutoConfiguration] conflicts with existing, non-compatible bean definition of same name and class [com.dtdream.eta.web.uaa.autoconfigure.ShiroAutoConfiguration] at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:546) at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:482) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:191) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) at com.dtdream.eta.web.EGGovUaaWebDubboApplication.main(EGGovUaaWebDubboApplication.java:57) Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'shiroAutoConfiguration' for bean class [com.dtdream.eta.web.auth.autoconfigure.ShiroAutoConfiguration] conflicts with existing, non-compatible bean definition of same name and class [com.dtdream.eta.web.uaa.autoconfigure.ShiroAutoConfiguration] at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:320) at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:259) at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:144) at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:275) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:237) at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:537) ... 13 common frames omitted Disconnected from the target VM, address: '127.0.0.1:55237', transport: 'socket' Process finished with exit code 1 ``` 附上两个配置文件配置:com.dtdream.eta.web.auth.autoconfigure.ShiroAutoConfiguration package com.dtdream.eta.web.auth.autoconfigure; import com.dtdream.eta.web.auth.cache.JedisCacheManager; import com.dtdream.eta.web.auth.mobile.AppDefaultWebSessionManager; import com.dtdream.eta.web.auth.mobile.AppSessionIdGenerator; import com.dtdream.eta.web.auth.mobile.AppTokenRealm; import com.dtdream.eta.web.auth.mobile.MobileAuthFilter; import com.dtdream.eta.web.auth.shiro.*; import com.dtdream.eta.web.auth.oauth2.OAuth2AuthenticationFilter; import com.dtdream.eta.web.auth.oauth2.OAuth2Realm; import com.dtdream.gamma.account.service.AccountPrivilegeReadService; import com.dtdream.gamma.organization.service.EmployeeReadService; import com.dtdream.gamma.uaa.service.OauthAccessTokenReadService; import com.google.common.base.Strings; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.codec.Base64; import org.apache.shiro.mgt.RememberMeManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.realm.Realm; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; import org.apache.shiro.session.mgt.eis.SessionDAO; import org.apache.shiro.session.mgt.eis.SessionIdGenerator; import org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.filter.authc.AuthenticationFilter; import org.apache.shiro.web.mgt.CookieRememberMeManager; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.servlet.AbstractShiroFilter; import org.apache.shiro.web.servlet.Cookie; import org.apache.shiro.web.servlet.ShiroHttpSession; import org.apache.shiro.web.servlet.SimpleCookie; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.data.redis.core.RedisTemplate; import javax.servlet.Filter; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; /** * */ @Configuration @Slf4j @Order(Ordered.LOWEST_PRECEDENCE) public class ShiroAutoConfiguration { @Bean @Autowired public CacheManager shiroCacheManager(EtaAuthProperties properties, RedisTemplate redisTemplate){ return new JedisCacheManager(redisTemplate); } @Bean @Autowired public AuthorizingRealm oAuth2Realm(EtaAuthProperties properties, EmployeeReadService employeeReadService, AccountPrivilegeReadService accountPrivilegeReadService, CacheManager cacheManager){ OAuth2Realm oAuth2Realm = new OAuth2Realm(cacheManager.getCache(JedisCacheManager.loginUserName)); oAuth2Realm.setCachingEnabled(true); oAuth2Realm.setAuthenticationCachingEnabled(true); oAuth2Realm.setAuthenticationCacheName(JedisCacheManager.authenticationName); oAuth2Realm.setAuthorizationCachingEnabled(true); oAuth2Realm.setAuthorizationCacheName(JedisCacheManager.authorizationName); oAuth2Realm.setProperties(properties); oAuth2Realm.setEmployeeReadService(employeeReadService); oAuth2Realm.setAccountPrivilegeReadService(accountPrivilegeReadService); return oAuth2Realm; } @Bean @Autowired public AppTokenRealm appTokenRealm(EtaAuthProperties properties, OauthAccessTokenReadService oauthAccessTokenReadService, EmployeeReadService employeeReadService, AccountPrivilegeReadService accountPrivilegeReadService, CacheManager cacheManager){ AppTokenRealm appTokenRealm = new AppTokenRealm(cacheManager.getCache(JedisCacheManager.loginUserName)); appTokenRealm.setCachingEnabled(true); appTokenRealm.setAuthenticationCachingEnabled(true); appTokenRealm.setAuthenticationCacheName(JedisCacheManager.authenticationName); appTokenRealm.setAuthorizationCachingEnabled(true); appTokenRealm.setAuthorizationCacheName(JedisCacheManager.authorizationName); appTokenRealm.setProperties(properties); appTokenRealm.setEmployeeReadService(employeeReadService); appTokenRealm.setAccountPrivilegeReadService(accountPrivilegeReadService); appTokenRealm.setOauthAccessTokenReadService(oauthAccessTokenReadService); return appTokenRealm; } // @Bean // @Autowired // public AppTokenRealm appTokenRealm(){ // AppTokenRealm appTokenRealm = new AppTokenRealm(); // return appTokenRealm; // } @Bean public SessionIdGenerator sessionIdGenerator(){ return new AppSessionIdGenerator(); } @Bean @Autowired public Cookie sessionIdCookie(EtaAuthProperties properties){ SimpleCookie template = properties.getCookie(); SimpleCookie cookie; if (null == template){ cookie = new SimpleCookie(); cookie.setPath("/"); cookie.setName(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); return cookie; } cookie = new SimpleCookie(template); if (null == cookie.getPath()) cookie.setPath("/"); if (Strings.isNullOrEmpty(cookie.getName())) cookie.setName(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); return cookie; } @Bean public Cookie rememberMeCookie(){ SimpleCookie cookie = new SimpleCookie("rememberMe"); cookie.setHttpOnly(true); cookie.setMaxAge(2592000); return cookie; } @Bean @Autowired @Qualifier("rememberMeCookie") public CookieRememberMeManager rememberMeManager(SimpleCookie rememberMeCookie) throws BeansException { CookieRememberMeManager rememberMeManager = new CookieRememberMeManager(); rememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag==")); rememberMeManager.setCookie(rememberMeCookie); return rememberMeManager; } @Bean @Autowired public SessionDAO sessionDAO(@Qualifier("sessionIdGenerator") SessionIdGenerator sessionIdGenerator, CacheManager cacheManager){ EnterpriseCacheSessionDAO sessionDAO = new EnterpriseCacheSessionDAO(); sessionDAO.setActiveSessionsCacheName(JedisCacheManager.sessionName); sessionDAO.setSessionIdGenerator(sessionIdGenerator); sessionDAO.setCacheManager(cacheManager); return sessionDAO; } @Bean public QuartzSessionValidationScheduler sessionValidationScheduler(){ QuartzSessionValidationScheduler scheduler = new QuartzSessionValidationScheduler(); scheduler.setSessionValidationInterval(10000); //scheduler.setSessionManager((ValidatingSessionManager)applicationContext.getBean("sessionManager")); return scheduler; } @Bean @Autowired public SessionManager sessionManager(QuartzSessionValidationScheduler scheduler, SessionDAO sessionDAO, @Qualifier("sessionIdCookie") Cookie sessionIdCookie){ AppDefaultWebSessionManager sessionManager = new AppDefaultWebSessionManager(); sessionManager.setGlobalSessionTimeout(7200000); sessionManager.setDeleteInvalidSessions(true); sessionManager.setSessionValidationSchedulerEnabled(false); //关闭session检查,否则会乱扫描redis //sessionManager.setSessionValidationScheduler(scheduler); scheduler.setSessionManager(sessionManager); sessionManager.setSessionDAO(sessionDAO); sessionManager.setSessionIdCookieEnabled(true); sessionManager.setSessionIdCookie(sessionIdCookie); return sessionManager; } @Bean @Autowired public SecurityManager securityManager(List<Realm> realms, SessionManager sessionManager, CacheManager cacheManager, RememberMeManager rememberMeManager){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealms(realms); securityManager.setSessionManager(sessionManager); securityManager.setCacheManager(cacheManager); //securityManager.setRememberMeManager(rememberMeManager); SecurityUtils.setSecurityManager(securityManager); return securityManager; } @Bean @Autowired public AuthenticationFilter oAuth2AuthenticationFilter(EtaAuthProperties properties){ OAuth2AuthenticationFilter oAuth2AuthenticationFilter = new OAuth2AuthenticationFilter(); oAuth2AuthenticationFilter.setAuthcCodeParam("code"); oAuth2AuthenticationFilter.setFailureUrl("/error"); oAuth2AuthenticationFilter.setProperties(properties); return oAuth2AuthenticationFilter; } @Bean @Autowired public Filter shiroFilter(SecurityManager securityManager, @Qualifier("oAuth2AuthenticationFilter") AuthenticationFilter oath2Filter, EtaAuthProperties properties, EtaAuthFilter authFilter, MobileAuthFilter mobileAuthFilter, CurrentUserEnvFilter userEnvFilter, EtaEgFilter etaEgFilter) throws Exception{ ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean(); filterFactoryBean.setSecurityManager(securityManager); filterFactoryBean.setLoginUrl(null); filterFactoryBean.setSuccessUrl("/"); Map<String, Filter> filters = new HashMap<>(); filters.put("oauth2Authc", oath2Filter); filters.put("mobileAuthFilter",mobileAuthFilter); filters.put("userEnv", userEnvFilter); filters.put("etaEgFilter", etaEgFilter); filters.put("perm", authFilter); filterFactoryBean.setFilters(filters); Map<String, String> map = new HashMap<>(); String ssoPath; try { URL url = new URL(properties.getOauth2().sso.loginPath); ssoPath = url.getPath(); }catch (Exception e){ ssoPath = properties.getOauth2().sso.loginPath; } if (properties.off){ map.put("/**", "anon, userEnv"); }else{ map.put("/", "anon"); //这个地方有问题,先放着,放在这里能发现更多问题 map.put("/error", "anon"); map.put(ssoPath, "oauth2Authc"); /*map.put("/logout", "logout"); lout使用自己controller*/ /*为政务提供的需要签名认证的api*/ map.put("/openApi/**", "etaEgFilter"); map.put("/**", "mobileAuthFilter, perm, userEnv"); filterFactoryBean.setFilterChainDefinitionMap(map); } return new EtaWebAuthShiroFilterWrapper((AbstractShiroFilter) filterFactoryBean.getObject()); } @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){ return new LifecycleBeanPostProcessor(); } } ``` 另一个:com.dtdream.eta.web.uaa.autoconfigure.ShiroAutoConfiguration ``` package com.dtdream.eta.web.uaa.autoconfigure; import com.dtdream.eta.web.common.ca.realm.CABindingRealm; import com.dtdream.eta.web.common.ca.realm.CARealm; import com.dtdream.eta.web.common.shiro.ShiroFilterWrapper; import com.dtdream.eta.web.uaa.cache.JedisCacheManager; import com.dtdream.eta.web.uaa.filter.LoginFilter; import com.dtdream.eta.web.uaa.realm.*; import com.dtdream.eta.web.uaa.session.UaaWebSessionManager; import com.google.common.base.Strings; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.codec.Base64; import org.apache.shiro.mgt.RememberMeManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.realm.Realm; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator; import org.apache.shiro.session.mgt.eis.SessionDAO; import org.apache.shiro.session.mgt.eis.SessionIdGenerator; import org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.CookieRememberMeManager; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.servlet.AbstractShiroFilter; import org.apache.shiro.web.servlet.Cookie; import org.apache.shiro.web.servlet.ShiroHttpSession; import org.apache.shiro.web.servlet.SimpleCookie; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; import javax.servlet.Filter; import java.util.HashMap; import java.util.List; import java.util.Map; /** * */ @Configuration @Slf4j public class ShiroAutoConfiguration { @Bean @Autowired public CacheManager cacheManager(EtaUaaProperties properties, RedisTemplate redisTemplate){ return new JedisCacheManager(redisTemplate); } @Bean @Autowired public ShiroRealm shiroRealm(){ ShiroRealm shiroRealm = new ShiroRealm(); return shiroRealm; } @Bean @Autowired public ThirdPartyRealm ThirdPartyRealm(){ ThirdPartyRealm thirdPartyRealm = new ThirdPartyRealm(); return thirdPartyRealm; } @Bean @Autowired public SmsRealm smsRealm() { SmsRealm smsRealm = new SmsRealm(); return smsRealm; } @Bean @Autowired public CARealm caRealm(){ CARealm caRealm = new CARealm(); return caRealm; } @Bean @Autowired public CABindingRealm caBindingRealm(){ CABindingRealm caBindingRealm = new CABindingRealm(); return caBindingRealm; } @Bean public SessionIdGenerator sessionIdGenerator(){ return new JavaUuidSessionIdGenerator(); } @Bean @Autowired public Cookie sessionIdCookie(EtaUaaProperties properties){ SimpleCookie template = properties.getCookie(); SimpleCookie cookie; if (null == template){ cookie = new SimpleCookie(); cookie.setPath("/"); cookie.setName(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); return cookie; } cookie = new SimpleCookie(template); if (null == cookie.getPath()) cookie.setPath("/"); if (Strings.isNullOrEmpty(cookie.getName())) cookie.setName(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); return cookie; } @Bean public Cookie rememberMeCookie(){ SimpleCookie cookie = new SimpleCookie("rememberMe"); cookie.setHttpOnly(true); cookie.setMaxAge(2592000); return cookie; } @Bean @Autowired @Qualifier("rememberMeCookie") public CookieRememberMeManager rememberMeManager(SimpleCookie rememberMeCookie) throws BeansException { CookieRememberMeManager rememberMeManager = new CookieRememberMeManager(); rememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag==")); rememberMeManager.setCookie(rememberMeCookie); return rememberMeManager; } @Bean @Autowired public SessionDAO sessionDAO(@Qualifier("sessionIdGenerator") SessionIdGenerator sessionIdGenerator, CacheManager cacheManager){ EnterpriseCacheSessionDAO sessionDAO = new EnterpriseCacheSessionDAO(); sessionDAO.setActiveSessionsCacheName(JedisCacheManager.sessionName); sessionDAO.setSessionIdGenerator(sessionIdGenerator); sessionDAO.setCacheManager(cacheManager); return sessionDAO; } @Bean public QuartzSessionValidationScheduler sessionValidationScheduler(){ QuartzSessionValidationScheduler scheduler = new QuartzSessionValidationScheduler(); scheduler.setSessionValidationInterval(7200000); //scheduler.setSessionManager((ValidatingSessionManager)applicationContext.getBean("sessionManager")); return scheduler; } @Bean @Autowired public SessionManager sessionManager(QuartzSessionValidationScheduler scheduler, SessionDAO sessionDAO, @Qualifier("sessionIdCookie") Cookie sessionIdCookie){ UaaWebSessionManager sessionManager = new UaaWebSessionManager(); sessionManager.setGlobalSessionTimeout(7200000); sessionManager.setDeleteInvalidSessions(true); sessionManager.setSessionValidationSchedulerEnabled(false); /*sessionManager.setSessionValidationScheduler(scheduler);*/ scheduler.setSessionManager(sessionManager); sessionManager.setSessionDAO(sessionDAO); sessionManager.setSessionIdCookieEnabled(true); sessionManager.setSessionIdCookie(sessionIdCookie); return sessionManager; } @Bean @Autowired public SecurityManager securityManager(List<Realm> realms, SessionManager sessionManager, CacheManager cacheManager, RememberMeManager rememberMeManager){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealms(realms); securityManager.setSessionManager(sessionManager); securityManager.setCacheManager(cacheManager); //securityManager.setRememberMeManager(rememberMeManager); SecurityUtils.setSecurityManager(securityManager); return securityManager; } @Bean @Autowired public Filter shiroFilter(SecurityManager securityManager, EtaUaaProperties properties, LoginFilter loginFilter) throws Exception { ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean(); filterFactoryBean.setSecurityManager(securityManager); filterFactoryBean.setLoginUrl(null); filterFactoryBean.setSuccessUrl("/"); Map<String, Filter> filters = new HashMap<>(); filters.put("loginFilter", loginFilter); filterFactoryBean.setFilters(filters); Map<String, String> map = new HashMap<>(); if (properties.off) { map.put("/**", "anon"); } else { map.put("/login", "loginFilter"); map.put("/iframe/login", "loginFilter"); map.put("/**", "anon"); } filterFactoryBean.setFilterChainDefinitionMap(map); return new ShiroFilterWrapper((AbstractShiroFilter) filterFactoryBean.getObject()); } @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){ return new LifecycleBeanPostProcessor(); } } ```
通过Php程序 像数据库插入内容时。在页面提交之后,mysql会有两个相同的数据 只有id不同
if($action == 'insert'){ //接收数据 $title = empty($_POST['subject']) ? '' : $_POST['subject']; $content = empty($_POST['content']) ? '' : $_POST['content']; $user_id = $_SESSION['myuser']['id']; $create_ad = time(); $summary = empty($_POST['summary']) ? '' : $_POST['summary']; $category_id = empty($_POST['category_id']) ? '' : $_POST['category_id']; $cover = empty($_POST['cover']) ? 'mr.jpg' : $_POST['cover']; $state = empty($_POST['submit']) ? '' : $_POST['submit']; $is_delete = 0; $tags = ''; //验证 if($category_id == '' || $title == '' || $content = '' || $summary == ''){ header('refresh : 2 ; url = article.php?a=add'); echo '输入的信息有误,请重新输入'; exit; } //入库 $sql = "INSERT INTO `tn_article` VALUES(null, '$title','$content', $user_id, $create_ad, '$summary', $category_id, '$cover', '$state', '$is_delete', '$tags')"; //获取页面 if($dao ->query($sql)){ header('location:article.php?a=list'); exit; } else{ header('refresh : 2; url = article.php?a=add'); echo '添加失败'; exit; } }
ecshop url修改的问题
我要做ecshop分享返利功能,准备给用商品详情页url添加参数user_id 和user_name 两个参数,并且通过url上的参数显示会员分享的先后顺序 比如 goods.php?id=119&uid=62&uname=wang+ id=119&uid=63&uname=wang1+ id=119&uid=64&uname=wang2 所以我在lib.common.php添加代码 case 'goods': if (empty($gid)) { return false; } else $uid = $_SESSION['user_id']; $username = $_SESSION['user_name']; $uri = $rewrite ? 'goods-' . $gid : 'goods.php?id=' . $gid .'&uid='.$uid .'&username='.$username; $query = $_SERVER['QUERY_STRING']; $uri = $uri.'+'.$query; echo $uri; } 可是他显示不正常,是什么原因
flask+mysql实现的web应用,在注册页面点击注册后提示 Instance '<User at 0x5486a10>' has been deleted?
##问题描述 从github(https://github.com/num10/transfile)上下载的一个用flask+mysql实现的转pdf成word的web应用,其中 涉及到新用户的注册: ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573098094_252858.png) 可是在注册页面填完信息点击注册后前端报错如下: ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573098203_905955.png) ``` sqlalchemy.orm.exc.ObjectDeletedError: Instance '<User at 0x58072f0>' has been deleted, or its row is otherwise not present. ``` 根据traceback的信息,定位到出错的位置应该是下图中的models.py和views.py文件 ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573100399_404211.jpg) 后台关于这两个文件的报错信息为: ```ruby File "C:\Users\26808\transfile-master\app\auth\views.py", line 68, in register token = user.generate_confirmation_token() File "C:\Users\26808\transfile-master\app\models.py", line 142, in generate_confirmation_token return s.dumps({'confirm': self.id}).decode('utf-8') ``` 对应文件中: views.py: ```ruby @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, '认证您的账户', 'auth/email/confirm', user=user, token=token) flash('认证信息已发送至您的邮箱') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form) ``` models.py: ``` def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}).decode('utf-8') ``` ##补充 1.按照requirements文件的要求,flask都安装了正确的包 2.正如register函数中所写的那样,点击注册后用户信息会被加入mysql数据库中但是会被重复加入,即多次运行每次都出错,并且相同的用户被反复加入mysql数据库中 3.网上大多数都是通过app.run()来启动文件的,但是这个项目里面先要设置 ```set FLASK_APP = manage.py``` 在```flask run```才能运行 能解释一下为什么吗? manage.py代码如下: ```ruby #!/usr/bin/ python # -*- coding: UTF-8 -*- import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() import sys import click from flask_migrate import Migrate,upgrade from app import create_app, db from app.models import User, Follow, Role, Permission, Post, Comment from flask_uploads import configure_uploads from app.auth.forms import pdfs,photos,words app = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(app, db) configure_uploads(app, pdfs) configure_uploads(app, photos) configure_uploads(app, words) @app.shell_context_processor def make_shell_context(): return dict(db=db, User=User, Follow=Follow, Role=Role, Permission=Permission, Post=Post, Comment=Comment) @app.cli.command() @click.option('--coverage/--no-coverage', default=False, help='Run tests under code coverage.') def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import subprocess os.environ['FLASK_COVERAGE'] = '1' sys.exit(subprocess.call(sys.argv)) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() @app.cli.command() @click.option('--length', default=25, help='Number of functions to include in the profiler report.') @click.option('--profile-dir', default=None, help='Directory where profiler data files are saved.') def profile(length=25, profile_dir=None): """Start the application under the code profiler.""" from werkzeug.contrib.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir) app.run(debug=False) @app.cli.command() def deploy(): """Run deployment tasks.""" # migrate database to latest revision upgrade() # create or update user roles Role.insert_roles() # ensure all users are following themselves User.add_self_follows() if __name__ == '__main__': deploy() ``` 数据模型models.py: ``` #!/usr/bin/ python # -*- coding: UTF-8 -*- from datetime import datetime import hashlib from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from markdown import markdown import bleach from flask import current_app, request,url_for from flask_login import UserMixin, AnonymousUserMixin from . import db, login_manager class Permission: FOLLOW = 1 COMMENT = 2 WRITE = 4 MODERATE = 8 ADMIN = 16 class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) default = db.Column(db.Boolean, default=False, index=True) permissions = db.Column(db.Integer) users = db.relationship('User', backref='role', lazy='dynamic') def __init__(self, **kwargs): super(Role, self).__init__(**kwargs) if self.permissions is None: self.permissions = 0 @staticmethod def insert_roles(): roles = { 'User': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE], 'Moderator': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE, Permission.MODERATE], 'Administrator': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE, Permission.MODERATE, Permission.ADMIN], } default_role = 'User' for r in roles: role = Role.query.filter_by(name=r).first() if role is None: role = Role(name=r) role.reset_permissions() for perm in roles[r]: role.add_permission(perm) role.default = (role.name == default_role) db.session.add(role) db.session.commit() def add_permission(self, perm): if not self.has_permission(perm): self.permissions += perm def remove_permission(self, perm): if self.has_permission(perm): self.permissions -= perm def reset_permissions(self): self.permissions = 0 def has_permission(self, perm): return self.permissions & perm == perm def __repr__(self): return '<Role %r>' % self.name class Follow(db.Model): __tablename__ = 'follows' follower_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) followed_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) timestamp = db.Column(db.DateTime, default=datetime.utcnow) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') comments = db.relationship('Comment', backref='author', lazy='dynamic') @staticmethod def add_self_follows(): for user in User.query.all(): if not user.is_following(user): user.follow(user) db.session.add(user) db.session.commit() def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['FLASKY_ADMIN']: self.role = Role.query.filter_by(name='Administrator').first() if self.role is None: self.role = Role.query.filter_by(default=True).first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = self.gravatar_hash() self.follow(self) @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}).decode('utf-8') def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}).decode('utf-8') @staticmethod def reset_password(token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False user = User.query.get(data.get('reset')) if user is None: return False user.password = new_password db.session.add(user) return True def can(self, perm): return self.role is not None and self.role.has_permission(perm) def is_administrator(self): return self.can(Permission.ADMIN) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def gravatar_hash(self): return hashlib.md5(self.email.lower().encode('utf-8')).hexdigest() def gravatar(self, size=100, default='identicon', rating='g'): url = 'https://secure.gravatar.com/avatar' hash = self.avatar_hash or self.gravatar_hash() return '{url}/{hash}?s={size}&d={default}&r={rating}'.format( url=url, hash=hash, size=size, default=default, rating=rating) def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): if user.id is None: return False return self.followed.filter_by( followed_id=user.id).first() is not None def is_followed_by(self, user): if user.id is None: return False return self.followers.filter_by( follower_id=user.id).first() is not None @property def followed_posts(self): return Post.query.join(Follow, Follow.followed_id == Post.author_id)\ .filter(Follow.follower_id == self.id) def to_json(self): json_user = { 'url': url_for('api.get_user', id=self.id), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts_url': url_for('api.get_user_posts', id=self.id), 'followed_posts_url': url_for('api.get_user_followed_posts', id=self.id), 'post_count': self.posts.count() } return json_user def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('utf-8') @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return None return User.query.get(data['id']) def __repr__(self): return '<User %r>' % self.username class AnonymousUser(AnonymousUserMixin): def can(self, permissions): return False def is_administrator(self): return False login_manager.anonymous_user = AnonymousUser @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) body_html = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) comments = db.relationship('Comment', backref='post', lazy='dynamic') @staticmethod def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) def to_json(self): json_post = { 'url': url_for('api.get_post', id=self.id), 'body': self.body, 'body_html': self.body_html, 'timestamp': self.timestamp, 'author_url': url_for('api.get_user', id=self.author_id), 'comments_url': url_for('api.get_post_comments', id=self.id), 'comment_count': self.comments.count() } return json_post @staticmethod def from_json(json_post): body = json_post.get('body') if body is None or body == '': raise ValidationError('post does not have a body') return Post(body=body) db.event.listen(Post.body, 'set', Post.on_changed_body) class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) body_html = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) disabled = db.Column(db.Boolean) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) post_id = db.Column(db.Integer, db.ForeignKey('posts.id')) @staticmethod def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i', 'strong'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) db.event.listen(Comment.body, 'set', Comment.on_changed_body) ```
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
【JSON解析】浅谈JSONObject的使用
简介 在程序开发过程中,在参数传递,函数返回值等方面,越来越多的使用JSON。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,同时也易于机器解析和生成、易于理解、阅读和撰写,而且Json采用完全独立于语言的文本格式,这使得Json成为理想的数据交换语言。 JSON建构于两种结构: “名称/值”对的集合(A Collection of name/va...
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
只因接了一个电话,程序员被骗 30 万!
今天想给大家说一个刚刚发生在我身边的一起真实的诈骗经历,我的朋友因此被骗走30万。注:为了保护当事人隐私,部分情节进行了修改。1平安夜突来的电话开始以为就像普通的诈骗一样,想办法让你把钱...
我一个37岁的程序员朋友
周末了,人一旦没有点事情干,心里就瞎想,而且跟几个老男人坐在一起,更容易瞎想,我自己现在也是 30 岁了,也是无时无刻在担心自己的职业生涯,担心丢掉工作没有收入,担心身体机能下降,担心突...
python自动下载图片
近日闲来无事,总有一种无形的力量萦绕在朕身边,让朕精神涣散,昏昏欲睡。 可是,像朕这么有职业操守的社畜怎么能在上班期间睡瞌睡呢,我不禁陷入了沉思。。。。 突然旁边的IOS同事问:‘嘿,兄弟,我发现一个网站的图片很有意思啊,能不能帮我保存下来提升我的开发灵感?’ 作为一个坚强的社畜怎么能说自己不行呢,当时朕就不假思索的答应:‘oh, It’s simple. Wait for me for a ...
一名大专同学的四个问题
【前言】   收到一封来信,赶上各种事情拖了几日,利用今天要放下工作的时机,做个回复。   2020年到了,就以这一封信,作为开年标志吧。 【正文】   您好,我是一名现在有很多困惑的大二学生。有一些问题想要向您请教。   先说一下我的基本情况,高考失利,不想复读,来到广州一所大专读计算机应用技术专业。学校是偏艺术类的,计算机专业没有实验室更不用说工作室了。而且学校的学风也不好。但我很想在计算机领...
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
Java 14 都快来了,为什么还有这么多人固守Java 8?
从Java 9开始,Java版本的发布就让人眼花缭乱了。每隔6个月,都会冒出一个新版本出来,Java 10 , Java 11, Java 12, Java 13, 到2020年3月份,...
达摩院十大科技趋势发布:2020 非同小可!
【CSDN编者按】1月2日,阿里巴巴发布《达摩院2020十大科技趋势》,十大科技趋势分别是:人工智能从感知智能向认知智能演进;计算存储一体化突破AI算力瓶颈;工业互联网的超融合;机器间大规模协作成为可能;模块化降低芯片设计门槛;规模化生产级区块链应用将走入大众;量子计算进入攻坚期;新材料推动半导体器件革新;保护数据隐私的AI技术将加速落地;云成为IT技术创新的中心 。 新的画卷,正在徐徐展开。...
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
立即提问