C#.net html代码如何生成新页面

新手上路,请问:如何在C#.net中实现新页面中打开html字符串呢
例如:后台程序有html字符串变量为str,如何单击按钮后,在另一页面中打开这个html页面呢,不是显示html代码
我用Response.Write(str);倒是打开了,但替换了原页面,如何在新页面实现呢

1个回答

window.open另外打开一个页面,不要再新页面打开,然后在Response.Write

showbo
支付宝加好友偷能量挖 回复happyarbing: <a href="xxxxxxx.aspx" target="_blank">输出str</a>,xxxxxx.aspx中Response.Write输出str,多去学下基础html,不要老依赖服务器端控件
3 年多之前 回复
happyarbing
happyarbing 回复无聊码农: 你好,我是新手,怎么写呢,谢谢!
3 年多之前 回复
showbo
支付宝加好友偷能量挖 不要再当前页面跳转
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
html字符串如何显示页面
C#.net中,后台有字符串str为某个网页的html代码,如何实现单击按钮后,在新页面中打开该html网页呢
.net生成大量静态页面速度问题(新手)
.net生成大量静态页面速度太慢,想使用多线程解决这个问题。但不会用。请大家帮忙!!!!现在1000多条新闻要三四分钟。 附上需要修改的代码: ``` protected void wznewxq_Click(object sender, EventArgs e) { string q1 = "select NS_Id from NewsSort where NS_Stop=0 order by NS_Order desc"; DataSet qq1 = DBHelper.GetDataSet(q1); int a = 0; for (int q = 0; q < qq1.Tables[0].Rows.Count; q++) { string w1 = "select * from News,NewsSort where News.N_Sortid=NewsSort.NS_Id and N_Sortid=" + qq1.Tables[0].Rows[q]["NS_Id"] + " and N_Show=1 order by N_Order desc"; DataSet ww1 = DBHelper.GetDataSet(w1); string w2 = "select top 1 N_Order from News where N_Sortid=" + qq1.Tables[0].Rows[q]["NS_Id"] + " and N_Show=1 order by N_Order desc"; DataSet ww2 = DBHelper.GetDataSet(w2); string w3 = "select top 1 N_Order from News where N_Sortid=" + qq1.Tables[0].Rows[q]["NS_Id"] + " and N_Show=1 order by N_Order asc"; DataSet ww3 = DBHelper.GetDataSet(w3); for (int m = 0; m < ww1.Tables[0].Rows.Count; m++) { //替换掉模板中的特征字符 string mbPath = Server.MapPath("/manager/n134.html"); Encoding code = Encoding.GetEncoding("UTF-8"); StreamReader sr = null; StreamWriter sw = null; string str = null; //读取 try { sr = new StreamReader(mbPath, code); str = sr.ReadToEnd(); } catch (Exception ex) { throw ex; } finally { sr.Close(); } Inittail(); Inittop(); StringBuilder sq = new StringBuilder(); sq.Append("<div class=\"ncont_page\">" + "\n"); if (Convert.ToString(ww1.Tables[0].Rows[m]["N_Order"]) == Convert.ToString(ww2.Tables[0].Rows[0]["N_Order"]) && Convert.ToString(ww1.Tables[0].Rows[m]["N_Order"]) == Convert.ToString(ww3.Tables[0].Rows[0]["N_Order"])) { sq.Append("<p class=\"l\">上一篇:没有了</p>" + "\n"); sq.Append("<p class=\"r\">下一篇:没有了</p>" + "\n"); } else if (Convert.ToString(ww1.Tables[0].Rows[m]["N_Order"]) == Convert.ToString(ww2.Tables[0].Rows[0]["N_Order"]) && Convert.ToString(ww1.Tables[0].Rows[m]["N_Order"]) != Convert.ToString(ww3.Tables[0].Rows[0]["N_Order"])) { string r2 = "select top 1 N_Url,N_Name from News where N_Order < " + ww1.Tables[0].Rows[m]["N_Order"] + " and N_Show=1 and N_Sortid=" + qq1.Tables[0].Rows[q]["NS_Id"] + " order by N_Order desc"; DataSet t2 = DBHelper.GetDataSet(r2); sq.Append("<p class=\"l\">上一篇:没有了</p>" + "\n"); sq.Append("<p class=\"r\">下一篇:<a href = \"" + t2.Tables[0].Rows[0]["N_Url"] + "\" title=\"" + t2.Tables[0].Rows[0]["N_Name"] + "\">" + t2.Tables[0].Rows[0]["N_Name"] + "</a></p>" + "\n"); } else if (Convert.ToString(ww1.Tables[0].Rows[m]["N_Order"]) == Convert.ToString(ww3.Tables[0].Rows[0]["N_Order"]) && Convert.ToString(ww1.Tables[0].Rows[m]["N_Order"]) != Convert.ToString(ww2.Tables[0].Rows[0]["N_Order"])) { string r1 = "select top 1 N_Url,N_Name from News where N_Order > " + ww1.Tables[0].Rows[m]["N_Order"] + " and N_Show=1 and N_Sortid=" + qq1.Tables[0].Rows[q]["NS_Id"] + " order by N_Order asc"; DataSet t1 = DBHelper.GetDataSet(r1); sq.Append("<p class=\"l\">上一篇:<a href = \"" + t1.Tables[0].Rows[0]["N_Url"] + "\" title=\"" + t1.Tables[0].Rows[0]["N_Name"] + "\">" + t1.Tables[0].Rows[0]["N_Name"] + "</a></p>" + "\n"); sq.Append("<p class=\"r\">下一篇:没有了 </p>" + "\n"); } else { string r1 = "select top 1 N_Url,N_Name from News where N_Order > " + ww1.Tables[0].Rows[m]["N_Order"] + " and N_Show=1 and N_Sortid=" + qq1.Tables[0].Rows[q]["NS_Id"] + " order by N_Order asc"; DataSet t1 = DBHelper.GetDataSet(r1); string r2 = "select top 1 N_Url,N_Name from News where N_Order < " + ww1.Tables[0].Rows[m]["N_Order"] + " and N_Show=1 and N_Sortid=" + qq1.Tables[0].Rows[q]["NS_Id"] + " order by N_Order desc"; DataSet t2 = DBHelper.GetDataSet(r2); sq.Append("<p class=\"l\">上一篇:<a href = \"" + t1.Tables[0].Rows[0]["N_Url"] + "\" title=\"" + t1.Tables[0].Rows[0]["N_Name"] + "\">" + t1.Tables[0].Rows[0]["N_Name"] + "</a></p>" + "\n"); sq.Append("<p class=\"r\">下一篇:<a href = \"" + t2.Tables[0].Rows[0]["N_Url"] + "\" title=\"" + t2.Tables[0].Rows[0]["N_Name"] + "\">" + t2.Tables[0].Rows[0]["N_Name"] + "</a></p>" + "\n"); } sq.Append("</div>" + "\n"); string[] ids; string sn = ww1.Tables[0].Rows[m]["N_Pid"].ToString(); StringBuilder xa1 = new StringBuilder(); StringBuilder xa = new StringBuilder(); if (sn != "") { xa.Append("<div id=\"pro\" class=\"proj_pro\">" + "\n"); xa.Append("<h2>相关产品</h2>" + "\n"); xa.Append("<ul>" + "\n"); ids = sn.Split(','); if (ids.Length >= 4) { for (int k = 0; k < 4; k++) { int id = Convert.ToInt32(ids[k]); string wa = "select P_Url,P_Pic,P_Name from Product where P_Id=" + id + ""; DataSet ws = DBHelper.GetDataSet(wa); xa.Append("<li>" + "\n"); xa.Append("<a href=\"" + ws.Tables[0].Rows[0]["P_Url"] + "\"><img src=\"" + ws.Tables[0].Rows[0]["P_Pic"] + "\" alt=\"" + ws.Tables[0].Rows[0]["P_Name"] + "\" /></a>" + "\n"); xa.Append("<a href=\"" + ws.Tables[0].Rows[0]["P_Url"] + "\">" + "\n"); xa.Append("<p>" + ws.Tables[0].Rows[0]["P_Name"] + "</p>" + "\n"); xa.Append("</a>" + "\n"); xa.Append("</li>" + "\n"); } } else { for (int k = 0; k < ids.Length; k++) { int id = Convert.ToInt32(ids[k]); string wa = "select P_Url,P_Pic,P_Name from Product where P_Id=" + id + ""; DataSet ws = DBHelper.GetDataSet(wa); xa.Append("<li>" + "\n"); xa.Append("<a href=\"" + ws.Tables[0].Rows[0]["P_Url"] + "\">" + "\n"); xa.Append("<img src=\"" + ws.Tables[0].Rows[0]["P_Pic"] + "\" alt=\"" + ws.Tables[0].Rows[0]["P_Name"] + "\" /></a>" + "\n"); xa.Append("<a href=\"" + ws.Tables[0].Rows[0]["P_Url"] + "\">" + "\n"); xa.Append("<p>" + ws.Tables[0].Rows[0]["P_Name"] + "</p>" + "\n"); xa.Append("</a>" + "\n"); xa.Append("</li>" + "\n"); } } xa.Append("</ul>" + "\n"); xa.Append("</div>" + "\n"); } string[] idm; string snm = ww1.Tables[0].Rows[m]["N_Nlistid"].ToString(); StringBuilder mm1 = new StringBuilder(); if (snm != "") { mm1.Append("<div id =\"rptnews\" class=\"ncont_news\">" + "\n"); mm1.Append("<h2>相关新闻</h2>" + "\n"); mm1.Append("<ul>" + "\n"); idm = snm.Split(','); for (int k = 0; k < idm.Length; k++) { int id = Convert.ToInt32(idm[k]); string wa = "select * from News where N_Id=" + id + ""; DataSet ws = DBHelper.GetDataSet(wa); mm1.Append("<li>" + "\n"); mm1.Append("<a href =\"" + ws.Tables[0].Rows[0]["N_Url"] + "\">" + ws.Tables[0].Rows[0]["N_Name"] + "</a>" + "\n"); mm1.Append("</li>" + "\n"); } mm1.Append("</ul>" + "\n"); mm1.Append("</div>" + "\n"); } string mx1 = mm1.ToString(); string xx1 = xa.ToString(); string st = sq.ToString(); string biaoti = ww1.Tables[0].Rows[m]["N_Name"].ToString(); string Ncaption = ww1.Tables[0].Rows[m]["N_Title"].ToString(); string Nkeyword = ww1.Tables[0].Rows[m]["N_Keywords"].ToString(); string Ndescribe = ww1.Tables[0].Rows[m]["N_Description"].ToString(); string dizhi = ww1.Tables[0].Rows[m]["NS_Name"].ToString(); string weizhi = ww1.Tables[0].Rows[m]["NS_Url"].ToString(); string time = ww1.Tables[0].Rows[m]["N_Date"].ToString(); string conter = ww1.Tables[0].Rows[m]["N_Content"].ToString(); //根据时间自动重命名,扩展名也可以自行修改 str = str.Replace("$stm$", st); str = str.Replace("$mx1$", mx1); str = str.Replace("$xx1$", xx1); str = str.Replace("$top$", top); str = str.Replace("$tail$", tail); str = str.Replace("$time$", time); str = str.Replace("$conter$", conter); str = str.Replace("$Ndescribe$", Ndescribe); str = str.Replace("$Nkeyword$", Nkeyword); str = str.Replace("$biaoti$", biaoti); str = str.Replace("$weizhi$", weizhi); str = str.Replace("$dizhi$", dizhi); str = str.Replace("$Ncaption$", Ncaption); string fileName = "" + ww1.Tables[0].Rows[m]["N_Url"] + ""; //生成静态文件 try { sw = new StreamWriter(Server.MapPath("/") + fileName, false, code); sw.Write(str); sw.Flush(); } catch (Exception ex) { throw ex; } finally { sw.Close(); } a = m; } } Response.Write("<script>alert('共生成了" + a + "个页面。')</script>"); } ```
C#采集网页,模拟点击后无法加载新页面
采集该网址: http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=3&qs=pc_%7Esoniu%7Estock%7Estock%7Ehistory%7Equery&selfsectsn=&querytype=&searchfilter=&tid=stockpick&w=%E6%A6%82%E5%BF%B5%E6%9D%BF%E5%9D%97%EF%BC%8C%E5%9F%8E%E5%B8%82 要求:模拟点击下一页,选择显示70/条每页,(抓包不知是否可获得下一页的地址),我的代码如下,运行后获得的html代码仍为第一页,没有翻页。 public class gWebByWebBrowser { WebBrowser web; HtmlElement btnAdd = null; public gWebByWebBrowser(){ web = new WebBrowser(); } public string GetHtml(string url, WBrowserPara wBrowserPara){ //web.DocumentCompleted += web_DocumentCompleted; web.Navigate(url); while (web.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents(); eventCounter = 0; operation(); return web.DocumentText; } void operation(){ // 模拟操作 HtmlElementCollection Aresults = web.Document.GetElementsByTagName("a"); foreach (HtmlElement item in Aresults){ if (item.InnerHtml == "下页") { btnAdd = item; } } btnAdd.InvokeMember("onclick"); foreach (HtmlElement f in web.Document.GetElementsByTagName("option")) { if (f.InnerText == @"显示70条/页") { f.InvokeMember("Click"); f.SetAttribute("selected", "selected"); } } web.Refresh(); while (web.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents(); } }
Easy UI DataGrid 的分页组件,显示异常?
![初次进入情况](https://img-ask.csdn.net/upload/201907/31/1564565417_824443.png) ![刷新页面后的情况](https://img-ask.csdn.net/upload/201907/31/1564565431_21227.png) ![理论上正常的样子](https://img-ask.csdn.net/upload/201907/31/1564565436_754134.png) 不知道为啥分页组件全部挤在了右边这角落里面,强迫症已近哭晕在厕所 我是直接复制的理论上不存在问题,尝试了从easyui官网复制代码也是出问题,把那个页面在新窗口打开没有问题,
如何实现导航栏链接点击后跳转,新页面相应的链接添加颜色样式作用于a?
```html: <p class="nav"> <ul> <li class="active"><a href="a.html">aaa</a></li> <li><a href="b.html">bbb</a></li> <li><a href="c.html">ccc</a></li> </ul> </p> ``` ``` jquery: $(".nav li a").each(function (i) { var $me = $(this); var lochref = $.trim(window.location.href); var mehref = $.trim($me.get(0).href); if (lochref.indexOf(mehref) != -1) { $me.parent().addClass("active"); } else { $me.parent().removeClass("active"); } }); ``` ``` css: .active{background-color:#ed0505;} ``` 以上就是如何实现导航栏链接点击后跳转,新页面相应的链接添加颜色的详细内容,更多请关注php中文网其它相关文章! 这个代码能用,但是我想把那个active的样式作用于a,应该怎么改??现在只能作用于li。出不来我想要的效果。
使用jquery-powerfloat.js来实现的悬浮层效果在IE7或者IE8下运行,导致页面卡住
一、问题描述 在最近开发的asp.net项目使用jquery-powerfloat.js来实现网页上的悬浮层效果,当鼠标悬浮在网页的某个字符串上时显示悬浮层,移出该字符串不显示悬浮层。但是在IE7或者IE8浏览器上运行时,会导致页面卡住。 ![IE7下页面卡住截图](https://img-ask.csdn.net/upload/201911/12/1573549904_306764.png) 二、代码片段 1、主页面前端代码 ``` <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainForm.aspx.cs" Inherits="powerFloat.MainForm" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>主界面</title> </head> <body> <form id="mainform" runat="server"> <div runat="server" id="addDiv"> </div> </form> </body> </html> ``` 2、主页面的后台代码 ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace powerFloat { public partial class MainForm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!Page.IsCallback) { InitData(); } } private void InitData() { Control ctl = this.LoadControl("AddWebUserControl.ascx"); ctl.ID = "Test"; addDiv.Controls.Add(ctl); addDiv.Controls.Add(new LiteralControl("<br/>")); } } } ``` 3、悬浮层前端代码 ``` <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddWebUserControl.ascx.cs" Inherits="powerFloat.AddWebUserControl" %> <style> .dn { display: none; } .shadow { -moz-box-shadow: 1px 1px 3px rgba(0, 0, 0, 4); -webkit-box-shadow: 1px 1px 3px rgba(0, 0, 0, 4); box-shadow: 1px 1px 3px rgba(0, 0, 0, 4); } .target_box { width: 700px; padding: 10px; border: 1px solid #aaa; background-color: #fff; } .target_list { padding: 4px; border-bottom: 1px dotted #ddd; overflow: hidden; _zoom: 1; } .target_list a { width: 160px; line-height: 20px; margin-right: 5px; padding: 1px; color: #333; font-size: 12px; text-align: left; text-decoration: none; float: left; } .target_list .select1 { width: 200px; line-height: 20px; margin-right: 5px; padding: 1px; color: red; font-size: 20px; text-align: left; text-decoration: none; float: left; } .target_more { margin-top: -20px; } .target_fixed { height: 25px; padding: 1px; position: fixed; _position: adsolute; top: 0; right: 0; } .custom_container { position: absolute; background-color: rgba(0, 0, 0, 5); background-color: #fff; } .custom_container img { padding: 0; position: relative; top: -5px; left: -5px; } </style> <table> <tr> <td>总署查验要求18项</td> <td> <input type="hidden" runat="server" id="hdnClientId" /> <asp:Literal ID="txt_CHECK_REQUEST_TOTAL" runat="server"></asp:Literal> </td> </tr> </table> <asp:Literal runat="server" ID="targetBox"></asp:Literal> <script src="scripts/jquery-1.4.1.js"></script> <script src="scripts/jquery-powerFloat.js"></script> <script> $(function () { var clientId = $("#Test_hdnClientId").val(); $(clientId).powerFloat( ) }); </script> ``` 4、悬浮层后台代码 ``` using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace powerFloat { public partial class AddWebUserControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { if(!Page.IsCallback) { InitData(); } } private void InitData() { string checkRequestTotal = "000101010101001001"; txt_CHECK_REQUEST_TOTAL.Text = string.Format("<a id='{1}_trigger' href='javascript:;' rel='Test_targetBox'>{0}</a>", checkRequestTotal, this.ClientID); hdnClientId.Value = "#" + this.ClientID + "_trigger"; char[] splitChar = checkRequestTotal.ToCharArray(); ArrayList arrayList = new ArrayList(); for(int i=0;i<splitChar.Length;i++) { arrayList.Add(splitChar[i].ToString()); } string strHTML = @" <div id='ABC$$_targetBox' class='shadow target_box dn'> <div class='target_list'> <a href='javascript:;' class='select{0}'>1.辐射探测</a> <a href='javascript:;' class='select{1}'>2.预防性检疫处理</a> <a href='javascript:;' class='select{2}'>3.检查病媒/有害生物</a> </div> <div class='target_list'> <a href='javascript:;' class='select{3}'>4.动物临床检查</a> <a href='javascript:;' class='select{4}'>5.检查残留剂</a> <a href='javascript:;' class='select{5}'>6.检查车体/箱体</a> </div> <div class='target_list'> <a href='javascript:;' class='select{6}'>7.检查包装</a> <a href='javascript:;' class='select{7}'>8.核对品名</a> <a href='javascript:;' class='select{8}'>9.检查标签/标识</a> </div> <div class='target_list'> <a href='javascript:;' class='select{9}'>10.核对规格/型号</a> <a href='javascript:;' class='select{10}'>11.核对产终地</a> <a href='javascript:;' class='select{11}'>12.核对数量</a> </div> <div class='target_list'> <a href='javascript:;' class='select{12}'>13.核对重量</a> <a href='javascript:;' class='select{13}'>14.检查侵权</a> <a href='javascript:;' class='select{14}'>15.检查外观品质</a> </div> <div class='target_list'> <a href='javascript:;' class='select{15}'>16.检查夹藏/夹杂</a> <a href='javascript:;' class='select{16}'>17.检查温度</a> <a href='javascript:;' class='select{17}'>18.取样送检</a> </div> </div> "; targetBox.Text = string.Format(strHTML, arrayList.ToArray()).Replace("ABC$$", this.ClientID); } } } ``` 三、源码下载 代码使用vs2012开发的。(链接:https://pan.baidu.com/s/1Y2c3yfC7oenSZwSw1Uh0VQ 提取码:iqr4 ) 四、解决:由于jquery-powerfloat.js版本问题导致的,使用新的版本的就可以了。 jquery-powerfloat.js:链接:https://pan.baidu.com/s/1sKorCkN1UkmCFtf-6MNVxg 提取码:rh5n
HTML求助!代码和示例图如下,请问如何使得图片标注的五张图片垂直居中?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> header{background:#09F; height:50px; width:100%; line-height:20px;} aside{background:#C6F; height:850px; width:18%; float:left;} ul{list-style-type:none;} article{height:800px; width:65%; float:left;} footer{background:#99F; width:100%; height:50px; clear:left;} </style> </head> <body> <header> <img src="搜索.png" width="2%"/>移动端页面练习 </header> <aside> <ul> <li> <a href=""> <img src="支.png" width="25%" /> </a> </li><br /> <li> <a href=""> <img src="促.png" width="15%" /> </a> </li><br /> <li> <a href=""> <img src="订.png" width="15%" /> </a> </li><br /> <li> <a href=""> <img src="卡.png" width="15%" /> </a> </li><br /> <li> <a href=""> <img src="团.png" width="15%" /> </a> </li><br /> </ul> </aside> <article> <figure> <img src="食品.png" /> <img src="家庭电器.png" /> </figure> <figcaption>食品/家用电器 </figcaption> <figure> <img src="全新整车车品.png" /> <img src="居家生活.png" /> </figure> <figcaption>汽车/居家 </figcaption> <figure> <img src="手机数码.png" /> <img src="珠宝手表眼镜.png" /> </figure> <figcaption>手机/珠宝 </figcaption> </article> <footer> <nav> <ul> <a href=""> <img src="菜单.png" width="2%"/> </a> <a href=""> <img src="星星.png" width="2%" /> </a> <a href=""> <img src="vip.png" width="2%" /> </a> <a href=""> <img src="钱.png" width="2%" /> </a> <a href=""> <img src="购物.png" width="2%" /> </a> </ul> </nav> </footer> </body> </html> ``` ```
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) ```
python flask_sqlalchemy如何维护一个全局查询结果
在我的webapp中,每个页面都要用到同一个一般不会变化的查询结果,为避免每次访问都需查询一次这个变量,我在views.py中弄了一个全局变量ADMIN_NOTES ``` ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() ``` 而当ADMIN_NOTE会发生变化时,如此时管理员又写入了一个新note,则重新查询数据库获得最新的ADMIN_NOTE的值,尽量减少访问数据库的次数 我本想这么实现的(中间部分不重要的代码省略了) ``` #全局变量 ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() #写入新note的函数1 @app.route('/new_note',methods=['GET','POST']) def new_note(): global ADMIN_NOTES data=json.loads(request.get_data()) note=Note(title=data['note_title'],upload_time=datetime.utcnow()) db.session.add(note) db.session.commit() #若是管理员写入新note,则重新查询并修改全局变量ADMIN_NOTES if note.author.nickname=='ADMIN': ADMIN_NOTES=Note.query.filter_by(author_id=ADMIN.id).all() KAFENUT_NOTES[0].author.nickname #能正确访问ADMIN_NOTES print(len(ADMIN_NOTES)) #正确访问ADMIN_NOTES resp['success']=True resp['text']='Upload successfully!' resp['url']=url_for('note',note_id=note.id,nickname=note.author.nickname) #浏览器接受到服务器的json之后跳转到,resp[url]所指示的页面,即下面这个页面 return json.dumps(resp) #返回note页面的函数2 @app.route('/<nickname>/note/<note_id>',methods=['GET','POST']) def note(nickname,note_id): global ADMIN_NOTES user=User.query.filter_by(nickname=nickname).first() note=Note.query.filter_by(id=note_id).first() if request.method=='GET': note.view_num+=1 db.session.add(note) db.session.commit() for nnote in ADMIN_NOTES: print(nnote.author.nickname) #出错位置 return render_template('note_page.html',note=note,admin_notes=ADMIN_NOTES) ``` 然而问题也正出在这里,当管理员写入新的note之后(即ADMIN_NOTES这个全局变量发生变化之后)重新查询的语句虽然在函数1中执行了(print出的note数量是写入新note之后的数量,)。但当用户根据函数1返回的json跳转到函数2的时候,函数2内就无法正确访问ADMIN_NOTES,准确来说无法访问nnote.author.nickname,其中author是note表用author_id这个外键连接到user表得到的,错误栈如下 ``` Traceback (most recent call last): File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\MSI-1\Anaconda3\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "E:\vs\python\AwesomeWebApp\AwesomeWebApp\app\views.py", line 232, in note print(nnote.author.nickname) #let author.id be preloaded File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\attributes.py", line 282, in __get__ return self.impl.get(instance_state(instance), dict_) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\attributes.py", line 710, in get value = self.callable_(state, passive) File "C:\Users\MSI-1\Anaconda3\lib\site-packages\sqlalchemy\orm\strategies.py", line 688, in _load_for_state % (orm_util.state_str(state), self.key) sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Note at 0x26de5f41198> is not bound to a Session; lazy load operation of attribute 'author' cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3) ``` sqlalchemy报出detached错误 sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Note at 0x26de5f41198> is not bound to a Session; lazy load operation of attribute 'author' cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3) 这该怎么解决?或者还有什么其他方法实现:在我的webapp中,每个页面都要用到同一个一般不会变化的查询结果,为避免每次访问都需查询一次这个一般不会变量,我在views.py中弄了一个全局变量ADMIN_NOTES。而当ADMIN_NOTE会发生变化时,如此时管理员又写入了一个新note,则重新查询数据库获得最新的ADMIN_NOTE的值,尽量减少访问数据库的次数
分页后GrideView新增一行空白行
项目中有个需求,需要对已经绑定数据并分页的GrideView进行新增一行空白行。用户在点击“新增行”后,在界GrideView界面的最下面增加一行空白行。 要求:1、用户在第几页点击新增行就在当前页面显示新增行; 2、新增行按钮在GrideView外面; 具体代码如下: ``` 前台页面代码: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="YPCGJCB.aspx.cs" Inherits="CenterBase.供应链管理.YPCGJCB" %> <%@ Register Assembly="UserControls" Namespace="UserControls" TagPrefix="cc2" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>药品折扣基础表</title> <link rel="stylesheet" href="../js/Grid/css/demo_page.css" /> <link rel="stylesheet" href="../js/DatePicker/base/jquery-ui.css" /> <script src="../js/jquery-1.7.2.min.js" type="text/javascript"></script> <script src="../js/JScript.js" type="text/javascript"></script> <script src="../js/DatePicker/jquery.ui.core.js" type="text/javascript"></script> <script src="../js/DatePicker/jquery.ui.datepicker.js" type="text/javascript"></script> <script src="../js/Ajax.js"></script> <script src="../js/jquery-1.4.1.js"></script> <style type="text/css"> .auto-style2 { height: 25px; } .auto-style3 { width: 156px; height: 25px; } .auto-style4 { margin-top: 5px; } .auto-style5 { text-align: right; } </style> <script language="javascript" type="text/javascript"> var dgPersonsID = "<%= YPZKXX.ClientID %>"; $(document).ready(function () { $("#dgPersons tr").eq(1).hide(); }); function AddNewRow() { var tr = $("#dgPersons tr").eq(1).clone(); tr.show(); tr.appendTo("#dgPersons"); refreshNo(); return false; } function refreshNo() { var dgg = document.getElementById(dgPersonsID); var index = 1; for (var i = 2; i < dgg.rows.length; ++i) { var cells = dgg.rows[i].cells; var row = dgg.rows[i]; if (row.style.display != "none") { cells[0].firstChild.nodeValue = index++; } } return false; } </script> </head> <body id="dt_example" class="ex_highlight_row"> <form id="form1" runat="server"> <div id="container"> <table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-image: url(../images/Pop_page_back.gif)" align="center"> <tr> <td valign="center" style="height: 27px">&nbsp;<strong>药品折扣基础表</strong></td> </tr> </table> <div id="search"> <table class="t2" style="width:100%"> <tr> <td class="auto-style2">医院名称:</td> <td class="auto-style3"> <input type="text" id="txtyymc" runat="server" class="inputbox" readonly="true"/> </td> <td class="auto-style2">开始时间:</td> <td class="auto-style2"> <input type="text" id="txtkssj" runat="server" class="inputbox" readonly="true" /> </td> <td class="auto-style2">结束时间:</td> <td class="auto-style2"> <input type="text" id="txtjssj" runat="server" class="inputbox" readonly="true"/> </td> <td class="auto-style2">供应商名称:</td> <td class="auto-style2"> <input type="text" id="txtgys" runat="server" class="inputbox" readonly="true"/> </td> </tr> </table> </div> <div id="menu" class="auto-style5"> &nbsp;<asp:Button ID="Btn_Download" runat="server" Text="查 询" CssClass="buttoncss" OnClick="Btn_Download_Click"/> &nbsp; &nbsp;<asp:Button ID="btn_AddLine" runat="server" Text="新增行" CssClass="buttoncss" OnClientClick="return AddNewRow();return false;" /> &nbsp; &nbsp;<asp:Button ID="btn_xz" runat="server" Text="下 载" CssClass="buttoncss"/> &nbsp; &nbsp<asp:Button ID="btn_dr" runat="server" Text="导 入" CssClass="buttoncss" OnClick="btn_dr_Click" /> &nbsp; &nbsp;<asp:CheckBox runat="server" Text="显示历史数据" ID="cbo_xs" Checked="false" /> </div> <div> <asp:GridView ID="YPZKXX" runat="server" AutoGenerateColumns="False" Width="100%" HorizontalAlign="Center" style="text-align: center" NoNewline="word-break: keep-all;" CssClass="auto-style4" OnRowCancelingEdit="YPCGJCXX_RowCancelingEdit" OnRowEditing="YPCGJCXX_RowEditing" OnRowUpdating="YPCGJCXX_RowUpdating"> <EmptyDataTemplate> 没有数据 </EmptyDataTemplate> <FooterStyle ForeColor="White" BackColor="#3B6BD1" Font-Bold="True"></FooterStyle> <SelectedRowStyle Font-Bold="True" ForeColor="Navy" BackColor="#FFCC66" BorderColor="CornflowerBlue" /> <RowStyle ForeColor="#333333" BackColor="#FFFBD6" BorderColor="CornflowerBlue" BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center" VerticalAlign="Bottom" Wrap="False" /> <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#3B6BD1" Wrap="False"></HeaderStyle> <Columns> <asp:TemplateField HeaderText="编号" Visible="false"> <ItemTemplate> <asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="医院名称"> <ItemTemplate> <asp:Label ID="lbl_yymc" runat="server" Text='<%# Bind("yymc") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="供货商编码"> <ItemTemplate> <asp:Label ID="lbl_ghsbm" runat="server" Text='<%# Bind("ghsbm") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="中心编码"> <ItemTemplate> <asp:Label ID="txt_zxbm" runat="server" Text='<%# Bind("zxbm") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="药品编码"> <ItemTemplate> <asp:Label ID="lbl_ypbm" runat="server" Text='<%# Bind("ypbm") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="药品名称"> <ItemTemplate> <asp:Label ID="lbl_ypmc" runat="server" Text='<%# Bind("ypmc") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="药品规格"> <ItemTemplate> <asp:Label ID="lbl_ypgg" runat="server" Text='<%# Bind("ypgg") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="药品单位"> <ItemTemplate> <asp:Label ID="lbl_ypdw" runat="server" Text='<%# Bind("ykdw") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="返利形式"> <ItemTemplate> <asp:Label ID="txt_flxs" runat="server" Text='<%# Bind("flxs") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="厂家名称"> <ItemTemplate> <asp:Label ID="lbl_sccj" runat="server" Text='<%# Bind("cjmc") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="供货单位"> <ItemTemplate> <asp:Label ID="lbl_ghdw" runat="server" Text='<%# Bind("ghdw") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="底 价"> <ItemTemplate> <asp:Label ID="txt_dj" runat="server" Text='<%# Bind("dj") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="折扣率"> <ItemTemplate> <asp:Label ID="txt_zkl" runat="server" Text='<%# Bind("zkl") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="开票价"> <ItemTemplate> <asp:Label ID="txt_kpj" runat="server" Text='<%# Bind("kpj") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="零售价"> <ItemTemplate> <asp:Label ID="lbl_lsj" runat="server" Text='<%# Bind("lsj") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="最新零售价"> <ItemTemplate> <asp:Label ID="lbl_zxlsj" runat="server" Text='<%# Bind("zxlsj") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="售价差价"> <ItemTemplate> <asp:Label ID="txt_sjcj" runat="server" Text='<%# Bind("lscj") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="成本价"> <ItemTemplate> <asp:Label ID="txt_cbj" runat="server" Text='<%# Bind("cbj") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="折 扣"> <ItemTemplate> <asp:Label ID="txt_zk" runat="server" Text='<%# Bind("zk") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="净利润"> <ItemTemplate> <asp:Label ID="txt_jlr" runat="server" Text='<%# Bind("jlr") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="业务费"> <ItemTemplate> <asp:Label ID="txt_ywf" runat="server" Text='<%# Bind("xywf") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="毛利率"> <ItemTemplate> <asp:Label ID="txt_mll" runat="server" Text='<%# Bind("mll") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="年"> <ItemTemplate> <asp:Label ID="lbl_nf" runat="server" Text='<%# Bind("nian") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="月"> <ItemTemplate> <asp:Label ID="lbl_yf" runat="server" Text='<%# Bind("yue") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="管理" ShowHeader="False"> <EditItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="更新"></asp:LinkButton> &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="取消"></asp:LinkButton> </EditItemTemplate> <ItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="编辑"></asp:LinkButton> &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Update" Text="修改"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> <cc2:PageTool ID="PageTool1" runat="server" Number="1" PageRows="10" PageCount="100"> </cc2:PageTool> </div> </form> </body> </html> ``` ``` 后台代码: using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CenterBase.供应链管理 { public partial class YPCGJCB : System.Web.UI.Page { CenterBaseBLL.YPCGMC cbby = new CenterBaseBLL.YPCGMC(); private static int pCount = 0;//总页数 private static int rCount = 0;//总数据数 private static int pageIndex = 1;//当前页 private static int pageSize = 20;//页面大小 private static string tableName = "View_YPJCB";//表名 private static string fields = "ID,yymc, ghsbm, zxbm, ypbm, ypmc, ypgg, ykdw, flxs,cjmc,ghdw,dj,zkl,kpj,lsj,zxlsj,lscj,cbj,zk,jlr,xywf,mll,nian,yue";//查询的字段 private static string order = "ID desc";//排序 private static string primaryKey = "ID";//关键字 private static string where = " "; protected void Page_Load(object sender, EventArgs e) { //UnobtrusiveValidationMode = UnobtrusiveValidationMode.None; //Response.AddHeader("P3P", "CP=CAO PSA OUR"); ////检测用户是否登录 //if (!CheckUserLogin()) //{ // Response.Redirect("../LoginMain.aspx"); //} ////检测用户是否具有权限 //if (!CheckUserAuthority()) //{ // Response.Redirect("../LoginMain.aspx"); //} if (!Page.IsPostBack) { //分页初始化 if (Request.QueryString["page"] == null) { pageIndex = 1; } else { pageIndex = CenterBaseTools.ConvertData.ConvertDataFromStringToInt(Request.QueryString["page"].ToString()); } ////绑定数据 //if (cbo_xs.Checked == true) //{ //} DataBinds(); //Sum(); } } protected void Btn_Download_Click(object sender, EventArgs e) { where = ""; if (sqlwhere() != "") { where = where + sqlwhere(); } DataBinds(); } public void DataBinds() { DataTable dt = new DataTable(); dt = CenterBaseBLL.PageView.GetAll(out pCount, out rCount, pageIndex, pageSize, tableName, fields, order, primaryKey, 2, 0, where); YPZKXX.DataSource = dt; YPZKXX.DataBind(); this.PageTool1.PageRows = pageSize; this.PageTool1.PageCount = rCount; } public string sqlwhere() { string yymc = txtyymc.Value.ToString(); string kssk = txtkssj.Value.ToString(); string jssj = txtjssj.Value.ToString(); string ghs = txtgys.Value.ToString(); int res = kssk.CompareTo(jssj); string sql = ""; if (yymc != "") { sql = sql + " where CYYMC = '" + yymc + "'"; } if (yymc != "" && kssk != "" && jssj != "" && res < 0) { sql = sql + " where CYYMC='" + yymc + "' and DRKRQ between '" + kssk + "' and '" + jssj + "'"; } if (yymc != "" && kssk != "" && jssj != "" && res < 0 && ghs != "") { sql = sql + " where CYYMC='" + yymc + "' and DRKRQ between '" + kssk + "' and '" + jssj + "' and CGHDW = '" + ghs + "'"; } return sql; } protected void YPCGJCXX_RowEditing(object sender, GridViewEditEventArgs e) { YPZKXX.EditIndex = e.NewEditIndex; DataBinds(); } protected void YPCGJCXX_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { YPZKXX.EditIndex = -1; DataBinds(); } protected void YPCGJCXX_RowUpdating(object sender, GridViewUpdateEventArgs e) { int id = Convert.ToInt32((YPZKXX.Rows[e.RowIndex].FindControl("lbl_ID") as Label).Text); string yymc = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_yymc") as Label).Text); string ghsbm = (YPZKXX.Rows[e.RowIndex].FindControl("txt_ghsbm") as TextBox).Text.ToString(); string zxbm = (YPZKXX.Rows[e.RowIndex].FindControl("txt_zxbm") as TextBox).Text.ToString(); string ypbm = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_ypbm") as Label).Text); string ypmc = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_ypmc") as Label).Text); string ypgg = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_ypgg") as Label).Text); string ypdw = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_ypdw") as Label).Text); string flxs = (YPZKXX.Rows[e.RowIndex].FindControl("txt_flxs") as TextBox).Text.ToString(); string cjmc = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_sccj") as Label).Text); string ghdw = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_ghdw") as Label).Text); string dj = (YPZKXX.Rows[e.RowIndex].FindControl("txt_dj") as TextBox).Text.ToString(); string zkl = (YPZKXX.Rows[e.RowIndex].FindControl("txt_zkl") as TextBox).Text.ToString(); string kpj = (YPZKXX.Rows[e.RowIndex].FindControl("txt_kpj") as TextBox).Text.ToString(); string lsj = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_lsj") as Label).Text); string dykpj = (YPZKXX.Rows[e.RowIndex].FindControl("txt_dykpj") as TextBox).Text.ToString(); string zxlsj = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_zxlsj") as Label).Text); string sjcj = (YPZKXX.Rows[e.RowIndex].FindControl("txt_sjcj") as TextBox).Text.ToString(); string cbj = (YPZKXX.Rows[e.RowIndex].FindControl("txt_cbj") as TextBox).Text.ToString(); string zk = (YPZKXX.Rows[e.RowIndex].FindControl("txt_zk") as TextBox).Text.ToString(); string jlr = (YPZKXX.Rows[e.RowIndex].FindControl("txt_jlr") as TextBox).Text.ToString(); string ywf = (YPZKXX.Rows[e.RowIndex].FindControl("txt_ywf") as TextBox).Text.ToString(); string mll = (YPZKXX.Rows[e.RowIndex].FindControl("txt_mll") as TextBox).Text.ToString(); string nf = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_nf") as Label).Text); string yf = Convert.ToString((YPZKXX.Rows[e.RowIndex].FindControl("lbl_yf") as Label).Text); DateTime time = System.DateTime.Now; string sql = "insert into YPFXJCXX(yymc,ghsbm,zxbm,ypbm,ypmc,ypgg,ykdw,flxs,cjmc,ghdw,dj,zkl,kpj,lsj,dykpj,zxlsj,lscj,cbj,zk,jlr,xywf,mll,nian,yue,ITime)" + "values(" + "'" + yymc + "'," + "'" + ghsbm + "'," + "'" + zxbm + "'," + "'" + ypbm + "'," + "'" + ypmc + "'," + "'" + ypgg + "'," + "'" + ypdw + "'," + "'" + flxs + "'," + "'" + cjmc + "'," + "'" + ghdw + "'," + "'" + dj + "'," + "'" + zkl + "'," + "'" + kpj + "'," + "'" + lsj + "'," + "'" + dykpj + "'," + "'" + zxlsj + "'," + "'" + sjcj + "'," + "'" + cbj + "'," + "'" + zk + "'," + "'" + jlr + "'," + "'" + ywf + "'," + "'" + mll + "'," + "'" + nf + "'," + "'" + yf + "'," + "'" + time + "'" + ")"; CenterBaseDAL.ExecuteSql exec = new CenterBaseDAL.ExecuteSql(); int falg = exec.run(sql); if (falg == 1) { Response.Write("<script>alert('更新成功')</script>"); Response.Write("<script>window.location.href='YPCGJCB.aspx'</script>"); Response.End(); } else { Response.Write("<script>alert('更新失败')</script>"); } } protected void btn_dr_Click(object sender, EventArgs e) { Response.Write("<script>window.open('药品销售明细查询/Improt.aspx','_blank')</script>"); } } } ``` 我用自己方法添加了一列行号,求大神指点!!
ASP.NET中加入JS 改变表格中数据
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="webgf.GF" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function HideShow() { hidetable.style.display = ""; } function calculateShanghai() { document.writeln("<h2>你好!</h2>"): } </script> </head> <body> <form id="form2" runat="server"> <div> <table border="0" id="table1" width="60%" align="center"> <tr> <td width="25%">城市名:</td> <td width="25%"> <asp:DropDownList ID="TBCityName0" runat="server" Width="74px" AutoPostBack="True" Height="19px" onselectedindexchanged="TBCityName0_SelectedIndexChanged"> <asp:ListItem>请选择</asp:ListItem> <asp:ListItem>北京市</asp:ListItem> <asp:ListItem>天津市</asp:ListItem> <asp:ListItem>河北省</asp:ListItem> <asp:ListItem>山西省</asp:ListItem> <asp:ListItem>内蒙古自治区</asp:ListItem> <asp:ListItem>辽宁省</asp:ListItem> <asp:ListItem>吉林省</asp:ListItem> <asp:ListItem>黑龙江省</asp:ListItem> <asp:ListItem>上海市</asp:ListItem> <asp:ListItem>江苏省</asp:ListItem> <asp:ListItem>浙江省</asp:ListItem> <asp:ListItem>安徽省</asp:ListItem> <asp:ListItem>福建省</asp:ListItem> <asp:ListItem>江西省</asp:ListItem> <asp:ListItem>山东省</asp:ListItem> <asp:ListItem>河南省</asp:ListItem> <asp:ListItem>湖北省</asp:ListItem> <asp:ListItem>湖南省</asp:ListItem> <asp:ListItem>广东省</asp:ListItem> <asp:ListItem>广西壮族自治区</asp:ListItem> <asp:ListItem>海南省</asp:ListItem> <asp:ListItem>重庆市</asp:ListItem> <asp:ListItem>四川省</asp:ListItem> <asp:ListItem>贵州省</asp:ListItem> <asp:ListItem>云南省</asp:ListItem> <asp:ListItem>西藏自治区</asp:ListItem> <asp:ListItem>陕西省</asp:ListItem> <asp:ListItem>甘肃省</asp:ListItem> <asp:ListItem>青海省</asp:ListItem> <asp:ListItem>宁夏回族自治区</asp:ListItem> <asp:ListItem>新疆维吾尔族自治区</asp:ListItem> <asp:ListItem>港澳台</asp:ListItem> </asp:DropDownList> <asp:DropDownList ID="TBCityName1" runat="server" Width="74px" AutoPostBack="True" Height="19px" onselectedindexchanged="TBCityName1_SelectedIndexChanged"> </asp:DropDownList> <br /> <asp:DropDownList ID="TBCityName" runat="server" Width="156px" Height="19px"> </asp:DropDownList> </td> <td width="25%">装机容量:(兆瓦)</td> <td width="25%"> <asp:TextBox ID="TBCapacity" runat="server" value="90"></asp:TextBox> </td> </tr> <tr> <td width="25%">每兆瓦投资:(万元)</td> <td width="25%"> <asp:TextBox ID="TBInvestmentPMW" runat="server" value="880"></asp:TextBox> </td> <td width="25%">使用年限:(年)</td> <td width="25%"> <asp:TextBox ID="TBUsedPeriod" runat="server" value="25"></asp:TextBox> </td> </tr> <tr> <td width="25%">含税上网电价:(元/度)</td> <td width="25%"> <asp:TextBox ID="TBElectricityPriceT" runat="server" value="1"></asp:TextBox> </td> <td width="25%">售电增值税税率:(%)</td> <td width="25%"> <asp:TextBox ID="TBElectricitySellingVATRate" runat="server" value="17"></asp:TextBox> </td> </tr> <tr> <td width="25%">银行货款比例:(%)</td> <td width="25%"> <asp:TextBox ID="TBRatioLoans" runat="server" value="70"></asp:TextBox> </td> <td width="25%">年货款利率:(%)</td> <td width="25%"> <asp:TextBox ID="TBInterestRate" runat="server" value="6.55"></asp:TextBox> </td> </tr> </table> <table id="hidetable" border="0" width="60%" align="center" runat="Server" style="display:none"> <tr> <td width="25%">其它费用(万元)</td> <td width="25%"> <asp:TextBox ID="TBQiTaFeiYong" runat="server" value="0"></asp:TextBox> </td> <td width="25%">设备净残率:(%)</td> <td width="25%"> <asp:TextBox ID="TBRSheBeiJingCang" runat="server" value="5"></asp:TextBox> </td> </tr> <tr> <td width="25%">日常投资费用:(%)</td> <td width="25%"> <asp:TextBox ID="TBRRiChangTouZi" runat="server" value="10"></asp:TextBox> </td> <td width="25%">大修费用:(%)</td> <td width="25%"> <asp:TextBox ID="TBRDaXiu" runat="server" value="10"></asp:TextBox> </td> </tr> <tr> <td width="25%">路线更换费用:(%)</td> <td width="25%"> <asp:TextBox ID="TBRLuXianGengHuan" runat="server" value="6"></asp:TextBox> </td> <td width="25%">经营期薪酬费用比例:(%)</td> <td width="25%"> <asp:TextBox ID="TBJingYingQiPay" runat="server" value="0.19"></asp:TextBox> </td> </tr> <tr> <td width="25%">保险费用:(%)</td> <td width="25%"> <asp:TextBox ID="TBRBaoXian" runat="server" value="0.15"></asp:TextBox> </td> <td width="25%">所得税率:(%)</td> <td width="25%"> <asp:TextBox ID="TBSuoDeShuiLv" runat="server" value="25"></asp:TextBox> </td> </tr> <tr> <td width="25%">预留金额参数:(%)</td> <td width="25%"> <asp:TextBox ID="TBRYuLiuJinE" runat="server" value="10.0"></asp:TextBox> </td> <td width="25%">城市税率:(%)</td> <td width="25%"> <asp:TextBox ID="TBChengShiShuiLv" runat="server" value="7"></asp:TextBox> </td> </tr> <tr> <td width="25%">教育税率:(%)</td> <td width="25%"> <asp:TextBox ID="TBJiaoYuShuiLv" runat="server" value="3"></asp:TextBox> </td> <td width="25%">折现率:(%)</td> <td width="25%"> <asp:TextBox ID="TBXianZhiXiShu" runat="server" value="8"></asp:TextBox> </td> </tr> <tr> <td width="25%">固定资产系数:</td> <td width="25%"> <asp:TextBox ID="TBdGuDingZiChangXiShu" runat="server" value="0.98"></asp:TextBox> </td> <td width="25%">发电效率:(%)</td> <td width="25%"> <asp:TextBox ID="TBR" runat="server" value="82"></asp:TextBox> </td> </tr> <tr> <td width="25%">年衰减率:(%)</td> <td width="25%"> <asp:TextBox ID="TBRNianShuaiJianRate" runat="server" value="0.8"></asp:TextBox> </td> <td width="25%">上网率:(%)</td> <td width="25%"> <asp:TextBox ID="TBRShangWang" runat="server" value="100"></asp:TextBox> </td> </tr> </table> </div> <div> <table border="0" cellspacing="0" cellpadding="0" align="center" style="height: 252px; width: 60%"> <tr> <td style="text-align:right"> <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">显示更多参数</asp:LinkButton> </td> </tr> <tr> <td style="text-align:center"> <asp:Button ID="BCalculate" runat="server" Text="计算" onclick="BCalculate_Click" /> <asp:Button ID="BClear" runat="server" Text="清空" onclick="BClear_Click" /> </td> </tr> <tr> <td style="text-align:center"> <asp:Label ID="Label3" runat="server" BackColor="Blue" Font-Names="微软雅黑" Font-Size="Large" ForeColor="White"></asp:Label> <br /> <asp:Label ID="Label4" runat="server" BackColor="Blue" BorderColor="Blue" Font-Names="微软雅黑" Font-Size="Large" ForeColor="White"></asp:Label> <br /> <asp:Label ID="Label2" runat="server" Visible="False"></asp:Label> <br /> <asp:Label ID="Label1" runat="server" Visible="False"></asp:Label> <br /> <asp:Label ID="Label5" runat="server" Visible="False"></asp:Label> <asp:GridView ID="GridView1" runat="server" EnableModelValidation="True" style="text-align: center" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" Visible="False"> <FooterStyle BackColor="#99CCCC" ForeColor="#003399" /> <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" /> <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" /> <RowStyle BackColor="White" ForeColor="#003399" /> <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" /> </asp:GridView> </td> </tr> </table> </div> </form> </body> </html> 上面是源代码 要实现的功能是:修改原始初值,对于百分比的,正负10%浮动(加减),每次浮动1%,对于数值的,从数值的90%到110%浮动,每次变动1%,能将得到的数据在页面全部显示出来,每次只要变动一个数据就好了,将所有的都跑一遍。毕设,来不及学js,忘谅解伸手党!
如何根据Ajax根据条件检索并实现局部刷新
随便举了个例子。 ``` @model IEnumerable<Ajax.Models.nmb> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.name) </th> <th> @Html.DisplayNameFor(model => model.age) </th> <th> @Html.DisplayNameFor(model => model.lesson) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.name) </td> <td> @Html.DisplayFor(modelItem => item.age) </td> <td> @Html.DisplayFor(modelItem => item.lesson) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.id }) | @Html.ActionLink("Details", "Details", new { id=item.id }) | @Html.ActionLink("Delete", "Delete", new { id=item.id }) </td> </tr> } </table> ``` ``` // GET: nmbs/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } nmb nmb = db.nmb.Find(id); if (nmb == null) { return HttpNotFound(); } return View(nmb); } ``` 这些代码都是MVC自动生成的,没什么好讲,我只是提供了一个模型。 当你点击Details的时候,他的原理是直接传递一个model的参数,然后跳转至一个新的页面。 现在我想实现的是,点击Details后,页面不进行跳转,而是进行局部刷新,将详情在该页面下方展示出来。 请最好能给出详情的代码和过程,我原来打算用Ajax.beginform来实现,但不知道哪个环节出了差错,老是出现各种奇怪的意外,希望能够得到坛友的帮助。
用selenium模拟登陆网站,点击图片链接后弹出的登陆页面如何输入用户名和密码后进行信息系统中
from selenium import webdriver chromedriver = r"C:\Program Files (x86)\chrome32_50.0.2661.75\chromedriver.exe" driver= webdriver.Chrome(chromedriver) driver.get("http://www.****")#系统网址 driver.find_element_by_xpath("/html/body/div[1]/div[2]/ul/li[4]/a/img").click() newWindow = chromedriver.switchTo().window(handle) driver.find_element_by_class_name("userName").send_keys(u"账户名") driver.find_element_by_class_name("userPwd").send_keys(u"密码") driver.find_element_by_xpath("//*[@id="layui-layer1"]/div[3]/a[1]").click() 新手自学中,1-5行代码可以进入系统登陆页,后面的代码不能输入账户名和密码进入系统中,请高手指点迷津。
关于爬虫百度百科问题,求教各位。代码如下,运行提示错误。
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import urllib2 from bs4 import BeautifulSoup import re import urlparse class UrlManager(object): def __init__(self): self.new_urls = set() self.old_urls = set() def add_new_url(self,url): if url is None: return if url not in self.new_urls and url not in self.old_urls: self.new_urls.add(url) def add_new_urls(self,urls): if urls is None or len(urls) == 0: return for url in urls: self.add_new_url(url) def has_new_url(self): return len(self.new_urls) != 0 def get_new_url(self): new_url = self.new_urls.pop() self.old_urls.add(new_url) return new_url class HtmlDownloader(object): def download(self,url): if url is None: return None response = urllib2.urlopen(url) if response.getcode() != 200: return None return response.read() class HtmlParser(object): def _get_new_urls(self,page_url,soup): new_urls = set() links = soup.find_all('a',href = re.compile(r'/item/(.*)')) for link in links: new_url = link['href'] new_full_url = urlparse.urljoin(page_url,new_url) new_urls.add(new_full_url) return new_urls def _get_new_data(self,page_url,soup): res_data = {} #url res_data['url'] = page_url # <dd class="lemmaWgt-lemmaTitle-title"><h1>Python</h1> title_node = soup.find('dd',class_ ="lemmaWgt-lemmaTitle-title").find("h1") res_data['title'] = title_node.get_text() #<div class="lemma-summary" label-module="lemmaSummary"> summary_node = soup.find('div',class_ = "lemma-summary") res_data['summary'] = summary_node.get_text() return res_data def parse(self,page_url,html_cont): if page_url is None or html_cont is None: return soup = BeautifulSoup(html_cont,'html_parser',from_encoding='utf-8') new_urls = self._get_new_urls(page_url,soup) new_data = self._get_new_data(page_url,soup) return new_urls,new_data class HtmlOutputer(object): def __init__(self): self.datas = [] def collect_data(self,data): if data is None: return self.datas.append(data) def output_html(self): fout = open('output.html','w') fout.write("<html>") fout.write("<body>") fout.write("<table>") for data in self.datas: fout.write("<tr>") fout.write("<td>%s</td>"% data['url']) fout.write("<td>%s</td>"% data['title'].encode('utf-8')) fout.write("<td>%s</td>"% data['summary'].encode('utf-8')) fout.write("</tr>") fout.write("</table>") fout.write("</body>") fout.write("</html>") fout.close() # 爬虫总调度程序 class SpiderMain(object): # 构造函数初始化url管理器、HTML下载器、HTML解析器、输出四个对象 def __init__(self): # url管理器 self.urls = UrlManager() # url下载器 self.downloader = HtmlDownloader() # url解析器 self.parser = HtmlParser() # 最终的输出 self.outputer = HtmlOutputer() # 爬虫调度程序 def craw(self, root_url): count = 1 # 添加入口URL self.urls.add_new_url(root_url) while self.urls.has_new_url(): try: # 取出新的URL new_url = self.urls.get_new_url() # 下载该url对应的页面 print("craw %d : %s" % (count, new_url)) html_cont = self.downloader.download(new_url) # 解析该url对应的页面,得到新的链接和内容 new_urls, new_data = self.parser.parse(new_url, html_cont) # 将新url添加到url管理器中 self.urls.add_new_urls(new_urls) # 将解析到的内容收集起来 self.outputer.collect_data(new_data) if count == 1000: # 爬取1000个页面即可 break count = count + 1 except: print("craw fail") # 最终输出爬取目标的内容 self.outputer.output_html() # 主函数启动爬虫 if __name__=="__main__": # root_url = "http://baike.baidu.com/item/Python/407313?fr=aladdin" root_url = "http://baike.baidu.com/item/Python/407313?fr=aladdin" obj_Spider = SpiderMain() obj_Spider.craw(root_url) 提示runfile('C:/Users/sun/.spyder/temp.py', wdir='C:/Users/sun/.spyder') craw 1 : http://baike.baidu.com/item/Python/407313?fr=aladdin craw fail
修改css样式表没有任何效果,将CSS样式表中的内容复制到新的表中导入后,样式同样不在页面显示
在同一个表中,属性相同但是class名不同,调用自己新建的class名不显示效果,但是用原来的就可以 请问是什么原因,后来新建了css表,将原css所有内容原封不动复制进去,再导入,但是效果却不显示, bootstrap的样式可以正常显示,js同样可以正常显示 ![这个是原来的样式](https://img-ask.csdn.net/upload/201701/18/1484705350_8330.jpg) ![我想把中间那块放到中间的,但是没有效果](https://img-ask.csdn.net/upload/201701/18/1484705359_500615.jpg) CSS代码 ``` @charset "utf-8"; *{margin:0px; padding:0px;} body{font-family:"微软雅黑", Arial, Helvetica, sans-serif; font-size:12px; line-height:1.5em; color:#555555;background:#f3f3f3;} ul{list-style-type:none;} input,select,textarea{vertical-align:middle; font-family:inherit; font-size:inherit; color:inherit; outline:none;} h1,h2,h3,h4,h5,h6{font-weight:normal;} a{color:#555555; text-decoration:none; outline:none;} a:hover,a.glink:hover,a.blink:hover{ text-decoration:none;outline:none;} .clear{ clear:both; font-size:0; height:0; line-height:0;overflow:hidden} a img{ border:0;} .leftF{ float:left;} .centerF{float:left;} .rightF{ float:right;} .main{ width:1116px; margin:0 auto; padding-bottom:330px;} .main .mainleft{ width:210px;top:90px; position:relative;} .main .mainright{ float:left;padding:0px;width:905px;} .foot{ background:#999999; color:#ffffff; padding:20px 0; text-align:center; font-size:14px; line-height:24px;} .footinner{ border-top:1px solid #dddddd; color:#ffffff; padding:45px 0 80px 0; text-align:center; font-size:14px; line-height:24px;} .footinner .footintop{ color:#333333;} .footinner .footinbto{ color:#555555;} .bigperson{ margin-bottom:-57px; top:-77px; position:absolute;} .bigperson .touxiang{ width:210px; text-align:center;} .bigperson .touxiang img{ width:100px; height:100px; border:2px solid #fff; border-radius:50%;} .bigperson .personname{ text-align:center; font-size:18px; color:#555555; line-height:32px;} header #header-top {top: 0; right: 0; left: 0; padding: 0 1em; height: 3em; line-height: 3em; color: #fff; background-color: #2c3e50; z-index: 2;} header #header-top #logout { float: right; } header #header-top #logout a { color: inherit; } .current a{display:block; background:#61b988;line-height:38px; height:38px; margin:0px 0 15px 0; color:#fff; font-size:14px;} .current a{color:#FFF;} .funclistul {position:relative;} .funclistul li{ line-height:38px; height:38px;font-size:14px;} .funclistul li a{ text-align:center;display:block; padding:0; line-height:38px; height:38px; font-size:14px; overflow:hidden;} .funclistul li a:hover{ background:#61b988; color:#fff;} .funclistul li b{ width:21px; height:20px; margin:10px 5px 0 0px;} .line {text-align:center;height:0px!important;border-top:solid 1px #CCC;} #divide_line {position:absolute;height:1316px;border-color:#CCC;border-left-style:solid;border-width:1px} #frame_content {border:0px; height:981px; min-height:700px;} .fl{float:left;} .fr{float:right;} .Wrapbody{width:890px;height:900px;overflow:hidden;padding-top:20px;position:relative;margin-left: 50px;} .zla_m_tab { width:850px;height:40px; padding-top:12px; border-bottom:2px #ccc solid;font-size:20px;color:#777;} .zla_m_item { float:left; width:106px; height:40px; } .zla_m_item a ,.zla_m_cur a { display:inline-block; width:150px; height:40px; line-height:40px; text-align:center;font-size:20px;color:#777;} .zla_m_item a:hover , .zla_m_cur a { display:inline-block; background:url(../img/tri.png) center 35px no-repeat; text-decoration:none; border-bottom:2px solid #61b988;font-size:20px;color:#333;} .Div { margin-top:30px; } .ulDiv { margin-top:30px; } .ulDiv ul li { margin-left: 3px; position:relative; width: 270px; margin-bottom: 32px; background-color: #fff; float:left; zoom: 1; letter-spacing: 0; overflow: hidden; height: 150px; margin-right: 16px; border-radius: 3px; } .ulDiv ul li:hover { border-color: rgba(101, 204, 153, 0.8); outline: 0; outline: thin dotted \9; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(101, 204, 153, 0.6); } .Mcon1img .Gd { display: block; width: 23px; height: 23px; position: absolute; top: 0px; right: 0px; display: none; } .Mconright{padding:20px;} .Mconright h3{font-size:18px;padding:7px 0 10px 0;} .Mconright h3 a{float:left} .Mconright p{color:#666;font-size:12px;} .Mcon1img{position:relative;} .Mcon1img:hover .Gd{display:block;} .Mconright h3 i{display:none;width:8px;height:8px;background:red;border-radius:8px;margin-left: 5px;float:left;} .red { color: #b9423c; } .green { color: #61b988; } .force_red { color: #b9423c!important; } .force_green { color: #61b988!important; } .block { padding: 30px 0; } .aline { margin-right: 50px; padding: 10px 0; float: right; } .four_in_one { height: 50px; line-height: 50px; width: 172px; padding: 10px 50px 10px 0px; float: right; text-align: center; vertical-align: middle; } .specail_line_one { margin-right: 150px; } .specail_line_two { margin-right: 68px; } .specail_line_three { margin-right: 357px; } .specail_line_four { margin-right: 111px; } .normal_one { font-size: 2em; vertical-align: middle; } .normal_two { font-size: 1.5em; vertical-align: middle; } .normal_three { width: 50px; display: inline-block; font-size: 2em; vertical-align: top; } .normal_one, .normal_two, .normal_three { margin: 5px; height: 30px; line-height: 30px; overflow: hidden; } .one_block { width: 150px; height: 30px; text-align: center; } .one_line { width: 750px; height: 30px; } .many_lines { width: 750px; height: 150px; resize: none; overflow: scroll; } .exam_many_lines { width: 720px; height: 150px; resize: none; overflow: scroll; } .one_block, .one_line, .many_lines, .exam_many_lines { box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); transition: border linear 0.2s, box-shadow linear 0.2s; font-size: 2em; display: inline-block; padding: 4px; color: #555555; vertical-align: middle; background-color: #ffffff; border: 1px solid #e3e3e3; border-radius: 3px; margin: 3px 0; } .one_block:focus, .one_line:focus, .many_lines:focus, .exam_many_lines:focus { border-color: rgba(101, 204, 153, 0.8); outline: 0; outline: thin dotted \9; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(101, 204, 153, 0.6); } .submit_button { width: 200px; height: 41px; transition: border linear 0.2s, box-shadow linear 0.2s; font-size: 1.5em; display: inline-block; padding: 4px; color: #555555; vertical-align: middle; background-color: #ffffff; border: 1px solid #e3e3e3; border-radius: 3px; margin: 3px 0; cursor: hand; } .submit_button:hover { border-color: rgba(101, 204, 153, 0.8); outline: 0; outline: thin dotted \9; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(101, 204, 153, 0.6); } .submit_button:focus { border-color: rgba(101, 204, 153, 0.8); outline: 0; outline: thin dotted \9; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(101, 204, 153, 0.6); } .submit_button:disabled { color: #555555; background-color: #e8e8e8; } .submit_button:disabled:hover { border-color: rgba(232, 232, 232, 0.8); outline: 0; outline: thin dotted \9; box-shadow: inset 0 0 0 rgba(0, 0, 0, 0.075), 0 0 0 rgba(232, 232, 232, 0.6); } .submit_button:disabled:focus { border-color: rgba(232, 232, 232, 0.8); outline: 0; outline: thin dotted \9; box-shadow: inset 0 0 0 rgba(0, 0, 0, 0.075), 0 0 0 rgba(232, 232, 232, 0.6); } .check { margin-right: 10px; } .score { padding: 30px 50px; height: 400px; overflow: scroll; } .score_title { font-size: 1.5em; } .button_block { padding: 10px 0; text-align: center; } .marklist { z-index: 50; width:250px; top:105px; right:160px; position:fixed; background: #fff; padding: 10px; border-radius: 3px; } .mark_title, .submit_paper, .marklist ul li { position:relative; margin-bottom: 32px; background: #fff; float:left; zoom: 1; letter-spacing: 0; overflow: hidden; border-radius: 3px; text-align: center; border: 1px solid #61b988; } .mark_title:hover, .submit_paper:hover, .marklist ul li:hover { border-color: rgba(101, 204, 153, 0.8); outline: 0; outline: thin dotted \9; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(101, 204, 153, 0.6); } .mark_title { width: 80px; height: 30px; margin: 10px 120px 10px 8px; } .submit_paper { width: 80px; height: 30px; margin: 20px 8px 10px 150px; } .marklist ul li { width: 30px; height: 30px; margin: 5px 8px; } .mark { line-height: 30px; font-size: 1.5em; color: #61b988; background: #fff; text-align: center; vertical-align: middle; } .active { background: #61b988!important; color: #fff; } .active a { background: #61b988!important; color: #fff; } header #exam_top {z-index:999!important;position: fixed; opacity:0.9; top: 0; right: 0; left: 0; padding: 0 1em; height: 4em; line-height: 4em; color: #3f3f3f; background-color: #fff; z-index: 2;font-size: 1.5em;} .exam_foot {z-index:999!important;margin-top:36px; background:#fefefe; color:#3f3f3f; padding:20px 0; text-align:center; font-size:14px; line-height:24px;} .center { text-align:center; } .exam_head { padding: 0 10px; } .alert_screen {position: fixed; top: 0; right: 0; bottom: 0; left: 0; background-color: #fff; z-index: 1000;} .alert_block {margin-top: 300px; text-align: center;} .alert_msg {font-size: 2em;} .quit_btn, .alert_btn {margin-top: 50px;text-align: center;} .examright {position:relative; top:105px; padding:25px; width:770px; background: #fff; border-radius: 3px;margin-bottom: 100px;} .title{ font-size: 2em; padding: 10px 0; } .content_box { padding: 20px; } .choice_box { padding-left: 20px; } .content { height: 30px; line-height: 30px; font-size: 1.5em; padding: 10px 0; } .title:target, .content_box:target{ padding-top:72px; } @media screen and (max-width: 1400px){ .marklist { right:100px; } } @media screen and (max-width: 1300px){ .marklist { right:50px; } } @media screen and (max-width: 1200px){ .marklist { right:0px; } } ``` ``` <header> <div id="exam_top"> <div class="leftF"> <span class="exam_head">专业简答题</span> </div> <div class="rightF"> <span class="exam_head">账号:<%=(String) session.getAttribute("login")%></span> </div> <div class="center"> <span class="exam_head">考试限时:30分钟</span> <span class="exam_head">剩余时间:<span class="green" id="time"></span>分钟 </span> </div> </div> </header> <div class="main"> <div class="examright centerF"><!-- class leftF被修改 --> <div class="block" > <form action="SaveAnswer" method="post" id="form1"> <c:forEach items="${sq}" var="QsInfo" varStatus="vs"> <input type="hidden" name="index${vs.count}" value="${QsInfo.essayId}"/><!-- 隐藏题目ID传递给后台 --> <!--循环输出分割线———————————————————————————————————— --> <!-- EL表达式可以自动转型 --> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">专业简答题${vs.count} :</h3> </div> <div class="panel-body">${QsInfo.eTitle}</div> <div class="form-group"> <textarea class="form-control" rows="3" name="ans${vs.count}"></textarea> </div> </div> </c:forEach> </form> <div> <button type="button" class="btn btn-success btn-block" onclick="sub()">提交试卷</button> </div> <!--———————————————————————————————————————————————————————— --> </div> </div> </div> ```
[freemarker]使用freemarker生成父子关系树抛异常
需要生成一个菜单树,使用了freemarker,由于采用了tiles2,在和freemarker整合的时候出现了问题,所以直接使用freemarker 2.3.15将模板通过template.process方法产生html code显示到前端,主要代码如下: [code="java"] //产生freemarker config package project.util.freemarker; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.TemplateExceptionHandler; public class FreeMarkerService { private static Configuration cfg = new Configuration(); static { //设置模版加载的路径,相对于FreemarkerService类路径下的templates路径 cfg.setTemplateLoader(new ClassTemplateLoader(FreeMarkerService.class, "ftl")); //设置对象包装器 cfg.setObjectWrapper(new DefaultObjectWrapper()); //设置默认编码 cfg.setDefaultEncoding("UTF-8"); //设置异常处理器 cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); } public static Configuration getConfiguration() { return cfg; } } [/code] [code="java"] //freemarker工具类,将数据和模板合成html package project.util.freemarker import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class FreeMarkerUtil { @SuppressWarnings("rawtypes") public static String dataToString(Map data,String templatePath) throws IOException,TemplateException{ if(data == null){ return null; } Writer out = null; Configuration cfg = FreeMarkerService.getConfiguration(); Template template = cfg.getTemplate(templatePath); out = new StringWriter(); template.process(data,out); return out.toString(); } } [/code] freemarker 模板 [code="html"] <#-- 定义宏buildNode --> <#macro buildNode child parent> <li id="${parent.menuId}" parentId="${parent.parent.menuId}"> <a href="${webRoot}/rbac/initMenuMgmtAction.do?menuId=${parent.menuId}"> <span <#if 'Y' == parent.isDel> style="text-decoration:line-through" </#if> > ${parent.menuName} </span> </a> <#if child?? && child?size gt 0> <ul> <#list child as t> <#-- 递归调用宏buildNode --> <@buildNode child=t.children parent=t/> </#list> </ul> </#if> </li> </#macro> <ul> <@buildNode child=rootMenu.children parent=rootMenu/> </ul> [/code] [code="java"] //实体类 package project.bean; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity @Table(name="RBAC_MENUS") public class Menu { private int menuId; private String menuName; private String description; private Menu parent; private List<Menu> children; private List<Function> functions; private String isDel; public Menu(){} @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "sequence", parameters= {@Parameter(name="sequence",value="RBAC_MENU_SEQ")}) @Column(name="MENU_ID") public int getMenuId() { return menuId; } public void setMenuId(int menuId) { this.menuId = menuId; } @Column(name="MENU_NAME") public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } @ManyToOne(cascade = {CascadeType.MERGE,CascadeType.REFRESH }, optional = true) @JoinColumn(name="PARENT_MENU_ID") public Menu getParent() { return parent; } public void setParent(Menu parent) { this.parent = parent; } @OneToMany(cascade = { CascadeType.REFRESH, CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE },mappedBy ="parent") public List<Menu> getChildren() { return children; } public void setChildren(List<Menu> children) { this.children = children; } public void addChildren(Menu menu){ if(this.children == null){ this.children = new ArrayList<Menu>(); } this.children.add(menu); } @OneToMany(cascade = { CascadeType.REFRESH, CascadeType.PERSIST,CascadeType.MERGE, CascadeType.REMOVE },mappedBy ="menu") public List<Function> getFunctions() { return functions; } public void setFunctions(List<Function> functions) { this.functions = functions; } @Column(name="IS_DEL") public String getIsDel() { return isDel; } public void setIsDel(String isDel) { this.isDel = isDel; } @Column(name="description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } [/code] [code="java"] //Struts action package project.web; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import project.bean.Menu; import project.service.MenuService; import project.util.freemarker.FreeMarkerUtil; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.ServletActionContext; public class MenuAction extends ActionSupport { ... @Resource private MenuService menuService; private String menuTree; public String getMenuTree(){ return menuTree; } ... @SuppressWarnings({ "rawtypes", "unchecked" }) public String initMenu(){ Menu rootMenu = menuService.getRootMenu(); try{ Map freemarkerData = new HashMap(); freemarkerData.put("rootMenu", rootMenu); freemarkerData.put("webRoot", ServletActionContext.getServletContext().getContextPath()); menuTree = FreeMarkerUtil.dataToString(freemarkerData, "menumgmt.ftl"); } catch(Exception e){ e.printStackTrace(); } return ActionSupport.SUCCESS; } ... [/code] [code="java"] //Menu Service实现类 public class MenuServiceImpl implements MenuService { @Resource private SessionFactory sessionFactory; ... //得到根菜单 @SuppressWarnings("unchecked") @Override public Menu getRootMenu() { List<Menu> menus = sessionFactory.getCurrentSession().createQuery("from Menu m where m.parent is null").list(); if(menus != null && menus.size()>0) return menus.get(0); return null; } //插入菜单 @Override public void insertMenu(Menu menu) { sessionFactory.getCurrentSession().persist(menu); } ... } [/code] jsp代码 [code="html"] ... <td rowspan="3" style="width:600px;vertical-align:top"> <!--添加层开始--> <div id="divTreeContainer" style="display:block;"> <div>菜单列表</div> <div id="treeContainer" style="margin-left:10px;display:block;"> ${menuTree} </div> </div> </td> ... <script type="text/javascript"> $(document).ready(function(){ $("#treeContainer ul").Treeview(); $("#treeContainer").show(500); }); </script> [/code] 异常信息 ... Hibernate: select menu0_.MENU_ID as MENU1_2_, menu0_.description as descript2_2_, menu0_.IS_DEL as IS3_2_, menu0_.MENU_NAME as MENU4_2_, menu0_.PARENT_MENU_ID as PARENT5_2_ from RBAC_MENUS menu0_ where menu0_.PARENT_MENU_ID is null Hibernate: select children0_.PARENT_MENU_ID as PARENT5_1_, children0_.MENU_ID as MENU1_1_, children0_.MENU_ID as MENU1_2_0_, children0_.description as descript2_2_0_, children0_.IS_DEL as IS3_2_0_, children0_.MENU_NAME as MENU4_2_0_, children0_.PARENT_MENU_ID as PARENT5_2_0_ from RBAC_MENUS children0_ where children0_.PARENT_MENU_ID=? [ERROR] [freemarker.log.Log4JLoggerFactory$Log4JLogger.error(Log4JLoggerFactory.java:96)] er.runtime - Expression parent.parent is undefined on line 3, column 43 in menumgmt.ftl. The problematic instruction: ---------- ==> ${parent.parent.menuId} [on line 3, column 41 in menumgmt.ftl] in user-directive buildNode [on line 27, column 21 in menumgmt.ftl] ---------- Java backtrace for programmers: ---------- freemarker.core.InvalidReferenceException: Expression parent.parent is undefined on line 3, column 43 in menumgmt.ftl. at freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:124) at freemarker.core.TemplateObject.invalidTypeException(TemplateObject.java:134) at freemarker.core.Dot._getAsTemplateModel(Dot.java:78) at freemarker.core.Expression.getAsTemplateModel(Expression.java:89) at freemarker.core.Expression.getStringValue(Expression.java:93) at freemarker.core.DollarVariable.accept(DollarVariable.java:76) at freemarker.core.Environment.visit(Environment.java:209) at freemarker.core.MixedContent.accept(MixedContent.java:92) at freemarker.core.Environment.visit(Environment.java:209) at freemarker.core.Macro$Context.runMacro(Macro.java:168) at freemarker.core.Environment.visit(Environment.java:602) at freemarker.core.UnifiedCall.accept(UnifiedCall.java:106) at freemarker.core.Environment.visit(Environment.java:209) at freemarker.core.MixedContent.accept(MixedContent.java:92) at freemarker.core.Environment.visit(Environment.java:209) at freemarker.core.Environment.process(Environment.java:189) at freemarker.template.Template.process(Template.java:237) at project.rbac.util.freemarker.FreeMarkerUtil.dataToString(FreeMarkerUtil.java:24) at project.rbac.web.MenuAction.initMenu(MenuAction.java:91) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:123) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:184) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:105) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:83) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:207) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:74) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:127) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:107) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:206) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:115) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:143) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:121) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:170) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:123) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224) at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:50) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:504) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:422) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:662) Hibernate: select children0_.PARENT_MENU_ID as PARENT5_1_, children0_.MENU_ID as MENU1_1_, children0_.MENU_ID as MENU1_2_0_, children0_.description as descript2_2_0_, children0_.IS_DEL as IS3_2_0_, children0_.MENU_NAME as MENU4_2_0_, children0_.PARENT_MENU_ID as PARENT5_2_0_ from RBAC_MENUS children0_ where children0_.PARENT_MENU_ID=? Hibernate: select children0_.PARENT_MENU_ID as PARENT5_1_, children0_.MENU_ID as MENU1_1_, children0_.MENU_ID as MENU1_2_0_, children0_.description as descript2_2_0_, children0_.IS_DEL as IS3_2_0_, children0_.MENU_NAME as MENU4_2_0_, children0_.PARENT_MENU_ID as PARENT5_2_0_ from RBAC_MENUS children0_ where children0_.PARENT_MENU_ID=? ... 菜单能够正常展现,但是这个异常为什么发生呢,我还碰到一个问题就是当我选择一个菜单项,并且插入一个子菜单的时候,发生一个异常,并且页面也无法展现最新插入的那个菜单,需要刷新一下才能看到新插入的菜单 程序界面如下: [img]http://hiphotos.baidu.com/lucky_sonic/pic/item/c81382cf5b0ce869f9dc612a.jpg[/img]
Javascript DOM编程艺术 Ajax XMLhttpRequest 实例问题
第二版 7章 P115页 AJAX中 XMLhttpRequest 的例子为何实现不了呢? ![![![图片说明](https://img-ask.csdn.net/upload/201705/18/1495090426_47813.png)图片说明](https://img-ask.csdn.net/upload/201705/18/1495090411_795048.png)图片说明](https://img-ask.csdn.net/upload/201705/18/1495090399_170604.png) ![图片说明](https://img-ask.csdn.net/upload/201705/18/1495090713_242087.png) 页面不能显示出example.txt 中的文本 会先弹出RequestReceived 在弹出 Function Done 页面上都是空白 试了几个浏览器都没打开 还有 DOM 7章 重返图片库P 112页 也没实现 这是HTML页面代码 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Image Gallery</title> <style> body { font-family: "Helvetica", "Arial", "serif"; color: #333; background-color: #ccc; margin: 1em 10%; } h1 { color: #333; background-color: transparent; } a { color: #c60; background-color: transparent; font-weight: bold; text-decoration: none; } ul { padding: 0; } li { float: left; padding: 1em; list-style: none; } img { display: block; clear: both; padding: 20px 20px; } #imagegallery { list-style: none; } #imagegallery li { display: inline; } #imagegallery li a img { border: 0; } </style> </head> <body> <h1>Snapshots</h1> <ul id="imagegallery"> <li> <a href="p1.jpg" title="A firework display"><img src="p1.jpg" alt="Firework" width="150" height="120"></a> </li> <li> <a href="p2.jpg" title="A cup of black coffee"><img src="p2.jpg" alt="Coffee" width="150" height="120"></a> </li> <li> <a href="p3.jpg" title="A red, red rose"><img src="p3.jpg" alt="Rose" width="150" height="120"></a> </li> <li> <a href="p4.jpg" title="The famous clock"><img src="p4.jpg" alt="BigBen" width="150" height="120"></a> </li> </ul> <script src="fun.js"></script> </body> </html> JS中的代码 function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } function insertAfter() { var parent = targetElement.parentNode; if (parent.lastChild == targetElement) { parent.appendChild(newElement); } else { parent.insertBefore(newElement, targetElement.nextSibling); } } function preparePlaceholder() { if (!document.createElement) return false; if (!document.createTextNodde) return false; if (!document.getElementById) return false; if (!document.getElementById("imagegallery")) return false; var placeholder = document.createElement("img"); placeholder.setAttribute("id", "palceholder"); placeholder.setAttribute("src", "p5.jpg"); placeholder.setAttribute("alt", "my image gallery"); var description = document.createElement("p"); description.setAttribute("id", "description"); var desctext = document.createTextNode("choose an image"); description.appendChild(desctext); var gallery = document.getElementById("imagegallery"); insertAfter(placeholder, gallery); insertAfter(description, placeholder); } function prepareGallery() { if (!document.getElementsByTagName) return false; if (!document.getElementById) return false; if (!document.getElementById("imagegallery")) return false; var gallery = document.getElementById("imagegallery"); var links = gallery.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) { links[i].onclick = function() { return !showPic(this); } links[i].onkeypresss = links[i].onclick; } } function showPic(whichpic) { if (!document.getElementById("placeholder")) return true; var source = whichpic.getAttribute("href"); var placeholder = document.getElementById("placeholder"); placeholder.setAttribute("src", source); if (placeholder.nodeName != "IMG") return false; if (document.getElementById("description")) { var text = whichpic.getAttribute("title") ? whichpic.getAttribute("title") : ""; var description = document.getElementById("description"); if (description.firstChild.nodeType == 3) { description.firstChild.nodeValue = text; } } return false; } addLoadEvent(preparePlaceholder); addLoadEvent(prepareGallery); ``` ![图片说明](https://img-ask.csdn.net/upload/201705/18/1495090989_349453.png) 这是页面显示出来的效果 图片点击后没反应,之前改了几次都没成功。 新手还在学习中,见谅
memory leak我的 jdbc 被强制注销
memory leak我的 jdbc 被强制注销, 我前几天还好好的,今天发现能够连到数据库oracle,但是新的程序无法在数据库中呈现出来,并且原来的表也没有了 The web application [UsersManager2] registered the JDBC driver [oracle.jdbc.driver.OracleDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. ## **这个是我的登录Servlet** package com.wzy.view; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //返回一个界面(html技术) out.println("<img src='imgs/1.png'/><hr/>"); out.println("<h1>用户登录</h1>"); //action 应该这样写/web应用名/Servlet的url out.println("<form action='/UsersManager2/LoginCLServlet ' method='post'>"); out.println("用户名:<input type='text' name='id'/><br/>"); out.println("密码:<input type='password' name='password'/><br/>"); out.println("<input type='submit' value='登录'/><br/>"); out.println("</form>"); String errInfo=(String) request.getAttribute("err"); if(errInfo!=null){ out.println("<font color='red'>"+errInfo+"</font>"); } out.println("<hr/><img src='imgs/2.png'/>"); } ## ** 这是登录处理转向Servlet** package com.wzy.controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginCLServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //向浏览器返回中文 request.setCharacterEncoding("utf-8"); //向控制台返回中文 在这里没什么用 //response.setContentType("text/html;charset=utf-8"); //PrintWriter out = response.getWriter(); //接收用户提交的用户名和密码 String id=request.getParameter("id"); String password=request.getParameter("password"); //到数据库中取验证 Connection ct = null; ResultSet rs= null; PreparedStatement ps=null; try { //1.加载驱动 Class.forName("oracle.jdbc.driver.OracleDriver"); //2.得到连接 ct=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORACLE","c##scott","tiger"); //3.创建PreparedStatement ps=ct.prepareStatement("select * from users where id=? and passwd=?"); //给?赋值 ps.setObject(1,id); ps.setObject(2, password); //4.执行操作 rs=ps.executeQuery(); //5.根据结果做处理 if(rs.next()){ //说明该用户合法 request.getRequestDispatcher("/MainFrame").forward(request,response); }else{ request.setAttribute("err", "用户id或者 密码有误!"); request.getRequestDispatcher("/LoginServlet").forward(request,response); } }catch (Exception e){ request.setAttribute("err", "您的输入id不是数字!"); request.getRequestDispatcher("/LoginServlet").forward(request,response); e.printStackTrace(); } finally{ //关闭资源 if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } rs=null; } if(ps!=null ){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } ps=null; } if(ct!=null){ try { ct.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } ct=null; } } ## 这是调转后第一个统筹页面**** package com.wzy.view; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MainFrame extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<img src='imgs/1.png'/>测试登录servlet页面</a> <a href='/UsersManager2/LoginServlet'>返回重新登录</a><hr/>"); //out.println("<h1>测试登录</h1>"); out.println("<h3>请选择您要进行的操作</h3>"); out.println("<a href='/UsersManager2/ManageUsers'>管理用户</a><br/>"); out.println("<a herf=''>添加用户</a><br/>"); out.println("<a herf=''>查找用户</a><br/>"); out.println("<a herf=''>退出系统</a><br/>"); out.println("<hr/><img src='imgs/2.png'/>"); } ## 接下来点进去会看到一张绿色的表10条信息我之前一直好好的**** 这个是我用jdbc连接oracle 看表的地方现在被强制注销, 我明明打了finally 然后close了,可是 却说我的项目在web application停止后没有被释放,所以为了防止内存泄露要强行关闭jdbc驱动,导致我现在 无法用jdbc 来更新内容,想问一下究竟是怎么回事 , 还望高手指点 下面的程序只能显示到“管理用户”这一行 最下面的数字也能打印但是 jdbc的链接这里被停止了,我现在不明白的是导致我连不上的原因是哪里没被释放,还是要再注册一下呢? package com.wzy.view; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ManageUsers extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<img src='imgs/1.png'/>测试登录servlet页面</a> <a href='/UsersManager2/LoginServlet'>返回主界面</a> <a href='/UsersManager2/LoginServlet'>安全退出</a><hr/>"); out.println("<h1>管理用户</h1>"); //从数据库中取出用户信息,并显示 //到数据库中去验证 Connection ct=null; ResultSet rs=null; PreparedStatement ps=null; try{ //1.加载驱动 Class.forName("oracle.jdbc.driver.OracleDriver"); //2.得到连接 ct=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORACLE","c##scott","tiger"); //算出共有多少页 rs=ps.executeQuery(); //1.查询rowCount rs.next(); //把游标下移 //4.执行操作 rs=ps.executeQuery(); out.println("<table border=1px bordercolor=green cellspacing=0 width=500px>"); out.println("<tr><th>id</th><th>用户名</th><th>email</th><th>级别</th></tr>"); //循环显示所有用户信息 while(rs.next()){ out.println("<tr><td>"+rs.getInt(1)+ "</td><td>"+rs.getString(2)+ "</td><td>"+rs.getString(3)+ "</td><td>"+rs.getInt(4)+ "</td></tr>"); } out.println("</table>"); //显示分页 }catch(Exception e){ }finally{ //关闭资源 if(rs!=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); } } rs=null; } if(ps!=null){ try{ ps.close(); }catch (SQLException e){ e.printStackTrace(); } ps=null; } if(ct!=null){ try{ ct.close(); }catch(SQLException e){ e.printStackTrace(); } ct=null; } out.println("1324234"); } 望大神指教,网上有用dbcp 重新写个close和改变 dbcp的配置来解决的,可我是新手还不懂hibernate 也有到server.xml里去关掉memory leak的监听,我试了,不行,我现在的情况是能够连到数据库oracle,但是原先的表无法显示和新写的代码无法传递进去,发生了宕机。还望各路高手救命
Java新手求助,动态下拉列表
项目用LayUi框架+SpringMvc实现的 点击总体页面右侧的编辑按钮弹出Layui渲染的窗口(另一个jsp页),窗口中的下拉列表想做成从后端数据库表中查出的数据 ![图片说明](https://img-ask.csdn.net/upload/201706/07/1496817409_419946.png) 整体页: ``` <fieldset class="layui-elem-field"> <legend>诉讼指南列表</legend> <div class="layui-field-box layui-form"> <table class="layui-table admin-table"> <thead> <tr> <th style="width: 30px;"><input type="checkbox" lay-filter="allselector" lay-skin="primary"></th> <th>标题</th> <th>日期</th> <th>分类</th> <th>操作</th> </tr> </thead> <tbody id="content"> </tbody> </table> </div> </fieldset> <div class="admin-table-page"> <div id="paged" class="page"> </div> </div> <script type="text/html" id="tpl"> {{# layui.each(d.list, function(index, item){ }} <tr> <td><input type="checkbox" lay-skin="primary"></td> <td>{{ item.heading }}</td> <td>{{ item.dates }}</td> <td>{{ item.litigationguidesubmenu.litigationguidesubmenuname }}</td> <td> <!-- 修改按钮 --> <a href="javascript:;" data-gid="{{ item.gid }}" data-heading="{{ item.heading }}" data-straightmatter="{{ item.straightmatter }}" data-dates="{{ item.dates }}" data-opt="edit" class="layui-btn layui-btn-mini" id="update" onclick="edit(this)">编辑</a> <a href="javascript:;" data-gid="{{ item.gid }}" data-opt="del" id="del" class="layui-btn layui-btn-danger layui-btn-mini" onclick="del(this)">删除</a> </td> </tr> {{# }); }} </script> <script type="text/javascript" src="${pageContext.request.contextPath }/plugins/layui/layui.js"></script> <script> layui.config({ base: 'js/' }); layui.use(['paging', 'form'], function() { var $ = layui.jquery, paging = layui.paging(), layerTips = parent.layer === undefined ? layui.layer : parent.layer, layer = layui.layer, form = layui.form(); paging.init({ /* 省略查询代码 */ complate: function() { //点击编辑按钮弹出编辑窗口 $.post('view/LitigationGuide/forms/updateForm.jsp',{gid:$(this).data('gid'),heading:$(this).data('heading'),straightmatter:$(this).data('straightmatter'),dates:$(this).data('dates'),submenu:$(this).data('submenu')}, function(form) { addBoxIndex = layer.open({ type: 1, title: '修改诉讼指南', content: form, btn: ['保存', '取消'], shade: false, offset: ['100px', '30%'], area: ['800px', '620px'], zIndex: 19950924, maxmin: true, yes: function(index) { //触发表单的提交事件 $('form.layui-form').find('button[lay-filter=edit]').click(); }, success: function(layero, index) { //弹出窗口成功后渲染表单 var form = layui.form(); form.render(); form.on('submit(edit)', function(data) { //参数传入controller $.post('litigationguide/updateLitigationGuide.json',data.field,function(res){ location.reload(); }); return false; }); }, end: function() { addBoxIndex = -1; } }); }); }); }); }, }); </script> ``` updateForm.jsp: ``` <html> ... <body> <!--省略标题、正文、日期等...--> <div class="layui-form-item" style="width:200px; margin-left:110px;"> <select name="fenlei" lay-verify="" > <option value="">请选择文章分类</option> <c:forEach items="${ 后台返回的集合 }" var="s"> <option value="${ s.id }">${ s.值 }</option> </c:forEach> </select> </div> ... </body> ... </html> ``` 小白还求高手指教
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、PDF搜索网站推荐 对于大部
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入  假设现有4个人
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
【图解经典算法题】如何用一行代码解决约瑟夫环问题
约瑟夫环问题算是很经典的题了,估计大家都听说过,然后我就在一次笔试中遇到了,下面我就用 3 种方法来详细讲解一下这道题,最后一种方法学了之后保证让你可以让你装逼。 问题描述:编号为 1-N 的 N 个士兵围坐在一起形成一个圆圈,从编号为 1 的士兵开始依次报数(1,2,3…这样依次报),数到 m 的 士兵会被杀死出列,之后的士兵再从 1 开始报数。直到最后剩下一士兵,求这个士兵的编号。 1、方
致 Python 初学者
文章目录1. 前言2. 明确学习目标,不急于求成,不好高骛远3. 在开始学习 Python 之前,你需要做一些准备2.1 Python 的各种发行版2.2 安装 Python2.3 选择一款趁手的开发工具3. 习惯使用IDLE,这是学习python最好的方式4. 严格遵从编码规范5. 代码的运行、调试5. 模块管理5.1 同时安装了py2/py35.2 使用Anaconda,或者通过IDE来安装模
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
      11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下
日均350000亿接入量,腾讯TubeMQ性能超过Kafka
整理 | 夕颜出品 | AI科技大本营(ID:rgznai100) 【导读】近日,腾讯开源动作不断,相继开源了分布式消息中间件TubeMQ,基于最主流的 OpenJDK8开发的
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
相关热词 如何提升c#开发能力 矩阵乘法c# c#调用谷歌浏览器 c# 去空格去转义符 c#用户登录窗体代码 c# 流 c# linux 可视化 c# mvc 返回图片 c# 像素空间 c# 日期 最后一天
立即提问