JSP中Form表单reset出现一个问题

[code="jsp"]

function fun_one() { document.newForm.one.style.display = ""; document.newForm.two.style.display = "none"; } function fun_two() { document.newForm.one.style.display = "none"; document.newForm.two.style.display = ""; } Input One Input Two
InputOne
InputTwo
 

[/code]

我的想法是用radio来控制表单里的元素,当点击Input One时,下面InputOne的文本框就会显示出来,而InputTwo就会隐藏;反之,点击Input Two也会有这样的效果。但是当我先点击了Input Two时,这时InputOne的文本框隐藏,InputTwo显示,这时还是正常情况,如果我接着点击reset,重新填写时,由于Input One默认被选中,理想的情况是InputOne重新显示,InputTwo隐藏,可是实际情况是Input One是被选中状态,而InputOne隐藏,InputTwo显示。
这个问题很奇怪,不知道我是否描述清楚,有人知道是哪里出的问题吗,清指点,谢谢!

2个回答

[code="java"]<br> function fun_one() {<br> document.getElementById(&quot;one&quot;).style.display = &quot;&quot;;<br> document.getElementById(&quot;two&quot;).style.display = &quot;none&quot;;<br> }<br> function fun_two() {<br> document.getElementById(&quot;one&quot;).style.display = &quot;none&quot;;<br> document.getElementById(&quot;two&quot;).style.display = &quot;&quot;;<br> }<br>

Input One Input Two
InputOne
InputTwo
 

[/code]

jinnianshilongnian
jinnianshilongnian 这个是没办法的 reset仅仅是把表单的值重置 不会修改dom的
7 年多之前 回复
c920644981
载心问情 在reset里加个事件,我之前也考虑过,但是我有好几张表单里面有不止一种这种情形的,怎么办
7 年多之前 回复

那就自己写一个,手动清空输入的值,同时修改dom的值

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
一个form表单一个submit
JSP内如下,执行的时候不校验数据, 直接就跳转了,想使用纯JS 可以校验数据吗? 还是只有把**onclick="isEmpty()"** 换成ID,然后使用ajax进行校验? ``` <script type="text/javascript" > function trim(s) { var count = s.length; var st = 0; // start var end = count-1; // end if (s == "") return s; while (st < count) { if (s.charAt(st) == " ") st ++; else break; } while (end > st) { if (s.charAt(end) == " ") end --; else break; } return s.substring(st,end + 1); } //增加用户判断 function isEmpty(){ //form1是form中的name属性 var form = document.form; if(trim(form.name.value)==""){ alert("用户名不能为空!"); return false; } if(trim(form.age.value)==""){ alert("年龄不能为空!"); return false; } return true; } </script> </head> <body> <div>用户信息</div> <form name="form" action="/add1User.do" method="post"> <div> <label>姓名:</label> <input type="text" name="NAME" > </div> <div > <label>年龄:</label> <input type="text" name="AGE" > </div> <div> <input type="submit" value="保存"  onclick="isEmpty()"> <input type="reset" value="清除"> </div> </form> </body> </html> ```
jsp页面中的表单数据在Servlet中取出来全为null
jsp页面中都是输入了数据的,可是Servlet中获取的数据每一个都为null jsp: ``` <form action="../addnews" method="post" enctype="multipart/form-data"> <p> <label> 主题 </label> <select name="natid"> <option>选择</option> <c:forEach items="${themelist}" var="t"> <option value="${t.themeId}">${t.themeName}</option> </c:forEach> </select> </p> <p> <label> 标题 </label> <input name="natitle" type="text" class="opt_input" /> </p> <p> <label> 作者 </label> <input name="naauthor" type="text" class="opt_input" value="${ui.username}" /> </p> <p> <label> 内容 </label> <textarea name="nacontent" cols="70" rows="10"></textarea> &nbsp;&nbsp; </p> <input name="action" type="hidden" value="addnews"/> <input type="submit" value="提交" class="opt_sub" /> <input type="reset" value="重置" class="opt_sub" /> </form> servlet: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); String i = request.getParameter("natid"); int id = 1; if (i != null) { id = Integer.parseInt(i); } String title = request.getParameter("natitle"); String author = request.getParameter("naauthor"); String content = request.getParameter("nacontent"); NewsDao ttd = new NewsDaoImpl(); News ni = new News(id, title, author, content, new Date()); int b = ttd.addNews(ni); if (b > 0) { response.sendRedirect("first"); } } ```
jsp提交表单后出现目标页面的源代码
注册页面 <form id="commenform" action="register_enter.jsp" method="post" > <fieldset class="field"> <legend align="center">用户注册</legend> <table class="table_set"> <tr> <td class="td_set">邮箱:</td> <td><input type="text" size="25" id="email" name="email" /></td> </tr> <tr> <td class="td_set">用户名:</td> <td><input type="text" size="25" id="name" name="name"></td> </tr> <tr> <td class="td_set">性别:</td> <td><input type="radio" id="sex" name="sex" >男 <input type="radio" id="sex" name="sex">女</td> </tr> <tr> <td class="td_set">密码:</td> <td><input type="password" size="25" id="userpass1" name="userpass1" /></td> </tr> <tr> <td class="td_set">确认密码:</td> <td><input type="password" size="25" id="userpass2" name="userpass2"/></td> </tr> <tr> <td colspan="2" class="submit_set"><input type="submit" value="提交">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="重置" /></td> </tr> </table> </fieldset> </form> 目标页面 <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.sql.*" %> <%@ page import="register.operation.*" %> <html> <body> <jsp:useBean id="add" class="register.operation.AddCustomer" scope="request" /> <jsp:setProperty name="add" property="*" /> <br>你添加记录操作的结果: <jsp:getProperty name= "add" property="addMessage" /> </body> </html> Java package register.operation; import java.sql.*; public class AddCustomer { String email="", name="", sex="", password=""; String addMessage=""; public AddCustomer() { try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){ } } public void setEmail(String e) { email=e.trim(); } public void setName(String n) { name=n.trim(); try{ byte bb[]=name.getBytes("ISO-8859-1"); name=new String(bb,"gb2312"); } catch(Exception e){} } public void setSex(String s) { sex=s.trim(); } public void setPassword(String p) { password=p.trim(); } public String getAddMessage() { String insertCondition="INSERT customer VALUES( '"+email+ "', '"+name+"','"+sex+"',"+password+")"; String str=""; Connection con; Statement sql; try { con=DriverManager.getConnection("jdbc:odbc:e_shop","Administrator","225196"); sql=con.createStatement(); if(email.length()>0) { int m=sql.executeUpdate(insertCondition); if(m!=0) { str="注册成功"; } else { str="注册失败"; } } else { str="必须要有邮箱地址"; } con.close(); } catch(SQLException e) { str="邮箱地址已注册"+e; } return str; } }
JSP在页面内显示所有表单信息,对某一行进行修改操作,结果所有数据都进行传值了?
我想对这个页面中的一项信息进行修改,原显示是这样的![图片说明](https://img-ask.csdn.net/upload/201912/07/1575686265_53 8116.jpg) 然后问题来了,我对选中对待某一行做了修改操作后,网页传值是这样的: ``` lhost:8084/JavaWebTest6/Subscripton.jsp?mailserver=qq.com&mailusernae=zsq&mailpassword=1&mailservertype=1&Username=null&mailserver=126.com&mailusernae=zs&mailpassword=1&mailservertype=2&Username=null&mailserver=136.com&mailusernae=ad&mailpassword=1&mailservertype=POP3&Username=null&mailserver=qq.com&mailusernae=w&mailpassword=q&mailservertype=1&Username=null&mailserver=136.com&mailusernae=e&mailpassword=e&mailservertype=e&Username=null&mailserver=qq.com&mailusernae=q&mailpassword=q&mailservertype=q&Username=null&Mailserver=&Mailusernae=&Mailpassword=&Mailservertype=&Username=null* ``` 很明显,把所有值都传过来了,下面是显示页的代码(有标注的地方是有问题的地方): ``` <%-- Document : mainMenu Created on : 2019-11-7, 11:28:27 Author : Administrator --%> <%@page language ="java" pageEncoding="UTF-8"%> <%@page import="java.sql.*"%> <!DOCTYPE html> <html> <head> <title>用户账号管理系统</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <div></div> <h2><b>用户账号及邮箱信息维护界面</b></h2> <table frame="hsides"> <% String username=request.getParameter("name"); out.println("用户名:"+username); %> <tr> <a href="account.jsp?username=<%=username%>">修改密码</a><br> </tr> <tr><br></tr> <tr> <td><input type="text" disabled="true" value="邮箱主机"></td> <td><input type="text" disabled="true" value="邮箱用户名"></td> <td><input type="text" disabled="true" value="邮箱密码"></td> <td><input type="text" disabled="true" value="邮箱服务器类型"></td> </tr> <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection("jdbc:odbc:ACCountdb"); Statement stat = conn.createStatement(); String sql = "SELECT * FROM TB_SUBSCRIPTION WHERE USERNAME='"+username+"'"; ResultSet rs = stat.executeQuery(sql); //这里写的循环直接导致后面传值的时候,所有表中数据都传过去了 while (rs.next()){ //String username = rs.getString("USERNAME"); String mailserver = rs.getString("MAILSERVER"); String mailusernae = rs.getString("MAILUSERNAE"); String mailpassword = rs.getString("MAILPASSWORD"); String mailservertype = rs.getString("MAILSERVERTYPE"); %> <form action="Subscripton.jsp"> <tr> <br> <td><input type="text" value='<%=mailserver%>' name="mailserver" ></td> <td><input type="text" value='<%=mailusernae%>' name="mailusernae"></td> <td><input type="text" value='<%=mailpassword%>' name="mailpassword"></td> <td><input type="text" value="<%=mailservertype%>" name="mailservertype"></td> <td><input type="submit" value="修改邮箱信息"></td> <td><a href="delSubscription.jsp?mailserver=<%=mailserver%>&mailusernae=<%=mailusernae%>">删除</a></td> <td><input name="Username" value='<%=username%>'</td> </tr> <% } stat.close(); conn.close(); %> <form action="addSubscription.jsp"> <tr> <br> <td><input type="text" name="Mailserver"></td> <td><input type="text" name="Mailusernae"></td> <td><input type="password" name="Mailpassword"></td> <td><input type="text" name="Mailservertype"></td> <td><input type="submit" value="添加新邮箱"></td> <td><input name="Username" value='<%=username%>'</td> </tr> </form> </table> <a href="login.jsp">退出</a> </body> </html> ``` 这是修改页的代码: ``` <%-- Document : Subscripton Created on : 2019-12-7, 10:01:00 Author : Administrator --%> <%@page language="java" pageEncoding="UTF-8"%> <%@page import="java.sql.*"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户账号管理系统</title> </head> <body> <% String username=request.getParameter("Username"); String mailserver=request.getParameter("mailserver"); String mailusernae=request.getParameter("mailusernae"); %> <form action="editSubscripton.jsp?mailserver=<%=mailserver%>&mailusernae=<%=mailusernae%>"> 用户名:<input type="text" name="Username" value="<%=username%>"><br><br> 邮箱密码:<input type="text" name="mailpassword">*<br><br> 邮箱服务器类型: <input type="text" name="mailservertype">*<br><br> <input type="submit" value="修改"> <input type="reset" value="重置"> </form> <a href="mainMenu.jsp">返回</a> </body> </html> ``` 希望能得到解答!感谢!!
jsvalidation用法,小白提问!!
1、使用jsvalidation没效果,点击表单提交没验证直接到了下一页,按F12显示 HTTP404: 找不到 - 服务器尚未找到与请求的 URI (统一资源标识符)匹配的任何内容。 GET - http://localhost:8081/js/validation-framework.js 不知道啥原因,jsvalidation的三个dtd xml 和js代码是老师给的,说是要写一个什么正则表达式,不会改 求解答 2 查过资料 web。xml中没有设置那个什么过滤那个 3下面是framework。js的代码,看不懂 ``/* * JavaScript Validation Framework * * Author: Michael Chen(mechiland) on 2004/03 * This software is on the http://www.cosoft.org.cn/projects/jsvalidation * for update, bugfix, etc, you can goto the homepage and submit your request * and question. * Apache License 2.0 * You should use this software under the terms. * * Please, please keep above words. At least ,please make a note that such as * "This software developed by Michael Chen(http://www.jzchen.net)" . * $Id: validation-framework.js,v 1.7 2004/04/30 05:33:29 jzchen Exp $ */ /** Config Section, Config these fields to make this framework work. **/ // If there is only one config file in your system, use this property. otherwise, use // ValidationFramework.init("configfile") // instead. var ValidationRoot = "/LoginServletProjectFour/js/"; // the field style when validation fails. it aim to provide more beautiful UI and more good // experience to the end-user. // NOTE: this will be buggy. Please report the error to me. var ValidationFailCssStyle = "border:2px solid #FFCC88;"; //Validation function. The entry point of the framework. function doValidate(formRef) { try { var formId = formRef; if (typeof (formRef) == "string") { formId = formRef; } else if (typeof (formRef) == "object") { formId = formRef.getAttribute("id"); } var form = FormFactory.getFormFromId(formId); if (form != null) { return ValidationFramework.validateForm(form); } else { return false; } } catch (e) { ValidationFramework.exception(e.name+":" +e.description); return false; } } /**===================================================================**/ /* * JSValidation Framework Code Started * * Please do not modify the code unless you are very familiar with JavaScript. * The best way to solve problem is report the problem to our project page. * url: http://cosoft.org.cn/projects/jsvalidation */ // The Xml document. To process cross-browser. Thanks Eric. function XmlDocument() {} XmlDocument.create = function () { if (document.implementation && document.implementation.createDocument) { return document.implementation.createDocument("", "", null); } else if (window.ActiveXObject) { try { var prefix = ["MSXML2", "MSXML", "Microsoft", "MSXML3"]; for (var i = 0; i < prefix.length; i++) { //return new ActiveXObject(prefix[i] + ".DomDocument"); var obj = new ActiveXObject(prefix[i] + ".DomDocument"); if (obj == null || typeof(obj) == 'undefined') { continue; } else { return obj; } } } catch (e) { //^_^ throw new Error("My God, What version of IE are you using? IE5&+ is requiered."); } } else throw new Error("Cannot create DOM Document!"); } function ValidationFramework() {} ValidationFramework._validationCache = null; ValidationFramework._currentForm = null; ValidationFramework._userLanguage="auto"; /** * Validate a form. * NOTE: the form is Framework virture form, not the HTML Form. * Html Form can be transform to Virture form by * FormFactory.getFormFromId(htmlFormId); * See the doc for more information. * @param form the virtual form. */ ValidationFramework.validateForm = function(fform) { ValidationFramework._currentForm = fform; var failFields = []; var id = fform.getId(); var showError = fform.getShowError(); var showType = fform.getShowType(); var br = null; if (showError != "alert") { br = "<br />"; } else { br = "\n"; } var errorStrArray = []; var ret = false; var formObj = document.getElementById(id); var fields = fform.getFields(); var rightnum = 0; for (var i = 0; i < fields.length; i++) { var retVal = ValidationFramework.validateField(fields[i]); var fo=formObj[fields[i].getName()]; if (typeof (fo) !='undefined' && fo != null && typeof(fo.type) != "undefined") { fo.style.cssText = ""; } if (retVal != "OK") { errorStrArray[errorStrArray.length] = retVal; failFields[failFields.length] = formObj[fields[i].getName()]; } else { rightnum ++; } } if (rightnum == fields.length) { ret = true; } if (errorStrArray.length > 0) { if (showError == "alert") { if (showType == "first") { alert(errorStrArray[0]); } else { alert(errorStrArray.join(br)); } } else { var errObj = document.getElementById(showError); if (showType == "first") { errObj.innerHTML = errorStrArray[0]; } else { errObj.innerHTML = errorStrArray.join(br); } } if (typeof (failFields[0]) !='undefined' && failFields[0] != null && typeof(failFields[0].type) != "undefined") { failFields[0].focus(); } for (var i = 0; i < failFields.length; i++) { var o = failFields[i]; if ( typeof (o) !='undefined' && o != null && typeof(o.type) != "undefined") { o.style.cssText = ValidationFailCssStyle; } } } return ret; } /** * Validation the field * @param filed the field you want to validate. */ ValidationFramework.validateField = function(field) { var depends = field.getDepends(); var retStr = "OK"; for (var i = 0; i < depends.length; i++) { if (!ValidationFramework.validateDepend(field, depends[i])) { retStr = ValidationFramework.getErrorString(field, depends[i]); return retStr; //Break; } } return retStr; } /** * Validate the field depend. * This function dispatch the various depends into ValidateMethodFactory.validateXXX */ ValidationFramework.validateDepend = function(field, depend) { if (depend.getName() == "required") { return ValidateMethodFactory.validateRequired(field, depend.getParams()); } else if (depend.getName() == "integer") { return ValidateMethodFactory.validateInteger(field, depend.getParams()); } else if (depend.getName() == "double") { return ValidateMethodFactory.validateDouble(field, depend.getParams()); } else if (depend.getName() == "commonChar") { return ValidateMethodFactory.validateCommonChar(field, depend.getParams()); } else if (depend.getName() == "chineseChar") { return ValidateMethodFactory.validateChineseChar(field, depend.getParams()); } else if (depend.getName() == "minLength") { return ValidateMethodFactory.validateMinLength(field, depend.getParams()); } else if (depend.getName() == "maxLength") { return ValidateMethodFactory.validateMaxLength(field, depend.getParams()); } else if (depend.getName() == "email") { return ValidateMethodFactory.validateEmail(field, depend.getParams()); } else if (depend.getName() == "date") { return ValidateMethodFactory.validateDate(field, depend.getParams()); } else if (depend.getName() == "time") { return ValidateMethodFactory.validateTime(field, depend.getParams()); } else if (depend.getName() == "mask") { return ValidateMethodFactory.validateMask(field, depend.getParams()); } else if (depend.getName() == "integerRange") { return ValidateMethodFactory.validateIntegerRange(field, depend.getParams()); } else if (depend.getName() == "doubleRange") { return ValidateMethodFactory.validateDoubleRange(field, depend.getParams()); } else if (depend.getName() == "equalsField") { return ValidateMethodFactory.validateEqualsField(field, depend.getParams()); } else { ValidationFramework.exception("还未实现该依赖: " + depend.getName()); return false; } } // hold the current config file var _validationConfigFile = ""; ValidationFramework.getDocumentElement = function() { if (ValidationFramework._validationCache != null) { return ValidationFramework._validationCache; } var file = ""; if (_validationConfigFile != "") { file = _validationConfigFile; } else { file = ValidationRoot + "validation-config.xml"; } var xmlDoc = XmlDocument.create(); xmlDoc.async = false; // Damn!!! it cost me half an hour to fix it! xmlDoc.load(file); if (xmlDoc.documentElement == null) { ValidationFramework.exception("配置文件读取错误,请检查。"); return null; } // TODO: parse the document if it's a valid document. ValidationFramework._validationCache = xmlDoc.documentElement; var lang=ValidationFramework._validationCache.getAttribute("lang"); ValidationFramework._userLanguage = (lang==null) ? "auto" : lang; return ValidationFramework._validationCache; } ValidationFramework.init = function(configFile) { _validationConfigFile = configFile; ValidationFramework.getDocumentElement(); } ValidationFramework.getAllForms = function() { var vforms = []; var root = ValidationFramework.getDocumentElement(); if (root != null) { var fs = root.childNodes; for (var i = 0;i < fs.length ;i++ ) { vforms[i] = new ValidationForm(fs.item(i)); } } return vforms; } ValidationFramework.getErrorString = function(field, depend) { var stringResource = null; var lang = ValidationFramework._userLanguage.toLowerCase(); //if lang == auto, get the user's browser language. if (lang == "auto") { // different browser has the different method the get the // user's language. so this is a stupid way to detect the // most common browser IE and Mozilla. if (typeof navigator.userLanguage == 'undefined') lang = navigator.language.toLowerCase(); else lang = navigator.userLanguage.toLowerCase(); } // get the language if (typeof ValidationErrorString[lang] != 'object') { stringResource = ValidationErrorString['zh-cn']; } else { stringResource = ValidationErrorString[lang]; } var dep = depend.getName().toLowerCase(); var retStr = stringResource[dep]; //If the specified depend not defined, use the default error string. if (typeof retStr != 'string') { retStr = stringResource["default"]; retStr = retStr.replace("{0}", field.getDisplayName()); return retStr; } retStr = retStr.replace("{0}", field.getDisplayName()); if (dep == "minlength" || dep == "maxlength" || dep == "date" ) { retStr = retStr.replace("{1}", depend.getParams()[0]); } else if ( dep == "equalsfield") { var eqField = field.getForm().findField(depend.getParams()[0]); if (eqField == null) { ValidationFramework.exception("找不到名称为[" + depend.getParams()[0]+"]的域,请检查xml配置文件。"); retStr = "<<配置错误>>"; } else { retStr = retStr.replace("{1}", field.getForm().findField(depend.getParams()[0]).getDisplayName()); } } else if (dep == "integerrange" || dep == "doublerange") { retStr = retStr.replace("{1}", depend.getParams()[0]); retStr = retStr.replace("{2}", depend.getParams()[1]); } return retStr; } ValidationFramework.getWebFormFieldObj = function(field) { var obj = null; if (ValidationFramework._currentForm != null) { var formObj = document.getElementById(ValidationFramework._currentForm.getId()); obj = formObj[field.getName()]; if (typeof(obj) == 'undefined') { obj = null; } } if (obj == null) { ValidationFramework.exception("在配置文件中有需要验证的域,但在实际网页表单中不存在:[name=" + field.getName() + "]。"); } return obj; } ValidationFramework.exception = function(str) { var ex = "JavaScript Validation Framework 运行时错误:\n\n"; ex += str; ex += "\n\n\n任何运行错误都会导致该域验证失败。"; alert(ex); } ValidationFramework.getIntegerValue = function(val) { var intvalue = parseInt(val); if (isNaN(intvalue)) { ValidationFramework.exception("期待一个整型参数。"); } return intvalue; } ValidationFramework.getFloatValue = function(val) { var floatvalue = parseFloat(val); if (isNaN(floatvalue)) { ValidationFramework.exception("期待一个浮点型参数。"); } return floatvalue; } /** * FormFactory * Build virture form from Html Form. */ function FormFactory() {} FormFactory.getFormFromDOM = function(dom) { var form = new ValidationForm(); form.setId(dom.getAttribute("id")); form.setShowError(dom.getAttribute("show-error")); form.setOnFail(dom.getAttribute("onfail")); form.setShowType(dom.getAttribute("show-type")); if (dom.hasChildNodes()) { var f = dom.childNodes; for (var i = 0; i < f.length; i++) { if (f.item(i) == null||typeof(f.item(i).tagName) == 'undefined' || f.item(i).tagName != 'field') { continue; } var field = FieldFactory.getFieldFromDOM(f.item(i)); if (field != null) { form.addField(field); } } } return form; } /// Get the Form from ID FormFactory.getFormFromId = function(id) { var root = ValidationFramework.getDocumentElement(); if ( root == null || (!root.hasChildNodes()) ) return null; var vforms = root.childNodes; for (var i = 0; i < vforms.length; i++) { var f = vforms.item(i); if (typeof(f.tagName) != 'undefined' && f.tagName == 'form' && f.getAttribute("id") == id) { return FormFactory.getFormFromDOM(f); } } return null; } /** * A validation form object. */ function ValidationForm() { this._fields = []; this._id = null; this._showError = null; this._onFail = null; this._showType = null; this.getFields = function() { return this._fields; } this.setFields = function(p0) { this._fields = p0; } this.getId = function() { return this._id; } this.setId = function(p0) { this._id = p0; } this.getShowError = function() { return this._showError; } this.setShowError = function(p0) { this._showError = p0; } this.getShowType = function() { return this._showType; } this.setShowType = function(p0) { this._showType = p0; } this.getOnFail = function() { return this._onFail; } this.setOnFail = function(p0) { this._onFail = p0; } // find field by it's name this.findField = function(p0) { for (var i = 0; i < this._fields.length; i++) { if (this._fields[i].getName() == p0) { return this._fields[i]; } } return null; } this.addField = function(p0) { this._fields[this._fields.length] = p0; p0.setForm(this); } } /** * A form filed. virtual. */ function ValidationField() { this._name = null; this._depends = []; this._displayName = null; this._onFail = null; this._form = null; this.getName = function() { return this._name; } this.setName = function(p0) { this._name = p0; } this.getDepends = function() { return this._depends; } this.setDepends = function(p0) { this._depends = p0; } this.getDisplayName = function() { return this._displayName; } this.setDisplayName = function(p0) { this._displayName = p0; } this.getOnFail = function() { return this._onFail; } this.setOnFail = function(p0) { this._onFail = p0; } this.getForm = function() { return this._form; } this.setForm = function(p0) { this._form = p0; } this.addDepend = function(p0) { this._depends[this._depends.length] = p0; } } ///Factory methods for create Field function FieldFactory() {} FieldFactory.getFieldFromDOM = function(dom) { var field = new ValidationField(); field.setName(dom.getAttribute("name")); field.setDisplayName(dom.getAttribute("display-name")); field.setOnFail(dom.getAttribute("onfail")); if (dom.hasChildNodes()) { var depends = dom.childNodes; for (var i = 0; i < depends.length; i++) { var item = depends.item(i); if (typeof(item.tagName) == 'undefined' || item.tagName != 'depend') { continue; } var dp = new ValidationDepend(); dp.setName(item.getAttribute("name")); dp.addParam(item.getAttribute("param0")); dp.addParam(item.getAttribute("param1")); dp.addParam(item.getAttribute("param2")); dp.addParam(item.getAttribute("param3")); dp.addParam(item.getAttribute("param4")); field.addDepend(dp); } } return field; } function FormFieldUtils() {} FormFieldUtils.findField = function(formName, fieldName) { var formArr = ValidationFramework.getAllForms(); var theForm = null; for (var i = 0; i < formArr.length; i++) { if (formArr[i].getName() == formName) { theForm = formArr[i]; } } if (theForm != null) { return theForm.findField(fieldName); } else { return null; } } /** * A validaton depend. */ function ValidationDepend() { this._name = null; this._params = []; this.getName = function() { return this._name; } this.setName = function(p0) { this._name = p0; } this.getParams = function() { return this._params; } this.setParams = function(p0) { this.params = p0; } this.addParam = function(p0) { this._params[this._params.length] = p0; } } function ValidateMethodFactory() {} ValidateMethodFactory._methods = []; ValidateMethodFactory.validateRequired = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (typeof(obj.type) == "undefined") { var tmp = 0; for (var i = 0; i < obj.length; i++) { if (obj[i].checked) { return true; } } return false; } if (obj.type == "checkbox" || obj.type == "radio") { return (obj.checked); } else { return !(obj.value == ""); } } ValidateMethodFactory.validateInteger = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^-?\\d+$"); return exp.test(obj.value); } ValidateMethodFactory.validateDouble = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^-?\\d+\.\\d+$"); return exp.test(obj.value); } ValidateMethodFactory.validateCommonChar = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^[A-Za-z0-9_]*$"); return exp.test(obj.value); } ValidateMethodFactory.validateChineseChar = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^[\u4E00-\u9FA5\uF900-\uFA2D]*$"); return exp.test(obj.value); } ValidateMethodFactory.validateMinLength = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var v = ValidationFramework.getIntegerValue(params[0]); return (obj.value.length >= v); } ValidateMethodFactory.validateMaxLength = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var v = ValidationFramework.getIntegerValue(params[0]); return (obj.value.length <= v); } ValidateMethodFactory.validateEmail = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; return ValidateMethodFactory.__checkEmail(obj.value); } ValidateMethodFactory.validateDate = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var value = obj.value; var datePattern = params[0]; var MONTH = "mm"; var DAY = "dd"; var YEAR = "yyyy"; var orderMonth = datePattern.indexOf(MONTH); var orderDay = datePattern.indexOf(DAY); var orderYear = datePattern.indexOf(YEAR); var bValid = true; var dateRegexp = null; if ((orderDay < orderYear && orderDay > orderMonth)) { var iDelim1 = orderMonth + MONTH.length; var iDelim2 = orderDay + DAY.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderDay && iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$"); } else if (iDelim1 == orderDay) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$"); } else if (iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$"); } else { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[2], matched[1], matched[3])) { bValid = false; } } else { bValid = false; } } else if ((orderMonth < orderYear && orderMonth > orderDay)) { var iDelim1 = orderDay + DAY.length; var iDelim2 = orderMonth + MONTH.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderMonth && iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$"); } else if (iDelim1 == orderMonth) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$"); } else if (iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$"); } else { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[1], matched[2], matched[3])) { bValid = false; } } else { bValid = false; } } else if ((orderMonth > orderYear && orderMonth < orderDay)) { var iDelim1 = orderYear + YEAR.length; var iDelim2 = orderMonth + MONTH.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderMonth && iDelim2 == orderDay) { dateRegexp = new RegExp("^(\\d{4})(\\d{2})(\\d{2})$"); } else if (iDelim1 == orderMonth) { dateRegexp = new RegExp("^(\\d{4})(\\d{2})[" + delim2 + "](\\d{2})$"); } else if (iDelim2 == orderDay) { dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})(\\d{2})$"); } else { dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{2})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[3], matched[2], matched[1])) { bValid = false; } } else { bValid = false; } } else { bValid = false; } return bValid; } ValidateMethodFactory.validateTime = function(field, params) { ////NOT IMPLEMENT YET SINCE IT'S NOT USEFUL. return true; } ValidateMethodFactory.validateMask = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp(params[0]); //FIXME: this method may be buggy, need more test. return exp.test(obj.value); } ValidateMethodFactory.validateIntegerRange = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var p0 = ValidationFramework.getIntegerValue(params[0]); var p1 = ValidationFramework.getIntegerValue(params[1]); if (ValidateMethodFactory.validateInteger(field)) { var v = parseInt(obj.value); return (v >= p0 && v <= p1); } else { return false; } return true; } ValidateMethodFactory.validateDoubleRange = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var p0 = ValidationFramework.getFloatValue(params[0]); var p1 = ValidationFramework.getFloatValue(params[1]); if (ValidateMethodFactory.validateInteger(field) || ValidateMethodFactory.validateDouble(field)) { var v = parseFloat(obj.value); return (v >= p0 && v <= p1); } else { return false; } return true; } ValidateMethodFactory.validateEqualsField = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var formObj = document.getElementById(ValidationFramework._currentForm.getId()); var eqField = formObj[params[0]]; if (eqField != null) { return (obj.value == eqField.value) } else { return false; } } ValidateMethodFactory.__isValidDate = function(day, month, year) { if (month < 1 || month > 12) return false; if (day < 1 || day > 31) return false; if ((month == 4 || month == 6 || month == 9 || month == 11) &&(day == 31)) return false; if (month == 2) { var leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day>29 || (day == 29 && !leap)) return false; } return true; } /** * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com), * http://javascript.internet.com */ ValidateMethodFactory.__checkEmail = function(emailStr) { if (emailStr.length == 0) { return true; } var emailPat=/^(.+)@(.+)$/; var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"; var validChars="\[^\\s" + specialChars + "\]"; var quotedUser="(\"[^\"]*\")"; var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/; var atom=validChars + '+'; var word="(" + atom + "|" + quotedUser + ")"; var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$"); var matchArray=emailStr.match(emailPat); if (matchArray == null) { return false; } var user=matchArray[1]; var domain=matchArray[2]; if (user.match(userPat) == null) { return false; } var IPArray = domain.match(ipDomainPat); if (IPArray != null) { for (var i = 1; i <= 4; i++) { if (IPArray[i] > 255) { return false; } } return true; } var domainArray=domain.match(domainPat); if (domainArray == null) { return false; } var atomPat=new RegExp(atom,"g"); var domArr=domain.match(atomPat); var len=domArr.length; if ((domArr[domArr.length-1].length < 2) || (domArr[domArr.length-1].length > 3)) { return false; } if (len < 2) { return false; } return true; } ////Language Definitions var ValidationErrorString = new Object(); ////Simplified Chinese(zh-ch) ValidationErrorString["zh-cn"] = new Object(); ValidationErrorString["zh-cn"]["default"]="域{0}校验失败。"; ValidationErrorString["zh-cn"]["required"]="{0}不能为空。<br/>"; ValidationErrorString["zh-cn"]["integer"]="{0}必须是一个整数。"; ValidationErrorString["zh-cn"]["double"]="{0}必须是一个浮点数(带小数点)。"; ValidationErrorString["zh-cn"]["commonchar"] = "{0}必须是普通英文字符:字母,数字和下划线。<br/>"; ValidationErrorString["zh-cn"]["chinesechar"] = "{0}必须是中文字符。"; ValidationErrorString["zh-cn"]["minlength"]="{0}长度不能小于{1}个字符。"; ValidationErrorString["zh-cn"]["maxlength"]="{0}长度不能大于{1}个字符。" ; ValidationErrorString["zh-cn"]["invalid"]="{0}无效。"; ValidationErrorString["zh-cn"]["date"]="{0}不是一个有效日期,期待格式:{1}。"; ValidationErrorString["zh-cn"]["integerrange"]="{0}必须在整数{1}和{2}之间。"; ValidationErrorString["zh-cn"]["doublerange"]="{0}必须在浮点数{1}和{2}之间。"; ValidationErrorString["zh-cn"]["pid"]="{0}不是一个有效身份证号。"; ValidationErrorString["zh-cn"]["email"]="{0}不是一个有效的Email。"; ValidationErrorString["zh-cn"]["equalsfield"]="{0}必须和{1}一致。"; ////English(en-us) ValidationErrorString["en-us"] = new Object(); ValidationErrorString["en-us"]["default"]="Failed when validating filed {0}."; ValidationErrorString["en-us"]["required"]="{0} is required."; ValidationErrorString["en-us"]["integer"]="{0} must be a integer."; ValidationErrorString["en-us"]["double"]="{0} must be a double value. "; ValidationErrorString["en-us"]["commonchar"] = "{0} should be common ascii characters, A-Z,a-z and undercore. "; ValidationErrorString["en-us"]["chinesechar"] = "{0} must be chinese characters. "; ValidationErrorString["en-us"]["minlength"]="{0} cannot be less then {1}. "; ValidationErrorString["en-us"]["maxlength"]="{0} cannot be more then {1}. "; ValidationErrorString["en-us"]["invalid"]="{0} in invalid. "; ValidationErrorString["en-us"]["date"]="{0} is not an invalid date format: {1}. "; ValidationErrorString["en-us"]["integerrange"]="{0} should be between number {1} and {2}. "; ValidationErrorString["en-us"]["doublerange"]="{0} should be between double {1} and {2}. "; ValidationErrorString["en-us"]["pid"]="{0} is not an valid pid. "; ValidationErrorString["en-us"]["email"]="{0} is not an valid email address. "; ValidationErrorString["en-us"]["equalsfield"]="{0} should be agree with field {1}. "; // preload the validation file. //ValidationFramework.getDocumentElement();` 4xml代码 ``` <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE validation-config SYSTEM "validation-config.dtd"> <validation-config lang="auto"> <form id="form1" show-error="alert" show-type="all"> <field name="name" display-name="姓名" onfail=""> <depend name="required" /> <depend name="commonChar" /> <depend name="minLength" param0="3" /> <depend name="maxLength" param0="20" /> </field> <field name="email" display-name="email邮箱"> <depend name="required" /> <depend name="email" /> </field> <field name="age" display-name="年龄"> <depend name="required" /> </field> <field name="protime" display-name="编程时间"> <depend name="required" /> </field> <field name="os" display-name="使用的操作系统"> <depend name="required" /> </field> <field name="lang" display-name="使用的编程语言"> <depend name="required" /> </field> <field name="editor1" display-name="建议"> <depend name="required" /> </field> </form> </validation-config> ``` 5jsp代码 ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <script type='text/javascript' src='ckeditor/ckeditor.js'></script> <script type='text/javascript' src='/js/validation-framework.js'></script> <body> <h1>潜在用户网络调查</h1> <form action='LoginServlet' name='form1' id='form1' method='post' onSubmit="return doValidate(this)"> 姓名:<input type='text' name='name' value='' /><br/> EMAIL:<input type='text' name='email' value=''/><br/> 年纪:<input type='radio' name='age' value='小于18' />小于18 <input type='radio' name='age' value='18-25'/>18-25 <input type='radio' name='age' value='26-40'/>26-40 <input type='radio' name='age' value='大于40'/>大于40<br/> 编程时间:<select name='protime'> <option value='6-12月' >6-12月</option> <option value='12-24月'>12-24月</option> <option value='24月以上'>24月以上</option> </select><br/> 使用操作系统:<select name='os' multiple='multiple' size='6'> <option value='Win XP'>Win XP</option> <option value='Win 2000/2003'>Win 2000/2003</option> <option value='Linux'>Linux</option> <option value='FreeBSD'>FreeBSD</option> <option value='Mac OS'>Mac OS</option> <option value='Other'>Other</option> </select><br/> 使用的编程语言:<input type='checkbox' name='lang' value='C'/>C <input type='checkbox' name='lang' value='C++'/>C++ <input type='checkbox' name='lang' value='C#'/>C# <input type='checkbox' name='lang' value='PYTHON'/>PYTHON <input type='checkbox' name='lang' value='JAVA'/>JAVA <input type='checkbox' name='lang' value='VB'/>VB <input type='checkbox' name='lang' value='DEPHI'/>DEPHI<br/> 建议:<textarea class='ckeditor' cols='50' id='editor1' name='editor1' rows='10'></textarea><br/> <input type='submit' value='提交'> <input type='reset' value='重置'> <input type='hidden' name='ring' value='normal'><br/> <% HttpSession hs=request.getSession(true); hs.setAttribute("write", "yes"); %> </form> </body> </html> ```
Struts2.16 form表单提交中文为空值 很纠结啊
jsp form表单代码如下。 [quote] <div class="pannelbody"> <div class="pannellist"> <form id="useradd" name="useradd" action="UserInseAction" method="post"> <label for="username">名称:</label> <input name="username" type="text" id="username" value="" size="30" class="colorblue" onFocus="this.className='colorfocus';" onBlur="this.className='colorblue';" /> <br /> <label for="nickname">昵称:</label> <input name="nickname" type="text" id="nickname" value="" size="30" class="colorblue" onFocus="this.className='colorfocus';" onBlur="this.className='colorblue';" /> <br /> <label for="password">密码:</label> <input name="password" type="password" id="password" value="" size="30" class="colorblue" onFocus="this.className='colorfocus';" onBlur="this.className='colorblue';" /> <br /> <label for="sex">性别:</label> <select name="sex" id="sex" class="colorblue"> <option value="0">女</option><option value="1">男</option><option value="9">人妖</option> </select> <br /> <label for="birthday">生日:</label> <input name="birthday" type="text" id="birthday" value="" size="30" class="colorblue Wdate" onFocus="this.className='colorfocus';WdatePicker({startDate:'1985-07-01'});" onBlur="this.className='colorblue';" /> <br /> <label for="remark">备注:</label> <textarea name="remark" cols="50" rows="6" id="remark" class="colorblue" onFocus="this.className='colorfocus';" onBlur="this.className='colorblue';" style="width:80%;"></textarea> <br /> <!---字段较多,省略一些个---> <label for=""></label> <input name="status" type="hidden" value="1" /> <input name="button" type="submit" class="sbutton" id="button" value="提交"/> &nbsp; <input name="button2" type="reset" class="sbutton" id="button2" value="返回" /> </form> </div> [/quote] Struts.xml的配置 [quote] <?xml version="1.0" encoding="gbk" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" namespace="/" extends="struts-default"> <action name="*"> <result>/WEB-INF/jsp/{1}.jsp</result> </action> <action name="UserInseAction" class="com.lcsz.classmates.action.UserInfoAction"> <!-- result name="success" type="redirect">login</result--> <result name="success" type="redirect">login</result> <result name="input" type="redirect">UserIns</result> </action> </package> </struts> [/quote] UserInfoAction.java 代码 [quote] package com.lcsz.classmates.action; import com.lcsz.classmates.dao.UserDao; import com.lcsz.classmates.dao.impl.UserDaoImpl; import com.lcsz.classmates.pojo.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class UserInfoAction extends ActionSupport implements ModelDriven<User> { /** * long */ private static final long serialVersionUID = 1L; public User user = new User(); public String execute(){ UserDao userdao = new UserDaoImpl(); try { if (userdao.UserIns(user)) { return SUCCESS; } else { return INPUT; } } catch (Exception e) { System.out.println("发现错误:"+e.getMessage()); return INPUT ; } } public User getModel() { return user; } } [/quote] 在数据库中的插入记录 中文的话就是null 英文和数字可以插入进行 [b]问题补充:[/b] [b]在Action中的值 如果是中文就是 null 如果不是中文就是就正常 :cry: [/b] [b]问题补充:[/b] [color=red]很郁闷的, 由于刚学Struts2 很多问题不知道是在哪产生的。 Struts.properties 中的设置如下 struts.enable.DynamicMethodInvocation = true struts.devMode = true struts.configuration.xml.reload =true struts.i18n.encoding =GBK struts.locale =zh_CN 在jsp页面中也设置 GBK [/color] 页面上的设置 和 XML上的设置 都是GBK了。 数据库也是GBK [b]问题补充:[/b] [color=blue] if (userdao.UserIns([color=violet]user[/color])) { return SUCCESS; } else { return INPUT; } [/color] 中文就为null 英文和数字就有值 [b]问题补充:[/b] - - - - - - - - - - - - - [color=darkred]问题其实已经决绝了。但是我觉得决绝的不够理想[/color] [list] [*]1.我在程序中加了个encoding Filter [/list] 数据库 jsp页面 Struts.xml都设置了gbk 为什么还要写Filter呢。。 [color=red][b]大家回答下这个问题吧[/b][/color] - - - - - - - - - - - - - [b]问题补充:[/b] 其实页面不一定要用s标签的 <s:textfield name="username"/> 用一般的 form input 一样可以等到的
如何在一个JSP页面完成用户名和密码的验证?在JSP使用Java代码片的方法
JAVA+JSP的作业题目: Login.jsp页面: 用表单输入用户名和口令,如果正确(假设正确的用户名是sky, 正确的口令是ocean,),进入select.jsp, 如果错误,提示用户名或口令错误; 效果是当用户输入账号密码点击提交之后在当前的JSP页面实现验证,如果正确就跳转到指定的页面,错误则给出错误信息要求重新输入 ``` <%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %> <!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> </head> <body> <form id="form1" name="form1" method="post" action=""> <p> <label>用户名: <input type="text" name="User" id="textfield" /> </label> </p> <p> <label>密码: <input type="password" name="Password" id="textfield2" /> </label> </p> <p> <label> <input type="submit" name="button" id="button" value="提交" /> </label> <label> <input type="reset" name="button2" id="button2" value="重置" /> </label> </p> </form> <% String name=request.getParameter("name"); String pw=request.getParameter("password"); if(name.equals("sky")&&pw.equals("ocean")) { session.setAttribute("name", name); request.getRequestDispatcher("Select.jsp").forward(request, response); } else{ out.write("用户名或密码错误!"); out.println("<br><a href= Login.jsp>返回登录"); } %> </body> </html> ```
JSp页面传值和Ext JS表单自动填充
有一个JSP文件:Center_right.jsp [code="java"]<body> <table border ="1"> <tr> <td>题目编号</td> <td>题目内容</td> <td>题目类型</td> <td>选项个数</td> <td>选 项</td> <td>题目备注</td> <td>操作</td> </tr> <% while (it.hasNext()) { Questions q=(Questions)it.next(); %> <tr> <td><%= q.getQ_id()%></td> <td><%= q.getQ_head()%></td> <td><%= q.getQ_type().getQt_des()%></td> <td><%= q.getQ_number()%></td> <td><%= q.getQ_body()%></td> <td><%= q.getQ_remarks()%></td> <td><a href ="DesignQuestions/UpdateQuestion.jsp?q_id=<%=q.getQ_id()%>">修改 </a></td> <td><a href ="servlet/DeleteQueByIdServlet?q_id=<%=q.getQ_id()%>">删除</a></td> </tr> <% } list.clear(); %> <tr align="center"> <td colspan ="6"> <a href ="DesignQuestions/Center_right.jsp?page=1"> 首页</a>|| <a href ="DesignQuestions/Center_right.jsp?page=<%=mypage-1%>"> 上一页 </a>|| <a href ="DesignQuestions/Center_right.jsp?page=<%=mypage+1%>"> 下一页 </a>|| <a href ="DesignQuestions/Center_right.jsp?page=<%=totalpage%>"> 末页 </a> </td> </tr> </table >[/code] 修改命令跳转到UpdateQuestion.jsp [code="java"]<script type="text/javascript" src="JS/ext-lang-zh_CN.js"></script> <script type="text/javascript"> Ext.require([ '*' ]); Ext.onReady(function() {//onReady()函数在页面注册多个函数,依次执行 Ext.QuickTips.init(); Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider')); Ext.state.Manager.setProvider(Ext .create('Ext.state.CookieProvider')); //表单组合控件 var form = new Ext.form.FormPanel({ labelAlign : 'right', autoScroll : true, labelWidth : 50, width : 600, // title: 'form', frame : true, //reader:reader, //standardSubmit:true, //url:'servlet/AddQueServlet', items : [ { layout : 'form', items : [ { //columnWidth:.7, xtype : 'fieldset', layout : 'form', checkboxToggle : true,//折叠fieldset title : '文字输入', autoHeight : true, defaults : { width : 400 }, defaultType : 'textfield', items : [ { fieldLabel : '题目', name : 'head', allowBlank : false }, { xtype : 'htmleditor', fieldLabel : '题目备注及说明', id : 'editor', anchor : '98%', name : 'remarks', fontFamilies: ["宋体", "隶书", "黑体","Times New Roman"] }, { xtype : 'hidden', name : 'hidden' } ] }, { //columnWidth:.3, xtype : 'fieldset', checkboxToggle : true, title : '数据验证', autoHeight : true, defaultType : 'checkbox', hideLabels : true, layout : 'column', name:'checkValue', //style: 'margin-left:10px;', //bodyStyle: 'margin-left:20px;', items : [ { boxLabel : '必填', columnWidth : .125, name : 'check', inputValue : '1', checked : true, width : 'auto' }, { boxLabel : '手机号码', columnWidth : .125, name : 'check', inputValue : '2', //checked: true, width : 'auto' }, { boxLabel : '邮编', columnWidth : .125, name : 'check', inputValue : '3', width : 'auto' }, { boxLabel : '身份证号', columnWidth : .125, name : 'check', inputValue : '4', width : 'auto' }, { boxLabel : '日期', columnWidth : .125, name : 'check', inputValue : '5', width : 'auto' }, { boxLabel : 'Email', columnWidth : .125, name : 'check', inputValue : '6', width : 'auto' }, { boxLabel : '必答题', columnWidth : .25, name : 'check', inputValue : '7', width : 'auto' } ] }, { xtype : 'fieldset', checkboxToggle : true, title : '选项(每行一个)', autoHeight : true, defaultType : 'textarea', hideLabels : true, layout:'form', //style: 'margin-left:10px;', //bodyStyle: 'margin-left:20px;', items : [ { xtype:'textfield', fieldLabel : '输入选项个数', name : 'number' },{ width : 400, grow : true, name : 'options', //allowBlank : false, emptyText : '输入选项', maxLength : 10, minLength : 2 } ] }, { xtype : 'fieldset', //checkboxToggle:true, title : '选项排列', autoHeight : true, defaultType : 'radio', hideLabels : true, layout : 'column', //style: 'margin-left:10px;', //bodyStyle: 'margin-left:20px;', items : [ { boxLabel : '横向', name : 'rank', inputValue : '1', //checked: true, width : 'auto' }, { boxLabel : '竖向', name : 'rank', inputValue : '2', checked : true, width : 'auto' } ] } ] } ], buttons: [{ text: '保存', handler: function(){ //此处可以用myFormPanel.getForm()和myFormPanel.form两种方法获得表单对象. form.getForm().submit({//提交表单数据 url: 'servlet/AddQueServlet',//处理页面,注意返回内容格式的正确性 method: 'post', success: function(form, action) {//保存成功 Ext.Msg.alert('保存成功', action.result.msg); }, failure: function(form, action) {//保存失败 Ext.Msg.alert('保存失败', action.result.msg); } }) ; } },{ text: '重置', handler: function(){ form.form.reset() ;//重置表单 } }] }); form.getForm().load({ url: 'DesignQuestions/ShowQueByIdJson.jsp', params: { id: 'load' }, failure: function(form, action) { Ext.Msg.alert("Load failed", action.result.errorMessage); }, success:function(form, action) { Ext.Msg.alert("Load success", action.result.errorMessage); } }); var viewport = Ext.create('Ext.Viewport', { id : 'Center_left', layout : 'fit', autoScroll : true, items : [form] }); form.render("form"); }); </script> </head> <body> <% String qID=request.getParameter("q_id"); session.setAttribute("q_id", qID); //System.out.print(qID); %>[/code] 这个表单我想要自动填充,从ShowQueByIdJson.jsp获取值: [code="java"]<% int q_id = Integer.parseInt((String)session.getAttribute("q_id"));// 获得页面传递的参数 Questions q = new Questions(); QuestionsDao questionDao = new QuestionsDaoImpl(); q = questionDao.findQuestionsById(q_id);// 调用实现类中根据id查询的方法 %> <% String id = request.getParameter("id") ; if(id!=null &&"load".equals(id)){ %> { success: true, data: { head: "${q.q_head }", remarks: "${q.q_remarks }", number:"${q.q_number }", options: ${q.q_body }" } } <% }else{ %> { success: false, msg: "数据载入错误" } <% } %> [/code] 问题来啦!session范围是一个会话,这个q_id传不到ShowQueByIdJson.jsp,所以查不到数据写进JSON字符串,怎样才能达到:点击修改,跳转到表单的页面能够把应该的信息都填充的效果?
jsp链接Mysql数据库,代码问题、求指导
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>登录</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="login_check.jsp" method="post"> <h2>用户登陆</h2> 登陆 ID:<input type="text" name="userid"><br> 登陆密码:<input type="password" name="password"><br> <input type="submit" value = "登陆"> <input type="reset" value = "重置"> </body> </html> <%! public static final String DBDRIVER = "com.mysql.jdbc.Driver" ; public static final String userName = "root"; //登录的用户名 public static final String userPasswd = "root"; //登录mysql密码 public static final String dbName = "test"; //数据库名 public static final String tableName="form1"; //表名 public static final String DBURL = "jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd; %> <% Connection conn = null ; PreparedStatement pstmt = null ; ResultSet rs = null ; boolean flag = false ; // 表示登陆成功或失败的标记 %> <% String userid = request.getParameter("username") ; // 接收表单参数 String password = request.getParameter("password") ; // 接收表单参数 try{ Class.forName(DBDRIVER) ; conn = DriverManager.getConnection(DBURL) ; String sql = "SELECT userid,password FROM tuser WHERE userid=? AND password=?" ; pstmt = conn.prepareStatement(sql) ; pstmt.setString(1,userid) ; pstmt.setString(2,password) ; rs = pstmt.executeQuery() ; while(rs.next()){ // 如果有内容,则此处执行,表示查询出来,合法用户 flag = true ; } }catch(Exception e){ }finally{ try{ conn.close() ; // 连接一关闭,所有的操作都将关闭 }catch(Exception e){} } %> <% if(flag){ // 登陆成功,应该跳转到success.jsp %> <jsp:forward page="login_success.jsp"/> <% }else{ // 登陆失败,跳转到failure.jsp %> <jsp:forward page="login_failure.jsp"/> <% } %> </body> </html>
Java WEB 连接数据库的登录界面失败?
使用Eclipse做登陆界面,连接MySQL 8.0,测试过连接数据库应该是成功的,可能是struts配置有问题,新手不知道问题出在哪里,请帮忙看一下代码,我标注几个我可能出问题又不知道怎么改的地方 //login.jsp //此处可能是表单中form的action属性有问题? ``` <%@ page contentType="text/html; charset=gb2312" language="java"%> <html> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <head> <title>图书馆管理系统</title> <link href="CSS/style.css" rel="stylesheet"> <script language="javascript"> function check(form){ if (form.name.value==""){ alert("请输入用户名称");form.name.focus();return false; } if (form.pwd.value==""){ alert("请输入密码");form.pwd.focus();return false; } } </script> </head> <body> <table width="1000" border="0" align="center" cellpadding="0" cellspacing="0" class="tableBorder"> <tr> <td width="1000" height="545" align="center" background="Images/login.png"> <table width="1000" height="345" aligh="center" ></table> <form name="form1" method="post" action="manager.do?action=login"> <table width="400" height="200" align="left"> <tr> <td height="37" style="width: 128px; "></td> <td height="37" width="50"> 用户名</td> <td height="37" width="150"> <input name="name" type="text" class="logininput" id="name" size="27"> </td> </tr> <tr> <td height="37" style="width: 128px; "></td> <td height="37" width="50"> 密码 </td> <td height="37" width="150"> <input name="pwd" type="text" class="logininput" id="pwd" size="27"> </td> </tr> <tr> <td height="37" style="width: 128px; "></td> <td height="37" width="50"></td> <td height="37" width="200"> <input name="Submit" type="submit" class="btn_grey" value="确定" onClick="return check(form1)"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name="Submit3" type="reset" class="btn_grey" value="重置"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name="Submit2" type="button" class="btn_grey" value="关闭" onClick="window.close();"> </td> </tr> </table> </form> </td> <tr> <td align="center" height="50" bgcolor="#3A3A3A" class="word_login">CopyRight &copy; 2019版权所有 xx图书馆<br> </td> </tr> </table> </body> </html> ``` //Manager.java ``` package com.action; import org.apache.struts.action.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.actionForm.ManagerForm; import com.dao.ManagerDAO; import javax.servlet.http.HttpSession; public class Manager extends Action { private ManagerDAO managerDAO = null; public Manager() { this.managerDAO = new ManagerDAO(); } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String action = request.getParameter("action"); // System.out.println("获取的查询字符串:" + action); if (action == null || "".equals(action)) { return mapping.findForward("error"); } else if ("login".equals(action)) { return managerLogin(mapping, form, request, response); } request.setAttribute("error", "操作失败!"); return mapping.findForward("error"); } // 管理员身份验证 public ActionForward managerLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ManagerForm managerForm = (ManagerForm) form; //将接收到的表单信息强制转换成ActionForm类型 managerForm.setAd_name(managerForm.getAd_name()); managerForm.setAd_pwd(managerForm.getAd_pwd()); int ret = managerDAO.checkManager(managerForm); System.out.print("验证结果ret的值:" + ret); if (ret == 1) { //将登录到系统的管理员名称保存到session HttpSession session = request.getSession(); session.setAttribute("manager", managerForm.getAd_name()); return mapping.findForward("managerLoginok"); } else { request.setAttribute("error", "您输入的管理员名称或密码错误!"); return mapping.findForward("error"); } } } ``` //ManagerForm ``` package com.actionForm; import org.apache.struts.action.ActionForm; public class ManagerForm extends ActionForm { private int ad_id; private String ad_name; private String ad_pwd; public ManagerForm() { } public int getAd_id() { return ad_id; } public void setAd_id(int ad_id) { this.ad_id=ad_id; } public String getAd_name() { return ad_name; } public void setAd_name(String ad_name) { this.ad_name=ad_name; } public String getAd_pwd() { return ad_pwd; } public void setAd_pwd(String ad_pwd) { this.ad_pwd=ad_pwd; } } ``` //ManagerDAO ``` package com.dao; import com.core.ChStr; import com.core.ConnDB; import java.util.*; import com.actionForm.ManagerForm; import java.sql.*; public class ManagerDAO { private ConnDB conn = new ConnDB(); //管理员身份验证 public int checkManager(ManagerForm managerForm) { int flag = 0; ChStr chStr=new ChStr(); String sql = "SELECT * FROM Ad_info where ad_name='" + chStr.filterStr(managerForm.getAd_name()) + "'"; ResultSet rs = conn.executeQuery(sql); try { if (rs.next()) { String pwd = chStr.filterStr(managerForm.getAd_pwd()); //获取输入的密码并过滤输入字符串中的危险字符 if (pwd.equals(rs.getString(3))) { flag = 1; } else { flag = 0; } }else{ flag = 0; } } catch (SQLException ex) { flag = 0; }finally{ conn.close(); } return flag; } } ``` //ConnDB ``` package com.core; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class ConnDB { public Connection conn=null; public Statement stmt=null; public ResultSet rs=null; private static String propFileName="/com/connDB.properties"; private static Properties prop=new Properties(); private static String dbClassName="com.mysql.cj.jdbc.Driver"; private static String dbUrl="jdbc:mysql://223.80.110.29:3306/sys_test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL"; private static String dbUserName="root"; private static String dbPassword=""; //加载资源文件 public ConnDB() { try { InputStream in=getClass().getResourceAsStream(propFileName); prop.load(in); dbClassName=prop.getProperty("DB_CLASS_NAME","com.mysql.cj.jdbc.Driver"); dbUrl=prop.getProperty("DB_URL","jdbc:mysql://localhost:3306/db_librarysys?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL"); dbUserName=prop.getProperty("DB_USERNAME"); dbPassword=prop.getProperty("DB_PASSWORD"); } catch(Exception e){ e.printStackTrace(); } } public static Connection getConnection() { Connection conn=null; try { //加载数据库驱动 Class.forName(dbClassName); conn=DriverManager.getConnection(dbUrl,dbUserName,dbPassword); } catch(Exception ee) { ee.printStackTrace(); } if(conn==null) { System.err.println("警告:DbConnectionManager.getConnection()获得数据库链接失败.\r\n\r\n链接类型:"+dbClassName+"\r\n链接位置:"+dbUrl); } return conn; } //执行查询语句 public ResultSet executeQuery(String sql) { try { conn=getConnection(); stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); /*ResultSet.CONCUR_READ_ONLY 不能用结果集更新数据库中的表 ResultSet.TYPE_SCROLL_INSENSITIVE 结果集的游标可以上下移动,当数据库变化时,当前结果集不变。 */ rs=stmt.executeQuery(sql); } catch(SQLException ex){ System.err.println(ex.getMessage()); } return rs; } //执行更新操作 添加修改删除数据 public int executeUpdate(String sql) { int result=0;//更新的行数 try { conn=getConnection(); stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); result=stmt.executeUpdate(sql); }catch(SQLException ex) { result=0; } return result; } public void close() { try { if(rs!=null) { rs.close(); } if(stmt!=null) { stmt.close(); } if(conn!=null) { conn.close(); } }catch(Exception e) { e.printStackTrace(System.err); } } } ``` //struts-config ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <form-beans> <form-bean name="managerForm" type="com.actionForm.ManagerForm" /> <form-bean name="ParameterForm" type="com.actionForm.ParameterForm" /> </form-beans> <action-mappings type="org.apache.struts.action.ActionMapping"> <action name="managerForm" path="/manager" scope="request" type="com.action.Manager" validate="true"> <forward name="managerLoginok" path="/main.jsp" /> <forward name="error" path="/error.jsp" /> </action> <action name="ParameterForm" path="/parameter" scope="request" type="com.action.Parameter" validate="true"> <forward name="error" path="/error.jsp" /> <forward name="parametermodify" path="/parameter_ok.jsp?para=2" /> <forward name="parametermodifyQuery" path="/parameter_modify.jsp" /> </action> </action-mappings> <message-resources parameter="com.wgh.struts.ApplicationResources" /> </struts-config> ```
jsp页面传值在spring mvc中的controller中的获取
``` <% Seller seller =(Seller)session.getAttribute("sellerinfo"); %> <form action="<%=basePath%>plmanage/updateSeller.do" method="post"> <input type="hidden" name="id" value="<%=seller.getSlId()%>"> <table> <caption>更新卖家信息</caption> <tr> <td>用户名:</td> <td><%=seller.getSellerName() %></td> </tr> <tr> <td>密码</td> <td><input type="password" name="password" value="<%=seller.getPassword() %>"/></td> </tr> <tr> <td>性别</td> <td> <% if(null==seller.getGender()){ %> <input type="radio" name="gender" value="男">男<input type="radio" name="gender" value="女">女 <% }else if(seller.getGender().equals("男")){ %> <input type="radio" name="gender" value="男" checked="checked">男<input type="radio" name="gender" value="女">女 <% }else{ %> <input type="radio" name="gender" value="男" >男<input type="radio" name="gender" value="女" checked="checked">女 <% }%> </td> </tr> <tr> <td>店铺名</td> <td><input type="text" name="storename" value="<%=seller.getStorename()%>"/></td> </tr> <tr> <td>电话</td> <td><input type="text" name="telephone" value="<%=seller.getTelephone()%>"/></td> </tr> <tr> <td>Email</td> <td><input type="text" name="email" value="<%=seller.getEmail()%>"/></td> </tr> <tr> <td>店铺书的数量</td> <td><input type="text" name="bookamount" /></td> </tr> </table> <input type='submit' value='提交'> <input type="reset" value="重置"> </form> </body> ``` 我先说明一下我的目的,在更新用户界面将信息传到controller中调用service更新至数据库,但是controller中获取不到实体Seller。 简单的注册页面就可以将Seller绑定到controller中,为什么这边加了一个数据的获取就不行了。这里的seller数据获取至已有的表单数据。 我做的就是将表单中的数据支持更新修改操作,跳转到如上的代码进行信息输入,再跳转到controller中进行service存储数据
form表单中提交servlet接受不到,但是在地址栏中点击enter却可以,帮忙看看
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <pre name="code" class="html">&lt;form action="upload.action" enctype="multipart/form-data" method="post"&gt; &lt;table&gt; &lt;tr&gt;&lt;td&gt;产品名称&lt;s:textfield name="product_name" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;产品介绍&lt;s:textarea name="product_intro" /&gt;&lt;/td&gt; &lt;/tr&gt;&lt;td&gt;产品类型&lt;s:select list="#types" listKey="type_id" listValue="type_name" name="product_type_id"&gt;&lt;/s:select&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;APK&lt;s:file name="product_apk"&gt;&lt;/s:file&gt; &lt;/td&gt; &lt;/table&gt; &lt;input type="submit" value="提交" /&gt; &lt;input type="reset" value="重置" /&gt; &lt;/form&gt;</pre> <p> </p> <p> </p> <pre name="code" class="java"> &lt;package name="default" namespace="/" extends="struts-default,json-default"&gt; &lt;action name="upload" class="cn.xuerge.game.web.ProductUploadAction" method="execute"&gt; &lt;/action&gt; &lt;action name="product_*" class="cn.xuerge.game.web.ProductAction" method="{1}"&gt; &lt;!-- 头版信息的result --&gt; &lt;result name="firsttimeline" type="json"&gt; &lt;param name="root"&gt;products&lt;/param&gt; &lt;/result&gt; &lt;result name="addProduct" &gt;/WEB-INF/pages/addProduct.jsp&lt;/result&gt; &lt;/action&gt; &lt;/package&gt;</pre> <p> </p> <p> </p> <p>直接点击提交提示错误“<strong style="line-height: 1.5;">No result defined for action cn.xuerge.game.web.ProductUploadAction and result input</strong><span style="line-height: 1.5;">”</span></p> <p><span style="line-height: 1.5;">但是在地址栏点击enter确可以正常到达</span></p> </div>
我一点onclick为什么总是提交表单
下面是一个表单,有一个onclick按钮,点击后上面文本框的内容被添加到下面的文本域中,并可以一直添加,然后点击submit后提交到另一个页面。但是,在Ie9或者火狐浏览器中我一点onclick为什么总是提交表单,在搜狗,360浏览器中并未出现这样的状况。想问是不是浏览器的兼容问题,该如何解决。 <form action="abc.jsp" method="get" > <input id = "input" size="30" maxlength="100" onMouseOver="this.focus()" onFocus="this.select()" /> <button onclick="document.getElementById('textarea').value+= document.getElementById('input').value+' '" >add</button> </p> <p> <label for="textarea"></label> <textarea name="name" id="textarea" cols="40" rows="5" readonly="true"></textarea> &nbsp;&nbsp;<input type="submit" id="button2" value="submit" /> <input type="reset" id="button" value="reset" /> </p> </form>
我的JSP页面代码,JS有点问题。但是不知道怎样解决。只想图片按钮可以提交表单
<%@ page contentType="text/html; charset=gbk" %> <html> <head> <title>登陆页面</title> <link rel=stylesheet href="css/style.css" type="text/css"> <script language="JavaScript" src="script/trim.js"></script> <script language="JavaScript"> function check(){ var uname = document.all.uname.value; var upwd = document.all.upwd.value; if(uname.trim()==""){ alert("用户名为空,请重新输入!!!"); return; } if(upwd.trim()==""){ alert("密码为空,请重新输入!!!"); return; } document.all.mf.submit(); } </script> </head> <body> <div class="out"> <div class="login_style"> <center> <form action="ManageServlet" method="post" id="mf" target="bottom"> <table> <tr> <td>用户名:</td> <td><input type="text" id="uname" name="uname" value="zrk"/></td> </tr> <tr> <td>密&nbsp;码:</td> <td><input type="password" id="upwd" name="upwd" value="12345"/></td> </tr> <tr> <td colspan="2" align="center"> <img border="0" src="img/ddl.gif" id="lg" onclick="JavaScript:check()" style="cursor:hand" onmouseover="document.all.lg.src='img/ddla.gif'" onmouseout="document.all.lg.src='img/ddl.gif'" onmouseup="document.all.lg.src='img/ddla.gif'" onmousedown="document.all.lg.src='img/ddlb.gif'"/> <img border="0" src="img/cz.gif" id="cz" onclick="JavaScript:document.all.mf.reset()" style="cursor:hand" onmouseover="document.all.cz.src='img/cza.gif'" onmouseout="document.all.cz.src='img/cz.gif'" onmouseup="document.all.cz.src='img/cza.gif'" onmousedown="document.all.cz.src='img/czb.gif'"/></td> </tr> </table> <input type="hidden" name="action" value="login"/> </form> </center> </div> </div> </body> </html>
curl 模拟登录网站,表单数据的填写问题
``` <form name=form1 method=post action="/Control"><input type="hidden" name="id" value="2000"> <table border="0" width="100%" cellspacing="1" cellpadding="0" height="100%" class="f1"> <tr> <td height="177" colspan="2"> <p align="center">  </td> </tr> <tr> <td height="41" width="39%" align="right">用户名 Usename</td> <td height="41" width="60%">&nbsp;<input name="strAccount" id="userId" type="text" maxlength="26" class="input-border" onKeyUp="this.value=new String(this.value).toLowerCase()"></td> </tr> <tr> <td height="36" width="39%" align="right">密 码 Password </td> <td height="36" width="60%">&nbsp;<input name="strPassword" type="password" maxlength="16" class="input-border"></td> </tr> <tr> <td height="40" width="39%" align="center"><a target="_blank" href="http://metcoa.cjlu.edu.cn:8080/service/forget_form.jsp">>>找回密码</a></td> <td height="40" width="60%">&nbsp;<input type="submit" name="0MKKey" value="" class="login-b" onMouseOver="this.className='login-b2'" onMouseDown="this.className='login-b3'" onMouseOut="this.className='login-b'"/>&nbsp;&nbsp; <input type="button" name="" value="" onClick="reset();return false;" class="login-a" onMouseOver="this.className='login-a2'" onMouseDown="this.className='login-a3'" onMouseOut="this.className='login-a'"/></td> </tr> <tr> <td height="61"> <P align="center"> <input type="checkbox" name="union" value="true" onClick="if(this.checked) this.checked=confirm('您已经选择互联网登录,开始计时')"> 互联网登录</P></td> <td height="61"> <a target="_blank" href="http://10.252.0.192/CMClient_Setup_1.4.2.11.zip">中国移动L2TP客户端(点击下载)</a><br> <a target="_blank" href="http://10.252.0.192/shanxunclient.zip">中国电信闪讯客户端(点击下载)</a> </td> </tr> <tr> <td valign="top" colspan="2">  </td> </tr> </table> </form> ``` 这是 登陆界面的form 部分 这是chrome 开发工具查看的提交的表单数据 ![图片说明](https://img-ask.csdn.net/upload/201509/20/1442729107_358896.png) ` 登录不上去,没有提示错误就返回登录界面的html ``` curl -d "id=2000&strAccount=帐号&strPassword=密码&union=true&0MMKey=" ``` 返回的这个 ![图片说明](https://img-ask.csdn.net/upload/201509/27/1443332200_25176.png)
jsp上传文件页面报无法解析的编译问题
index.jsp <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <html> <head> <title>带进度条的文件上传</title> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <link href="CSS/style.css" rel="stylesheet"> <script language="javascript" src="JS/AjaxRequest.js"></script> <script language="javascript"> //此处需要加&nocache="+new Date().getTime(),否则将出现进度不更新的情况 function getProgress(){ var loader=new net.AjaxRequest("showProgress.jsp?nocache="+new Date().getTime(),deal_p,onerror,"GET"); } function onerror(){ alert("上传文件出错!"); } function deal_p(){ var h=this.req.responseText; h=h.replace(/\s/g,""); //去除字符串中的Unicode空白符 document.getElementById("progressPercent").style.display=""; //显示百分比 progressPercent.innerHTML=h+"%"; //显示完成的百分比 document.getElementById("progressBar").style.display="block"; //显示进度条 document.getElementById("imgProgress").width=h*(255/100); //显示完成的进度 } function deal(form){ form.submit(); //提交表单 timer=window.setInterval("getProgress()",500); //每隔500毫秒获取一次上传进度 } </script> </head> <body> <form name="form1" enctype="multipart/form-data" method="post" action="UpLoad?action=uploadFile"> <table width="500" height="289" border="0" align="center" cellpadding="0" cellspacing="0" background="images/bg.jpg"> <tr> <td width="61" rowspan="2">&nbsp;</td> <td width="439" align="center"> <table width="80%" height="190" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center">&nbsp;</td> </tr> <tr> <td height="34" style="color:#FFFFFF">请选择上传的文件:</td> </tr> <tr> <td height="42"><input name="file" type="file" size="42"></td> </tr> <tr> <td height="50" style="color:#FFFFFF"> 注:文件大小请控制在50M以内。</td> </tr> <tr> <td height="29" align="center" style="color:#FFFFFF"><div id="progressBar" class="prog_border" align="left"><img src="images/progressBar.jpg" width="0" height="13" id="imgProgress"></div>  <span id="progressPercent" style="width:40px;display:none">0%</span></td> </tr> <tr> <td height="29" align="center"><img src="images/shangchuan.gif" width="61" height="23" onClick="deal(form1)"> <img src="images/chongzhi.gif" width="61" height="23" onClick="form1.reset();">&nbsp; </td></tr> </table> </td> </tr> </table> </form> </body> </html> upload.java package com.wgh.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * * @author administrator */ public class UpLoad extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if ("uploadFile".equals(action)) { this.uploadFile(request, response); // 上传文件 } } public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=GBK"); request.setCharacterEncoding("GBK"); HttpSession session = request.getSession(); session.setAttribute("progressBar", 0); // 定义指定上传进度的Session变量 String error = ""; int maxSize = 50 * 1024 * 1024; // 单个上传文件大小的上限 DiskFileItemFactory factory = new DiskFileItemFactory(); // 基于磁盘文件项目创建一个工厂对象 ServletFileUpload upload = new ServletFileUpload(factory); // 创建一个新的文件上传对象 try { List items = upload.parseRequest(request);// 解析上传请求 Iterator itr = items.iterator();// 枚举方法 while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // 获取FileItem对象 if (!item.isFormField()) {// 判断是否为文件域 if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件 long upFileSize = item.getSize(); // 上传文件的大小 String fileName = item.getName(); // 获取文件名 // System.out.println("上传文件的大小:" + item.getSize()); if (upFileSize > maxSize) { error = "您上传的文件太大,请选择不超过50M的文件"; break; } // 此时文件暂存在服务器的内存中 File tempFile = new File(fileName);// 构造临时对象 // String savePath=tempFile.getName(); // //返回上传文件在客户端的完整路径名称 // request.setAttribute("filename", savePath); File file = new File(request.getRealPath("/upload"), tempFile.getName()); // 获取根目录对应的真实物理路径 InputStream is = item.getInputStream(); int buffer = 1024; // 定义缓冲区的大小 int length = 0; byte[] b = new byte[buffer]; double percent = 0; FileOutputStream fos = new FileOutputStream(file); while ((length = is.read(b)) != -1) { percent += length / (double) upFileSize * 100D; // 计算上传文件的百分比 fos.write(b, 0, length); // 向文件输出流写读取的数据 session.setAttribute("progressBar", Math .round(percent)); // 将上传百分比保存到Session中 } fos.close(); Thread.sleep(1000); // 线程休眠1秒 } else { error = "没有选择上传文件!"; } } } } catch (Exception e) { e.printStackTrace(); error = "上传文件出现错误:" + e.getMessage(); } if (!"".equals(error)) { request.setAttribute("error", error); request.getRequestDispatcher("error.jsp") .forward(request, response); } else { request.setAttribute("result", "文件上传成功!"); request.getRequestDispatcher("upFile_deal.jsp").forward(request, response); } } } 问题 java.lang.Error: 无法解析的编译问题: 无法解析导入 org.apache.commons.fileupload.disk 无法解析导入 org.apache.commons.fileupload.servlet DiskFileItemFactory 无法解析为类型 DiskFileItemFactory 无法解析为类型 ServletFileUpload 无法解析为类型 ServletFileUpload 无法解析为类型 com.wgh.servlet.UpLoad.<init>(UpLoad.java:15) sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:423) java.lang.Class.newInstance(Class.java:442) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879) org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:610) org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1777) java.lang.Thread.run(Thread.java:745) 求救
multipart/form-data提取不出数据来
``` <form id="resiger" name="resiger" method="post" action="Student.servlet" enctype="multipart/form-data"> <input type="text" name="action" value="doNewStudent">..... <input type="file" name="photo" id="photo" class="wbk"/><span id="photo"> <input type="submit" name="button" id="button" value="添 加" /> <input type="reset" name="button2" id="button2" value="清 除" /> <input type="button" name="button3" id="button3" value="返回首页"/> --没有给表单加上enctype="multipart/form-data"的时候,能够把全部的数据提取出来,如action,只是提取不出文本域的中的文件而已,这是正常的,但是加上enctype="multipart/form-data"之后,却连普通的数据都提取不出来了,让老师看了下代码,他说没什么问题,可能是配置或者哪儿出问题了,但我就是找不出来(我是在servlet中提取的)------- package com.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.commons.db.Pager; import com.commons.util.ActionResult; import com.commons.util.Validator; import com.factory.ServiceFactory; import com.model.Student; import com.service.StudentService; @WebServlet(name="StudentServlet",urlPatterns="/Student.servlet") public class StudentServlet extends HttpServlet { private StudentService studentService=ServiceFactory.getStudentService(); private static final long serialVersionUID = 1L; public StudentServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String action=request.getParameter("action"); System.out.println("动作"+action); if(action==null){ this.doNewStudent(request, response); } else if(action.equals("goPage")){ this.goPage(request, response); }else if(action.equals("goList")){ // this.goList(request, response); this.findAll(request, response); }else if(action.equals("doNewStudent")){ this.doNewStudent(request,response); }else if(action.equals("goUpdate")){ goUpdate(request,response); }else if(action.equals("doUpdate")){ this.doUpdate(request, response); }else if(action.equals("doDelete")){ this.doDelete(request, response); }else if(action.equals("fenYe")){ this.findAll(request, response); } } protected void goPage(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String url=""; url=request.getParameter("url"); response.sendRedirect(url); } protected void goList(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { List<Student> lists=this.studentService.findAllStudent(); request.getSession().setAttribute("lists", lists); response.sendRedirect("adminOperator.jsp"); } protected void doNewStudent(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String name=request.getParameter("name"); System.out.println(name); int age=Integer.parseInt(request.getParameter("age")); String sex=request.getParameter("sex"); String grade=request.getParameter("grade"); String major=request.getParameter("major"); String address=request.getParameter("address"); Part part=request.getPart("photo"); // 获取文件扩展名 System.out.println("长度是:"+part.getSize()); String ext = part.getHeader("content-disposition").substring( part.getHeader("content-disposition").lastIndexOf(".") + 1, part.getHeader("content-disposition").length() - 1);// 获取文件扩展 part.write(this.getServletContext().getRealPath("photo")+"\\"+ext); Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-S"); String stuPhoto=sdf.format(date); // 将文件放入到服务器磁盘 part.write(this.getServletContext().getRealPath("ptoto")+"\\"+stuPhoto); Student student=new Student(name, sex, age, grade, major, address, stuPhoto); boolean flag=this.studentService.addStudent(student); if(flag){ this.goList(request, response); }else{ request.setAttribute("student", student); request.getRequestDispatcher("newStudent.jsp").forward(request, response); } } protected void goUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ String sid=request.getParameter("sid"); Student student=this.studentService.serchStudnet(sid); request.setAttribute("student", student); request.getRequestDispatcher("update.jsp").forward(request, response); } protected void doUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String sid=request.getParameter("sid"); String name=request.getParameter("name"); int age=Integer.parseInt(request.getParameter("age")); String sex=request.getParameter("sex"); String grade=request.getParameter("grade"); String major=request.getParameter("major"); String address=request.getParameter("address"); Part part=request.getPart("photo"); // 获取文件扩展名 String ext=part.getHeader("content-dispoistion").substring( part.getHeader("content-dispoistion").indexOf(".")+1,part.getHeader("content-dispoistion").length()-1); part.write(this.getServletContext().getRealPath("photo")+"\\"+ext); Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-S"); String stuPhoto=sdf.format(date); // 将文件放入到服务器磁盘 part.write(this.getServletContext().getRealPath("ptoto")+"\\"+stuPhoto); Student student=new Student(name, sex, age, grade, major, address, stuPhoto); student.setSid(sid); boolean flag=studentService.updateStudent(student); if(flag){ this.goList(request, response); }else{ request.setAttribute("student", student); request.getRequestDispatcher("update.jsp").forward(request, response); } } protected void doDelete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String sid=request.getParameter("sid"); boolean flag=studentService.deleteStudent(sid); if(flag){ this.goList(request, response); }else{ response.sendRedirect("adminOperator.jsp"); } } protected void findAll(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String pageNoStr=request.getParameter("pageNo"); int pageNo=1; if(!Validator.isEmpty(pageNoStr)){ pageNo=Integer.parseInt(pageNoStr); } long rowCount=studentService.getStusRowCount(); Pager pager=new Pager(rowCount, 3, pageNo); List<Student> stuList=studentService.findAllStudent(pager); request.getSession().setAttribute("lists", stuList); request.getSession().setAttribute("pager", pager); System.out.println(pager.getCurrentPage()); response.sendRedirect("adminOperator.jsp"); // return new ActionResult("adminOperator.jsp",true); } } ```
Jquery Ajax 提交表单 JSP页面局部刷新 javascript 中写的code不执行
下面是我碰到的具体问题,一直很是郁闷!我贴下我的代码,如果解决了,小弟不甚感激。。。 js 代码: [code="js"] //ajax 执行成功的回调函数 function showSuccess(data){ alert('执行成功!!!'); } function showError(){ alert('出错啦!!!'); } //ajax提交采购或者销售项 function addGoodsItems(){ if($("#goodsName").val() == ""){ alert('货品不能为空!'); }else if($("#amount").val() == 0){ alert('数量需多余0'); }else if($("#price").val() == ""){ alert('单价不能为空'); }else{ $(document).ready(function(){ alert('这个方法始终就是没有起作用?????????'); $("#itemsForm").submit(function(){ //ajax 提交参数 var options = { dataType:'json', resetForm:false, success:showSuccess, error:showError, timeout:10000 } //提交表单 $(this).ajaxSubmit(options); // 为了防止普通浏览器进行表单提交和产生页面导航(防止页面刷新?)返回false return false; }); }); alert('方法执行到这儿了!!'); } } [/code] 涉及的页面: [code="html"] <form id="itemsForm" action="addGoodsItems.action" method="post"> <table> <tr> <td> 存货名称: </td> <td> <input type="text" name="goodsItems.goodsName" id="goodsName" class="baseline" value="${pcb.goodsItems.goodsName}" style="width: 150px;" /> <input type="button" value="选择存货" onclick="selectGoods()" /> </td> <td width="40px;"></td> <td> 存货地点: </td> <td> <input type="text" name="goodsItems.stockPlace" id="storage" class="baseline" value="${pcb.goodsItems.stockPlace}" style="width: 150px;" /> <input type="button" value="存货地点" onclick="selectPlace()" /> </td> </tr> <tr> <td> 物品数量: </td> <td> <c:choose> <c:when test="${goodsItems.amount == null}"> <input type="text" name="goodsItems.amount" id="amount" onfocus="onfocusSelect(this)" onblur="jsje()" style="text-align: right;" value="0" /> </c:when> <c:otherwise> <input type="text" name="goodsItems.amount" id="amount" onfocus="onfocusSelect(this)" onblur="jsje()" class="baseline" style="width: 50px; text-align: right;" value="${goodsItems.amount}" /> </c:otherwise> </c:choose> </td> <td></td> <td> 单价: </td> <td> <select id="priceType" name="goodsItems.priceType" onchange="selectPrice(this)" style="width: 100px;"> <c:choose> <c:when test="${pcbtype == 0 || pcbtype == 1}"> <option value="0"> 采购标准价 </option> <option value="1"> 采购最高价 </option> </c:when> <c:when test="${pcbtype == 2 || pcbtype == 3}"> <option value="2"> 销售标准价 </option> <option value="3"> 最低销售价 </option> </c:when> </c:choose> </select> <input type="text" id="price" name="goodsItems.price" onblur="jsje()" /> </td> <td width="10"></td> <td> 折扣率: </td> <td> <input type="text" id="discountRate" name="goodsItems.discountRate" style="text-align: right" onblur="jsje()" value="${pcb.goodsItems.discountRate}" /> </td> </tr> <tr> <td> 折扣额: </td> <td> <input type="text" id="zke" value="0.00" disabled="disabled" style="text-align: right" /> <input type="hidden" id="discount" name="goodsItems.discount" value="${goodsItems.discount}" /> </td> <td width="20"></td> <td> <c:choose> <c:when test="${pcbtype == 0 || pcbtype == 1}"> 采购额: </c:when> <c:when test="${pcbtype == 2 || pcbtype == 3}"> 销售额: </c:when> </c:choose> </td> <td> <input type="text" id="je" value="0.00" disabled="disabled" style="text-align: right" /> <input type="hidden" id="procureCellMoney" name="goodsItems.procureCellMoney" value="${goodsItems.procureCellMoney}" /> </td> <td colspan="4"></td> </tr> <tr> <td> 说明: </td> <td colspan="8"> <input type="text" id="notes" name="goodsItems.notes" style="width: 500px;" /> </td> </tr> <tr> <td colspan="9" align="right"> <input type="button" value="保存分录" onclick="addGoodsItems()" /> <input type="reset" value="重置" /> </td> </tr> </table> </from> [/code] action 代码: [code="java"] public String addGoodsItems(){ log.info("获得的存货名称是:"+goodsItems.getGoodsName()); log.info('这里面我准备将form表单中提交过来的数据存到session中去,如果,我提交采购单的话,才将session中的值取出来存到数据库中,session中我想的是存放一个goodsMap'); return "addItems"; } [/code] struts.xml 代码: [code="xml"] <package name="goodsItems" extends="json-default"> <action name="addGoodsItems" class="xxpcb" method="addGoodsItems"> <result name="addItems"> <!--<param name="includeProperties">goodsItemsMap.*</param>--> </result> </action> </package> [/code]
struts的html:cancel的用法
为什么我使用struts的html:cancel标签后,在表单点击cancel后,页面交给action后为什么输入框里的内容的数据还是存在? 这是我的表单内容: <html:form action="/reg.do" method="post"> 用户id<html:text property="userid"></html:text><br/> 用户名<html:text property="username"></html:text><br/> 电子邮箱<html:text property="email"></html:text><br/> <html:submit value="注册用户"></html:submit> <input type="reset" value="reset"/> <html:cancel property="org.apache.struts.taglib.html.CANCEL" value="重新填写"></html:cancel> </html:form> 这是我的配置文件: <action attribute="userForm" input="/WEB-INF/register.jsp" name="userForm" path="/reg" scope="request" type="com.snow.struts.action.RegAction" cancellable="true" > <forward name="err" path="/WEB-INF/err.jsp" /> <forward name="ok" path="/WEB-INF/ok.jsp" /> <forward name="fail" path="/WEB-INF/register.jsp" /> </action> 这是我的action: if(isCancelled(request)){ return mapping.findForward("fail"); } 求教该如何解决?为什么我使用struts的html:cancel标签后,在表单点击cancel后,页面交给action后为什么输入框里的内容的数据还是存在? 这是我的表单内容: <html:form action="/reg.do" method="post"> 用户id<html:text property="userid"></html:text><br/> 用户名<html:text property="username"></html:text><br/> 电子邮箱<html:text property="email"></html:text><br/> <html:submit value="注册用户"></html:submit> <input type="reset" value="reset"/> <html:cancel property="org.apache.struts.taglib.html.CANCEL" value="重新填写"></html:cancel> </html:form> 这是我的配置文件: <action attribute="userForm" input="/WEB-INF/register.jsp" name="userForm" path="/reg" scope="request" type="com.snow.struts.action.RegAction" cancellable="true" > <forward name="err" path="/WEB-INF/err.jsp" /> <forward name="ok" path="/WEB-INF/ok.jsp" /> <forward name="fail" path="/WEB-INF/register.jsp" /> </action> 这是我的action: if(isCancelled(request)){ return mapping.findForward("fail"); } 求教该如何解决?
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
2019年还剩1天,我从外包公司离职了
这日子过的可真快啊,2019年还剩1天,外包公司干了不到3个月,我离职了
《面试宝典》2019年springmvc面试高频题(java)
前言 2019即将过去,伴随我们即将迎来的又是新的一年,过完春节,马上又要迎来新的金三银四面试季。那么,作为程序猿的你,是否真的有所准备的呢,亦或是安于本职工作,继续做好手头上的事情。 当然,不论选择如何,假如你真的准备在之后的金三银四跳槽的话,那么作为一个Java工程师,就不可不看了。如何在几个月的时间里,快速的为即将到来的面试进行充分的准备呢? 1、什么是Spring MVC ?简单...
计算机网络的核心概念
这是《计算机网络》系列文章的第二篇文章 我们第一篇文章讲述了计算机网络的基本概念,互联网的基本名词,什么是协议以及几种接入网以及网络传输的物理媒体,那么本篇文章我们来探讨一下网络核心、交换网络、时延、丢包、吞吐量以及计算机网络的协议层次和网络攻击。 网络核心 网络的核心是由因特网端系统和链路构成的网状网络,下面这幅图正确的表达了这一点 那么在不同的 ISP 和本地以及家庭网络是如何交换信息的呢?...
python自动下载图片
近日闲来无事,总有一种无形的力量萦绕在朕身边,让朕精神涣散,昏昏欲睡。 可是,像朕这么有职业操守的社畜怎么能在上班期间睡瞌睡呢,我不禁陷入了沉思。。。。 突然旁边的IOS同事问:‘嘿,兄弟,我发现一个网站的图片很有意思啊,能不能帮我保存下来提升我的开发灵感?’ 作为一个坚强的社畜怎么能说自己不行呢,当时朕就不假思索的答应:‘oh, It’s simple. Wait for me a few
一名大专同学的四个问题
【前言】   收到一封来信,赶上各种事情拖了几日,利用今天要放下工作的时机,做个回复。   2020年到了,就以这一封信,作为开年标志吧。 【正文】   您好,我是一名现在有很多困惑的大二学生。有一些问题想要向您请教。   先说一下我的基本情况,高考失利,不想复读,来到广州一所大专读计算机应用技术专业。学校是偏艺术类的,计算机专业没有实验室更不用说工作室了。而且学校的学风也不好。但我很想在计算机领...
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
20道你必须要背会的微服务面试题,面试一定会被问到
写在前面: 在学习springcloud之前大家一定要先了解下,常见的面试题有那块,然后我们带着问题去学习这个微服务技术,那么就会更加理解springcloud技术。如果你已经学了springcloud,那么在准备面试的时候,一定要看看看这些面试题。 文章目录1、什么是微服务?2、微服务之间是如何通讯的?3、springcloud 与dubbo有哪些区别?4、请谈谈对SpringBoot 和S...
Java 14 都快来了,为什么还有这么多人固守Java 8?
从Java 9开始,Java版本的发布就让人眼花缭乱了。每隔6个月,都会冒出一个新版本出来,Java 10 , Java 11, Java 12, Java 13, 到2020年3月份,...
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试一个ArrayList我都能跟面试官扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
2020年1月中国编程语言排行榜,python是2019增长最快编程语言
编程语言比例 排名 编程语言 最低工资 工资中位数 最低工资 最高工资 人头 人头百分比 1 rust 20713 17500 5042 46250 480 0.14% 2 typescript 18503 22500 6000 30000 1821 0.52% 3 lua 18150 17500 5250 35000 2956 0.84% 4 go 17989 16...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
立即提问