(学生党)如何将js获取到的text值传递给后台servlet页面(mvc) 5C

$("a").click(function () {
var txtContent=$(this).text();
然后通过servlet将取到的值进行查询
显示在新的jsp页面上

5个回答

$("a").click(function () {
var txtContent=$(this).text();
location.href= “test.do?xxx=”+txtContent;
}

后端用
request.getAttribute("xxx");可以取出来查询完数据库之后早用request.setAttribute("sss",sss);存起来然后跳转页面
在跳转后的页面用jstl表达式来获取

图片说明图片说明
这两个图片是mvc框架的,与servlet有点区别,不过传值都是一样的

可以通过ajax请求将取到的值提交给servlet。


<input id="username" type="text"/>
<button onclick="getFromServlet()"></button>

function getFromServlet(){
    var text = $("#username").val();
    $.ajax({
                type: "GET",
                url: "TestServlet.do?username="+text,
                dataType: "text",
                success: function(data){
                    //data就是返回的数据
                }
            });
}


public class TestServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/text; charset=utf-8");
        PrintWriter out = response.getWriter();
        //获取到jsp页面传过来的username
        String username = request.getParameter("username");


    }

}

$("a").click(function () {
var content=$(this).text();
$.get("你的服务器地址.jsp?v=" + content, function(result){
$("某个div").html(result);
});
});

你的服务器上用
request.getParameter("v") 可以获取

一般用AJax传值,不过新手可以先用表单体验下,有get和POST两种方式,后端用Springboot框架比较简单哦

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
(学生党)如何将js获取到的text值传递给后台servlet页面

$("a").click(function () { var content=$(this).text(); }); 传统的MVC模式,将从a标签中值用jq获取之后,如何将数据传到后台的servlet页面 ,并且获取出来,

如何将js获取到的text值传递给后台servlet页面,

<script type="text/javascript"> $("a").click(function () { var content=$(this).text(); });</script> 并且在servlet页面进行查询,查询的结果传递到新的页面中

通过js动态生成文本框,怎么把文本框中的值传到java后台?

var lengths; function insertrow2() //增加的一行方法2 { newRow=document.all.yltable.insertRow(-1); lengths = document.all.yltable.rows.length; newcell=newRow.insertCell() ; newRow.bgColor='#FFFFFF'; newcell.align='center'; newcell.innerHTML='<input name="button3" type="button" onClick="delrow1()" value="删除1"> '; newcell=newRow.insertCell() ; newRow.bgColor='#FFFFFF'; newcell.align='center'; newcell.innerHTML="<input type='text' id='name"+lengths+"' name='ylText"+lengths+"' />"; newcell=newRow.insertCell() ; newRow.bgColor='#FFFFFF'; newcell.align='center'; newcell.innerHTML="<input type='text' id='sex"+lengths+"' name='ylText"+lengths+"' />"; newcell=newRow.insertCell() ; newRow.bgColor='#FFFFFF'; newcell.align='center'; newcell.innerHTML="<input type='text' name='age"+lengths+"' />"; newcell=newRow.insertCell() ; newRow.bgColor='#FFFFFF'; newcell.align='center'; newcell.innerHTML="<input type='text' name='no"+lengths+"' />"; var a ="'name"+lengths+"'"; b = "name"+String(lengths); alert(b); var v = document.getElementById(b).value; alert(v); document.all.yltable.focus(); } function inserttable() { var newnode = document.getElementById('yltable').cloneNode(true); document.getElementById('ylform').appendChild(newnode); } function getValues(){ //通过这个方法可以取到动态table中输入的值,怎么能够通过button的提交,把该值传到后台处理? b = "name"+String(lengths); var address = document.getElementById(b).value; alert(address); //怎么把获取到的address 传到java后台呢? } </script>

使用servlet用request去获取前台在from的action后面用问号传值得不到,一直都为空

<form method="post" action="logServlet?op=add"> <table> <tr> <td colspan="2"><input type="text" name="title"/></td> </tr> <tr> </tr> <tr> <td colspan="2"><textarea name="content" rows="35" cols="100"></textarea></td> </tr> <tr> <td height="30px"><input type="image" src="images/fabiaolog_01.jpg" onmouseover="show()" onmouseout="moveOut()" id="img"/></td> <td align="left"><input type="reset" value="取消"/></td> </tr> </table> 这个是前台的代码 下面是servlet的代码 @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String op=request.getParameter("op"); if("add".equals(op)){ System.out.println("新增日志"); }else{ /** * 修改日志 */ this.updateLogInfo(request, response); } } 还有就是,request.getRequestDispatcher("logList.jsp").forward(request, response);这个一直都跳转不过去。。感觉是request失效了。。。

jsp与servlet数组怎么传值接收

<script type="text/javascript"> function se(){ var stno=document.getElementById("date1").value; var stno1=document.getElementById("date2").value; var stno2=document.getElementById("year1").value; var stno3=document.getElementById("month1").value; var stno4=document.getElementById("man").value; window.location="${pageContext.request.contextPath}/servlet/GrowthOwnerServlet?stno="+stno+"&stno1="+stno1+"&stno2="+stno2+"&stno3="+stno3+"&stno4="+stno4+""; } function se1(){ var stno=document.getElementById("date1").value; var stno1=document.getElementById("date2").value; var stno2=document.getElementById("year1").value; var stno3=document.getElementById("month1").value; var stno4=document.getElementById("man").value; window.location="${pageContext.request.contextPath}/servlet/GrowthOwnerExcel?stno="+stno+"&stno1="+stno1+"&stno2="+stno2+"&stno3="+stno3+"&stno4="+stno4+""; } function checkAll(field) { var selectFlags = document.getElementsByName("selectFlag"); for (var i=0; i<selectFlags.length; i++) { selectFlags[i].checked = field.checked; } } function see(){ var stno=document.getElementById("date1").value; var stno1=document.getElementById("date2").value; var stno2=document.getElementById("year1").value; var stno3=document.getElementById("month1").value; var stno4=document.getElementById("man").value; var selectFlags=[]; var selectFlags = document.getElementsByName("selectFlag"); var flag = false; for (var i=0; i<selectFlags.length; i++) { if (selectFlags[i].checked) { flag = true; break; } } alert(selectFlags); window.location="${pageContext.request.contextPath}/servlet/GrowthOwnersServlet?stno="+stno+"&stno1="+stno1+"&stno2="+stno2+"&stno3="+stno3+"&stno4="+stno4+"&selectFlags="+selectFlags+""; } </script> </head> <body class="body1"> <form name="matterForm" id="matterForm" > <div align="left" > 需求日期<input type="text" id="date1" name="date1" onclick="new Calendar().show(this);" value="${date1}" readonly="true" autocomplete="off" /> <input type="text" id="date2" name="date2" onclick="new Calendar().show(this);" value="${date2}" readonly="true" autocomplete="off" /> 需求年月<select name="year1" id="year1" onchange="onselectd();"> <option value="2017">2017年</option> <option value="2018">2018年</option> <option value="2019">2019年</option> <option value="2020">2020年</option> <option value="2021">2021年</option> <option value="2022">2022年</option> <option value="2023">2023年</option> </select> <select name="month1" id="month1" onchange="onselectd();"> <option value="01">1月</option> <option value="02">2月</option> <option value="03">3月</option> <option value="04">4月</option> <option value="05">5月</option> <option value="06">6月</option> <option value="07">7月</option> <option value="08">8月</option> <option value="09">9月</option> <option value="10">10月</option> <option value="11">11月</option> <option value="12">12月</option> </select> 店面区域范围<select name="man" id="man" onchange="onselectd();"> <option value="222104112">孙xx</option> <option value="222104360">张xx</option> <option value="222103816">谌xx</option> <option value="222103226">刘xx</option> <option value="222104891">罗xx</option> <option value="111222333">管xx</option> </select> <input type="button" id="button" onclick="see()" class="button1" value="查询" > <input type="button" id="button" onclick="se1()" class="button1" value="导出execl" > <c:forEach items="${fault}" var="i"> <tr> <td width="37" class="rd8"> <input name="selectFlag" type="checkbox" class="checkbox1" id="selectFlag" value="${i.shopid}"> </td> <td width="100" class="rd8"> <c:out value="${i.shopid}"></c:out> </td> </tr> </c:forEach> </div> ============================================== 后台servlet部分 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("text/html;charset=utf-8"); String date1=request.getParameter("stno"); String date2=request.getParameter("stno1"); String year1=request.getParameter("stno2"); String month1=request.getParameter("stno3"); String man=request.getParameter("stno4"); String [] ss= request.getParameterValues("selectFlags"); // System.out.println(date1); // System.out.println(man); // System.out.println(ss); DataManage mn=new DataManage(); request.getSession().setAttribute("date1", date1); request.getSession().setAttribute("date2", date2); request.getSession().setAttribute("year1", year1); request.getSession().setAttribute("month1", month1); request.setAttribute("qc",mn.getGrowthOwners(date1,date2,year1,month1,man,ss)); request.getRequestDispatcher("/page/model/alliance/growthOwner.jsp").forward(request, response); } ============= service 里的方法 public List<GrowthOwner> getGrowthOwners(String date1,String date2,String year1,String month1,String man,String[] ss){ List<GrowthOwner> pre=new ArrayList<GrowthOwner>(); Connection cn=null; PreparedStatement pr=null; ResultSet rs=null; try { cn=getConnection(); pr=cn.prepareCall("{ call companyreport.[dbo].[店成长率报表_个人] (?,?,?,?,?)}"); pr.setString(1,date1); pr.setString(2,date2); pr.setString(3, year1+"-"+month1); pr.setString(4,man); pr.setString(5, ss); rs=pr.executeQuery(); while(rs.next()){ pre.add(new GrowthOwner(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10), rs.getString(11),rs.getString(12),rs.getString(13),rs.getString(14),rs.getString(15))); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { rs.close(); pr.close(); cn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return pre; }

怎样让js和java之间传值?

如下:一个用户登录,怎么消除一开始的alert窗口。能用java代码调用js的函数么? 或者用java传一个flag给js. <%@ 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> <body> <h1>用户登录</h1> <form action="" method = "get" onsubmit="return check()" name="form1"> 用户名:<input type="text" name="name"><br> 密码:<input type="password" name="password"><br> <input type="submit" > </form> </body> <script type="text/javascript"> <% String name = request.getParameter("name"); String password = request.getParameter("password"); if(name!=null && name.trim().length()>0 && name.equals("tom")&& password!=null && password.trim().length()>0 && password.equals("1234")){ %> alert("success!")<% }else{ %> alert("fail!")<% } %> </script> </html>

html+js+servlet 前端接收不到结果

html ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Js</title> </head> <body> <input type="text" id="param1" /> <input type="text" id="param2" /> <button onclick="ajax()">Go!</button> </body> </html> <script> function createXMLHttpRequest() { var XMLHttpRequest1; if (window.XMLHttpRequest) { XMLHttpRequest1 = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { XMLHttpRequest1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { XMLHttpRequest1 = new ActiveXObject("Microsoft.XMLHTTP"); } } return XMLHttpRequest1; } function ajax() { //param1与param2就是用户在输入框的两个参数 var param1=document.getElementById("param1").value; var param2=document.getElementById("param2").value; var XMLHttpRequest1 = createXMLHttpRequest(); //指明相应页面 var url = "http://192.168.0.111:8080/AjaxServer/Test"; XMLHttpRequest1.open("POST", url, true); //这里没法解释,你所有JavaScript的请求头都这样写就对了,不会乱码 XMLHttpRequest1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //对于ajaxRequest,本js.html将会传递param1与param2给你。 XMLHttpRequest1.send("param1=" + param1 + "&param2=" + param2); //对于返回结果怎么处理的问题 XMLHttpRequest1.onreadystatechange = function() { //这个4代表已经发送完毕之后 if (XMLHttpRequest1.readyState == 4) { //200代表正确收到了返回结果 if (XMLHttpRequest1.status == 0) { //弹出返回结果 alert(XMLHttpRequest1.responseText); } else { //如果不能正常接受结果,你肯定是断网,或者我的服务器关掉了。 alert("网络连接中断!"); } } }; } </script> ``` servlet: ``` /** * Servlet implementation class Test */ @WebServlet("/Test") public class Test extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Test() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html; charset=utf-8"); PrintWriter pw = response.getWriter(); request.setCharacterEncoding("utf-8"); String param1=request.getParameter("param1"); System.out.println("param1="+param1); String param2=request.getParameter("param2"); System.out.println(",param2="+param2); pw.print("param1="+param1+",param2="+param2); pw.flush(); pw.close(); } } ``` 前段发送的请求servlet收到了,并且处理了,可是前段接收到结果总是为空,并且XMLHttpRequest1.status==0,求问哪里出了问题

购物车怎么通过jsp向servlet传递商品id和购买数量?

各位大神帮忙看看 servlet里想通过request.getParameter()来获取 form试过,不能获得点击按钮的商品id,全是相同的1 jsp: ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML> <html> <head> <title>商品信息列表</title> <script type="text/javascript" src="js/jquery-1.11.1.js"></script> <script type="text/javascript"> function increase(btn){ var $text=$(btn).prev(); var num=$text.val(); $text.val(++num); } function decrease(btn){ var $text=$(btn).next(); var num=$text.val(); if(num<=1){ return; } $text.val(--num); } </script> </head> <body> <h2>包子店</h2> <h4><a href="shoppingcarServlet">查看购物车</a></h4> <hr> <table width="80%" border="1"> <tr> <th>商品名称</th> <th>商品图片</th> <th>商品价格</th> <th>购买数量</th> <th>操作</th> </tr> <c:forEach items="${goodslist}" var="goodslist"> <tr align="center"> <td>${goodslist.name}</td> <td><img src="img/${goodslist.img}" width="200" height="70"></td> <td>${goodslist.price}</td> <td><input type="button" value="-" onclick="decrease(this);"> <input size="1" maxlength="4" type="text" id="num" name="num" value="1"/> <input type="button" value="+" onclick="increase(this);"/></td> <td><a href="shoppingcarServlet?id=${goodslist.id}">加入购物车</a></td> </tr> </c:forEach> </table> </body> </html> ``` ![图片说明](https://img-ask.csdn.net/upload/201601/15/1452860777_691480.png)这是商品页面,商品数量我想自己控制然后发送到servlet ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML> <html> <head> <title>商品信息列表</title> <script type="text/javascript" src="js/jquery-1.11.1.js"></script> <script type="text/javascript"> function increase(btn){ var $text=$(btn).prev(); var num=$text.val(); $text.val(++num); } function decrease(btn){ var $text=$(btn).next(); var num=$text.val(); if(num<=1){ return; } $text.val(--num); } </script> </head> <body> <h2>包子店</h2> <h4><a href="shoppingcarServlet">查看购物车</a></h4> <hr> <form action="shoppingcarServlet" method="get"> <table width="80%" border="1"> <tr> <th>商品名称</th> <th>商品图片</th> <th>商品价格</th> <th>购买数量</th> <th>操作</th> </tr> <c:forEach items="${goodslist}" var="goodslist"> <tr align="center"> <input type="hidden" name="id" value="${goodslist.id}"> <td>${goodslist.name}</td> <td><img src="img/${goodslist.img}" width="200" height="70"></td> <td>${goodslist.price}</td> <td><input type="button" value="-" onclick="decrease(this);"> <input size="1" maxlength="4" type="text" id="num" name="num" value="1"/> <input type="button" value="+" onclick="increase(this);"/></td> <td><input type="submit" value="加入购物车"></td> </tr> </c:forEach> </table> </form> </body> </html> ``` 这是改成的form表单提交,servlet接到的id全是第一件商品的id

uploadify3.2.1用formDate向servlet动态传递参数的问题,已经要崩溃了

这个传的参数,在servlet怎么用request都取不到,官方文档的方案也不对,已经疯了。。 ``` $("#uploadify").uploadify({ 'auto' : true, 'swf' : 'js/uploadify.swf', 'folder' : '/uploads', 'uploader' : url, 'method' : 'GET', 'cancelImg' : 'img/uploadify-cancel.png', 'progressData' : 'percentage', 'formData' : {"userName" : userName}, // "fileTypeDesc" : 'rar文件或zip文件', // "fileTypeExts" : '*.rar;*.zip', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc // 'multi' : true, 'buttonText' : '上传', 'onUploadStart' : function (file) { $("#uploadify").uploadify("settings",'userName',userName); }, 'onUploadSuccess' : function (file, data, response) { $('#' + file.id).find('.data').html('上传完毕!'); }, 'onUploadError ' : function (file, errorCode, errorMsg, errorString){ $('#' + file.id).find('.data').html('上传失败!'+errorMsg); } }); ```

form表单action带参数传递

上面是我的form头 我想要传type类型到servlet,但是servlet中接收到的type为空,请问type后面应该怎么写 <form method="post" action="/Exchange/servlet/itemAddAltSelServlet?type="add"" enctype="multipart/form-data">

如何取到jsp页面某一行表单数据的id

![图片说明](https://img-ask.csdn.net/upload/201709/12/1505204942_388393.png) ![图片说明](https://img-ask.csdn.net/upload/201709/12/1505204967_74849.png) 点击删除,可以获得当前行表单的userId并可以传递到后台!求大神指点

datagrid根据后台数据动态显示列名与内容

已知后台返回数据格式为(1){"total":8,"rows":[{"HID":"1","HNAME":"世纪新 都","AMOUNT":"1075.00"},{"HID":"2","HNAME":"江南商 都","AMOUNT":"33.00"},{"HID":"3","HNAME":"凯瑞商都","AMOUNT":"- 51.00"},{"HID":"4","HNAME":"阳光百货","AMOUNT":"9.00"}, {"HID":"5","HNAME":"银泰百货","AMOUNT":"-35.00"}, {"HID":"281","HNAME":"测试1","AMOUNT":"-13.00"}, {"HID":"297","HNAME":"家乐福","AMOUNT":"-4.00"}, {"HID":"327","HNAME":"利比亚","AMOUNT":"-2.00"}]} (2){"total":16,"rows":[{"WAID":"1","WANO":"3001","WANAME":"上 衣","UNITS":"件","SALE":"900","KKHJ":"-35.00","KK1":"0.00","KK2":"- 20.00","KK3":"-12.00","KK4":"- 3.00","KK5":"","KK281":"","KK297":"","KK327":"","ROWNUMBER":"1.00"}, {"WAID":"47","WANO":"700096","WANAME":"工装","UNITS":" 套","SALE":"100","KKHJ":"-24.00","KK1":"-4.00","KK2":"- 1.00","KK3":"","KK4":"","KK5":"","KK281":"- 19.00","KK297":"","KK327":"","ROWNUMBER":"2.00"}, {"WAID":"12569","WANO":"3001A","WANAME":"休闲裤","UNITS":" 件","SALE":"100","KKHJ":"-24.00","KK1":"- 3.00","KK2":"2.00","KK3":"- 23.00","KK4":"","KK5":"","KK281":"","KK297":"","KK327":"","ROWNUMBER":"3.00"}, {"WAID":"6592","WANO":"A121","WANAME":"西装","UNITS":" 套","SALE":"33","KKHJ":"-23.00","KK1":"","KK2":"","KK3":"- 19.00","KK4":"","KK5":"","KK281":"","KK297":"","KK327":"- 4.00","ROWNUMBER":"4.00"},{"WAID":"21","WANO":"3006","WANAME":"牛仔 裤","UNITS":"条","SALE":"280","KKHJ":"- 14.00","KK1":"","KK2":"","KK3":"","KK4":"","KK5":"- 19.00","KK281":"5.00","KK297":"","KK327":"","ROWNUMBER":"5.00"}, {"WAID":"3","WANO":"30032","WANAME":"风衣","UNITS":" 件","SALE":"900","KKHJ":"-12.00","KK1":"18.00","KK2":"- 17.00","KK3":"3.00","KK4":"","KK5":"- 16.00","KK281":"","KK297":"","KK327":"","ROWNUMBER":"6.00"}, {"WAID":"6591","WANO":"A12","WANAME":"西装","UNITS":" 套","SALE":"0","KKHJ":"-5.00","KK1":"","KK2":"","KK3":"- 1.00","KK4":"","KK5":"","KK281":"","KK297":"- 4.00","KK327":"0.00","ROWNUMBER":"7.00"}, {"WAID":"99","WANO":"CY003","WANAME":"衬衫","UNITS":" 件","SALE":"0","KKHJ":"-1.00","KK1":"- 1.00","KK2":"","KK3":"","KK4":"","KK5":"","KK281":"","KK297":"","KK327":"","ROWNUMBER":"8.00"}, {"WAID":"1324","WANO":"NZK0869","WANAME":"睡衣","UNITS":" 双","SALE":"0","KKHJ":"- 1.00","KK1":"","KK2":"","KK3":"","KK4":"","KK5":"","KK281":"- 1.00","KK297":"","KK327":"","ROWNUMBER":"9.00"}, {"WAID":"53","WANO":"7001","WANAME":"t恤条纹","UNITS":" 件","SALE":"380","KKHJ":"0.00","KK1":"1.00","KK2":"- 1.00","KK3":"","KK4":"","KK5":"","KK281":"","KK297":"","KK327":"","ROWNUMBER":"10.00"}, {"WAID":"6572","WANO":"2543212","WANAME":"衬衫","UNITS":" 件","SALE":"44","KKHJ":"1.00","KK1":"1.00","KK2":"","KK3":"","KK4":"","KK5":"","KK281":"","KK297":"","KK327":"","ROWNUMBER":"11.00"}, {"WAID":"5","WANO":"3005","WANAME":"T恤","UNITS":" 件","SALE":"780","KKHJ":"2.00","KK1":"","KK2":"","KK3":"","KK4":"2.00","KK5":"","KK281":"","KK297":"","KK327":"","ROWNUMBER":"12.00"}, {"WAID":"48","WANO":"100330000001","WANAME":"女装雪纺衫红袖","UNITS":" 件","SALE":"500","KKHJ":"12.00","KK1":"","KK2":"12.00","KK3":"","KK4":"","KK5":"","KK281":"","KK297":"","KK327":"","ROWNUMBER":"13.00"}, {"WAID":"4","WANO":"3004","WANAME":"西便装","UNITS":" 件","SALE":"900","KKHJ":"15.00","KK1":"9.00","KK2":"","KK3":"","KK4":"5.00","KK5":"","KK281":"","KK297":"","KK327":"1.00","ROWNUMBER":"14.00"}, {"WAID":"2","WANO":"3002","WANAME":"大衣","UNITS":" 件","SALE":"900","KKHJ":"119.00","KK1":"54.00","KK2":"58.00","KK3":"1.00","KK4":"5.00","KK5":"","KK281":"","KK297":"","KK327":"1.00","ROWNUMBER":"15.00"}, {"WAID":"58","WANO":"771","WANAME":"女装-连衣裙","UNITS":" 套","SALE":"0","KKHJ":"1002.00","KK1":"1000.00","KK2":"","KK3":"","KK4":"","KK5":"","KK281":"2.00","KK297":"","KK327":"","ROWNUMBER":"16.00"}]} jsp: ``` <script type="text/javascript"> var colname=[]; var cols=[]; var ss=""; //分页设置 function pp(){ //var hide=$('#huizong').val(); //if(hide==0){ // hide1==true;hide2=true; //}else if(hide==1){ // hide1=false;hide2=true; //}else{ // hide1=true;hide2=false; //} $('#pp').pagination({//分页设置 layout:['first','links','last','manual'], pageSize:20, onSelectPage : function(pageNum, pageSize) { nouse=$('#nouse').val(); page=pageNum.toString(); getinventorydistri(page,nouse); } }); var col = [ [{ field : 'WARENAME', title : '商品', width : 20 }, { field : 'KCHJ', title : '小计', width : 20 }] ]; //s = "[["; // s = s + "{field:'WARENAME',title:'商品',width:160},{field:'COLORNAME',{field:'KCHJ',title:'小计'}"; // s = s + "]]"; var options= { idFile : 'WARENAME', width : '100%', height : '520px', fitColumns : true, striped : true, //隔行变色 rownumbers : true, //显示行数 singleSelect : true, columns:col, showFooter:true, onClickRow:function(rowIndex, rowData){ }, pageSize : 20 } //加载数据 $('#gg').datagrid(options); getinvdistridata(); setTimeout('1000'); getinvdistrisum(); setTimeout('1000'); getinventorydistri(); } //查询统计库存分布方法 function getinvdistridata(){ $('#selectd').dialog('close'); var nowdate =$('#nowdate').datebox('getValue');//当前时间 var wareid=$("#awareno").val();//货号 var adbrandid =$("#adbrandid").val();//品牌 var adtypeid=$("#adtypeid").val();//类型 var prodyear=$("#yearss").val();//生产年份 var seasonname=$("#jijie option:selected").text();//季节 //alert(nowdate); $.ajax({ type : "POST", //访问WebService使用Post方式请求 url : "InvDistriServlet", //调用WebService的地址和方法名称组合 ---- WsURL/方法名 data : { invdistriser : "getinvdistridata", nowdate:nowdate, wareid:wareid, adbrandid:adbrandid, adtypeid:adtypeid, prodyear:prodyear, seasonname:seasonname }, //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到 dataType : 'text', success : function(text) { //回调函数,result,返回值 if (text != "f") { data = $.parseJSON(text); $('#gg').datagrid('loadData', data); $('#pp').pagination({ total : data.total, }); } else { alert(text); } } }); } function getinvdistrisum(){ $('#selectd').dialog('close'); $.ajax({ type : "POST", //访问WebService使用Post方式请求 url : "InvDistriServlet", //调用WebService的地址和方法名称组合 ---- WsURL/方法名 data : { invdistriser : "getinvdistrisum" }, //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到 dataType : 'text', success : function(text) { //回调函数,result,返回值 if (text != "f") { alert(text); //colname = $.parseJSON(text); colname=text; } else { alert(text); } } }); } //查询库存分布列表方法 function getinventorydistri(page, nouse){ $('#selectd').dialog('close'); var hzfs=$("#huizong").val();//汇总方式 var wareid=$("#awareno").val();//货号 var adbrandid =$("#adbrandid").val();//品牌 var adtypeid=$("#adtypeid").val();//类型 var prodyear=$("#yearss").val();//生产年份 var seasonname=$("#jijie option:selected").text();//季节 var order=$("input[name='pai1']:checked").val();//排序方式 var paixu=$("#paixu").val();//排序项目 $.ajax({ type : "POST", //访问WebService使用Post方式请求 url : "InvDistriServlet", //调用WebService的地址和方法名称组合 ---- WsURL/方法名 data : { invdistriser : "getinvdistri", hzfs:hzfs, wareid:wareid, adbrandid:adbrandid, adtypeid:adtypeid, prodyear:prodyear, seasonname:seasonname, order:order, paixu:paixu, page:page,nouse:nouse }, //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到 dataType : 'text', success : function(text) { //回调函数,result,返回值 if (text != "f") { data = $.parseJSON(text); $('#gg').datagrid('loadData', data); $('#pp').pagination({ total : data.total, }); } else { alert(text); } } }); } </script> ``` Servlet:(为节约略去方法中从jsp取值) //库存分布数据求和及生成列表头 private void getinvdistrisum(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String,String> res = InvDistriBase.getinvdistrisum(); System.out.println("size"); System.out.println("size"+res.size()); PrintWriter out = response.getWriter(); out.print(res); out.close(); } private void getinvdistridata(HttpServletRequest request, HttpServletResponse response) throws IOException { // 获取统计库存数据 String res = InvDistriBase.getinvdistridata(); JSONObject obj = JSONObject.fromObject(res); InvDistriBase.sqltext=obj.getString("SQLTEXT"); PrintWriter out = response.getWriter(); out.print(res); out.close(); } private void getinvdistri(HttpServletRequest request, HttpServletResponse response) throws Exception { // 获得库存分页数据 String res = InvDistriBase.getinvdistri(); PrintWriter out = response.getWriter(); InvDistriBase.page = "1"; out.print(res); out.close(); }

前台页面中点击按钮,在弹出的编辑框中输入数值,点击提交按钮

jsp <table id="border" cellSpacing=1 cellPadding=0 width="100%" align=center border=0> <form name="infoForm" id="infoForm" method="post" action="webadmin/servlet/BookingServlet" target="actionifram"> <!-- BookingServlet在指定的框架中打开 --> <input type="hidden" id="method" name="method" value="save"> <input type="hidden" id="id" name="id" value="${a.id}"> <div id="modal-default" class="iziModal"> <!-- 弹窗内容设置 --> <!-- 提交按钮:输入框以及确认框 --> <ul class="datefrm"> <li><input type="text" class="form-control input1" value="联系人" name="linkman" id="linkman" value="${a.linkman}" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '联系人';}"></li> <li><input type="text" class="form-control input1" value="联系电话" name="linktel" id="linktel" value="${a.linktel}" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '联系电话';}"></li> <li class="center"><input name="" type="button" class="btn-primary btn1" value="提交" onclick="javascript:toSubmit();"></li> <!-- onclick="javascript:toSubmit();" --> <!-- <li class="tip center">已有<font color="red">36</font>位业主预约</li> --> <!-- 将预约人数去除 --> <!-- value="${a.id}即为所有的预约人数" --> </ul> </div> </form> </table> ``` BookingServlet ``` public void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Booking booking = (Booking) RequestUtil.copyParam(Booking.class, request); bookingDao.add(booking); //System.out.println("linkman=="+booking.getLinkman()); request.setAttribute("success", "预约服务增加成功!"); request.getRequestDispatcher("/webadmin/pages/success1.jsp").forward(request, response); } ``` ```

请求大佬支援!!!为什么我的$.post执行有错

错误 ![图片说明](https://img-ask.csdn.net/upload/201910/27/1572162999_869619.jpg) ## 这个是前台 ``` <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <%-- <base href="<%=basePath%>"/> --%> <meta charset="utf-8"> <title>验证码</title> <script type="text/javascript" src="js/jquery-3.4.1.js"></script> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> function reloadCheckImg(){ /* 强制刷新:除了禁止缓存以外,还需要给服务端传递一个唯一的参数值, 参数一般是随机数或者时间,这个参数没有什么实际的意义 */ $("img").attr("src","img.jsp?t="+(new Date().getTime()));//<img src=""> } $(document).ready(function(){ $("#checkcodeId").blur(function(){ var $checkcode = $("#checkcodeId").val(); //校验:文本框中输入值发送到服务端 //服务端:获取文本框输入的值,和真实验证码图片中的值对比,并返回验证结果 $.post( "CheckCodeServlet",//发送请求地址 {checkcode:$checkcode},//待发送 Key/value参数 function(result){//发送成功时回调函数 var resulthtml = $("<p>"+result+"</p>"); $("#tip").html(resulthtml); alert("resulthtml"); }); }); }); </script> </head> <body> 验证码: <input type="text" name="checkcode" id="checkcodeId" size="4"> <!-- 验证码: --> <a href="javascript:reloadCheckImg();"><img src="img.jsp"></a> <span id="tip"></span> </body> </html> ``` **##这个是后台** ``` package my; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/CheckCodeServlet") public class CheckCodeServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("111"); String resultTip = "验证码错误"; //获取用户输入的验证码 String checkcodeClient = req.getParameter("checkcode"); //真实的验证码值 String checkcodeServer = (String) req.getSession().getAttribute("CHECKCODE"); if(checkcodeServer.equals(checkcodeClient)) { resultTip = "g"; } resp.setContentType("text/html;charset=utf-8"); PrintWriter writer = resp.getWriter();//输出流 writer.write(resultTip); writer.flush(); writer.close(); } } ```

spring thymeleaf 中文乱码

userList.html [code="java"] <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <div><span>用户名:</span><input name="name" value=""/><input type="button" id="search" value="查询"/></div> <div id="user"> </div> <div id="userlist" > <table > <thead> <tr> <th>name</th> <th>age</th> <th>sex</th> </tr> </thead> <tr th:each="sb : ${allUsers}"> <td th:text="${sb.name}"></td> <td th:text="${sb.age}"></td> <td th:text="${sb.sex}"></td> </tr> </table> <a href="thymeleafe/userList">go userList</a> </div> </body> </html> [/code] dispatcher-servlet.xml [code="java"] <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"> <property name="prefix" value="/WEB-INF/views/html/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML5" /> <property name="cacheable" value="true" /> <property name="characterEncoding" value="UTF-8"/> </bean> <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> </bean> <bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <property name="order" value="1" /> <property name="viewNames" value="thymeleafe/*" /> </bean> [/code] ThymeleafeControler [code="java"] package com.cn.ld.modules.thymeleaf; import java.util.List; @RequestMapping("/thymeleafe/") @Controller public class ThymeleafeControler { @Autowired private UserService userService; @RequestMapping("userList") public String goSerchUserH(HttpServletResponse response) { return "userList"; } @ModelAttribute("allUsers") public List<User> getAllUsers(){ return this.userService.getUserList(); } @RequestMapping("save") public void save(User user){ this.userService.addUser(user); } @RequestMapping("remove") public void save(String name){ User u = this.userService.findByName(name); this.userService.removeUser(u); } } [/code] web.xml [code="java"] <!-- 字符集 过滤器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> [/code] pom.xml [code="java"] <!-- thymeleaf --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring3</artifactId> <version>2.0.17</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>2.0.17</version> </dependency> [/code] [img]http://dl2.iteye.com/upload/attachment/0086/6304/9fc69b75-4a27-3ed3-b262-77fd356fc4f0.png[/img]

java向mysql写入数据时,double类型行报错

**做了一个插入学生信息的页面,用户填写完相应内容后,调用studentDaoImpl中的addStu方法向数据库写入对应数据** ## addStu方法 ``` public int addStu(student stu) { // TODO Auto-generated method stub sql = "insert into student values(?,?,?,?,?,?)";//int string string int string double try { PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, stu.getId()); ps.setString(2, stu.getName()); ps.setDouble(3, stu.getScore()); ps.setString(4, stu.getSex()); ps.setInt(5, stu.getAge()); ps.setString(6, stu.getClassname()); num = ps.executeUpdate(); ps.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return num; } ``` ## **Servlet中取页面输入的数据(数据格式已经用js控制了) ``` public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); double score = Double.parseDouble(request.getParameter("score")); String sex = request.getParameter("sex"); int age = Integer.parseInt(request.getParameter("age")); String classname = request.getParameter("classname"); /*添加进数据库前先判断此学生存在了没有 * :存在,返回页面并提示已存在 * :不存在,添加 * */ studentDaoImpl sdi = new studentDaoImpl(); if(sdi.findStuById(id)!=null){ //存在 request.setAttribute("exist", "<font color='red'>此学生已存在</font><br/>"); request.getRequestDispatcher("addStu.jsp").forward(request, response); } else{ //不存在 student stu = new student(); stu.setId(id); stu.setName(name); stu.setScore(score); stu.setSex(sex); stu.setAge(age); stu.setClassname(classname); sdi.addStu(stu); request.setAttribute("exist", "添加成功"); request.getRequestDispatcher("addStu.jsp").forward(request, response); } } ``` ## 这是js代码,用正则表达式控制input的各个数据格式 ``` // JavaScript Document function check(){ var id = document.getElementsByName('id')[0].value.replace(/(^\s*)|(\s*$)/g, ""); var score = document.getElementsByName('score')[0].value.replace(/(^\s*)|(\s*$)/g, ""); var age = document.getElementsByName('age')[0].value.replace(/(^\s*)|(\s*$)/g, ""); var classname = document.getElementsByName('classname')[0].value.replace(/(^\s*)|(\s*$)/g, ""); var errors = document.getElementsByName('error'); var flag = true; /*每次点击时都先清空错误提示消息*/ for(var i=0; i<errors.length; i++){ errors[i].innerHTML = ""; } if(/^[1-9]\d{0,1}/.test(id)==false){ errors[0].innerHTML = "学号输入有误,应为非0开头的1-2位数字"; flag = false; } if(/^\d+(\.\d+)?$/.test(score)==false){ errors[1].innerHTML = "分数格式有误,应为非负小数或整数"; flag = false; } if(/^[1-9]\d{0,2}$/.test(age)==false){ errors[2].innerHTML = "年龄格式有误,应为1-3位不为0开头的数字"; flag = false; } if(/^[1-9]{2}[\u4e00-\u9fa5]{2,3}[1-9]{1}[\u73ed]{1}$/.test(classname)==false){ errors[3].innerHTML = "班级名称格式有误,应为'2位数字+2字专业+1位数字+班'"; flag = false; } return flag; } ``` 在执行时报错Data truncated for column 'score' at row 1,网上搜大多是说格式没有对应上,可能java里的score是个字符串而数据库里的是double,我也特意检查了一下表格式,发现无误,这是创建表的语句 ``` mysql> create table student( -> id int(10) not null auto_increment, -> name varchar(20) not null, -> score double(5,2) not null, -> sex varchar(2) not null, -> age int(3) not null, -> classname varchar(20) not null, -> primary key(id) -> )ENGINE=InnoDB, DEFAULT CHARSET=utf8; Query OK, 0 rows affected (0.01 sec) ``` 不太会排版,有点凌乱了,实在抱歉

使用ssm框架开发,一直跳转不到controller层。。。不报错。。。

``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="ctx" value="${pageContext.request.contextPath }"></c:set> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="${ctx}/css/style.css" type="text/css" media="all"/> <title>请假的实战记录</title> <style type="text/css"> body{ background-color: #fff; } </style> </head> <body> <center> <div style="width:350px;"> <form id="myForm" action="${ctx}/lr/lrAdd">----这就是跳转的地址 <h1>添加请假记录</h1> <table> <tr> <td>姓名</td> <td><input type="text" name="name" datatype="s6-16" errormsg="姓名长度为6-16位" nullmsg="请输入姓名"/> </td> </tr> <tr> <td>请假时间</td> <td> <input type="text" name="time" onclick="WdatePicker();" nullmsg="请输入时间"/> </td> </tr> <tr> <td>请假原因</td> <td> <textarea name="reason" datadype="s1-200" errormsg="最长字数为200" nullmsg="请假原因"></textarea> </td> </tr> <tr> <td></td> <td> <input type="submit" name="" value="提交"/>&nbsp;&nbsp; <input type="reset" name="" value="清空"/> </td> </tr> </table> </form> </div> </center> <scritpt type="text/javascript" src="${ctx}/js/jquery-1.9.1.min.js"></scritpt> <scritpt type="text/javascript" src="${ctx}/js/Validform_v5.3.2_min.js"></scritpt> <scritpt type="text/javascript" src="${ctx}/js/My97DatePicker/WdatePicker.js"></scritpt> <scritpt type="text/javascript" src="${ctx}/js/My97DatePicker/calendar.js"></scritpt> <script type="text/javascript"> $(function(){ $("#myFrom").Validform(); }); </script> </body> </html> ``` ``` package com.sxt.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.sxt.pojo.Leaver; import com.sxt.service.LrService; import com.sxt.util.DateUtil; @Controller() @RequestMapping("/lr") public class AddController { @Autowired LrService lrService; @RequestMapping("/lrAdd") public String lrAdd(Leaver leaver,HttpServletRequest request){ //接收前台传送的数据 String name = request.getParameter("name"); String time = request.getParameter("time"); String reason = request.getParameter("reason"); //设置时间模式 String patten ="yyyy-MM-dd"; //将信息整合成一个对象进行传递 Leaver lea = new Leaver(name, DateUtil.str2Date(time, patten), reason); //对后台数据进行调用 int count = lrService.addLea(lea); if(count > 0){ return "redirect:/index"; }else{ return "redirect:/add"; } } } ``` 控制台不报错,F12页面信息老是显示的是404,就进不了Controller层,老是显示 lrAdd好像有问题。。 ![图片说明](https://img-ask.csdn.net/upload/201710/16/1508149012_161177.png) 控制台不报错就是浏览器就成这样了。。。很伤啊。。一下午了,搞不定。。

JSP搜索联想框,新手求指教。

不是用的SSH框架,DAO用JDBC,项目赶工,DAO和Service整合在了一起,我是半路插入的~各位大神先别吐槽……咱先把问题解决再美化~谢谢 页面结构如下 ``` <input name="accountName" id="accountName" class="yhgl_ser required inputElem" onkeyup="getLinkData();" value="<%StringHelper.filterHTML(out, request.getParameter("accountName"));%>" /> <div id="popup" style="position: absolute;"> <table width="100%" bgcolor="#fffafa"> <tbody id="popupBody"></tbody> </table> </div> ``` JS代码如下(借鉴了很多网上的JS方法) ``` <script type="text/javascript"> function getLinkData() { var popupDiv = document.getElementById("info");//获得对应的div对象 var popupBody = document.getElementById("popupBody");//获得对应的tbody对象 var linkDataProperty = document.getElementById("accountName"); //获得对应的输入框对象 clearModels();//清除联想输入提示框的内容 //利用ajax获取后台的模糊查询的数据,并且封装成下拉列表的形式展现出来 $.ajax({ type : "post",//提交的方法为post //对应的Action提交的路径 url : "<%configureProvider.format(out, URLVariable.SEARCH_ACCOUNT);%>", data:{linkDataProperty:linkDataProperty.value},//从前台传递到后台的查询语句的参数 dataType : "json", //从Action中返回的数据的类型为json类型的 error:function(){ alert("没有对应的数据,请查看输入的查询条件!"); }, success : function(data) {//当Ajax提交成功时调用的方法 if(data.length==0){return;} setOffsets();//设置联想输入下拉列表提示框的位置 var tr,td,text; for (var i = 0; i < data.length; i++) {//根据返回的值,手动的拼tbody的内容 text = document.createTextNode(data[i].linkDataProperty);//从Action中返回的数据中取出linkDataProperty的值 td = document.createElement("td");//创建一个td的对象 tr = document.createElement("tr");//创建一个tr的对象 td.mouseOver = function(){this.className="mouseOver;"}; td.mouseOut = function(){this.className="mouseOut;"}; td.onclick = function(){populateModel(this)};//单击td是的方法为populateModel td.appendChild(text); tr.appendChild(td); popupBody.appendChild(tr); } }}); //点击下拉列表中的某个选项时调用的方法 function populateModel(cell) { clearSelect(); linkDataProperty.value = cell.firstChild.nodeValue; //initOtherData(linkDataProperty.value);利用输入框中的数据调用其他方法,初始化其他数据 clearModels();//清除自动完成行 } //清除自动完成行,只要tbody有子节点就删除掉,并且将将外围的div的边框属性设置为不可见的 function clearModels() { while (popupBody.childNodes.length > 0) { popupBody.removeChild(popupBody.firstChild); } popupDiv.style.border = "none"; } //设置下拉列表的位置和样式 function setOffsets() { var width = linkDataProperty.offsetWidth;//获取linkDataProperty输入框的相对宽度 var left = getLeft(linkDataProperty); var top = getTop(linkDataProperty) + linkDataProperty.offsetHeight; popupDiv.style.border = "black 1px solid"; popupDiv.style.left = left + "px"; popupDiv.style.top = top + "px"; popupDiv.style.width = width + "px"; } //获取指定元素在页面中的宽度起始位置 function getLeft(e) { var offset = e.offsetLeft; if (e.offsetParent != null) { offset += getLeft(e.offsetParent); } return offset; } //获取指定元素在页面中的高度起始位置 function getTop(e) { var offset = e.offsetTop; if (e.offsetParent != null) { offset += getTop(e.offsetParent); } return offset; } } //清空输入框中的数据 function clearSelect() { var linkDataProperty=document.getElementById(linkDataProperty); linkDataProperty.value=""; } </script> ``` Servlet代码如下 ``` protected void processPost(HttpServletRequest request, HttpServletResponse response, ServiceSession serviceSession) throws Throwable { //往后传数据 System.out.println("进入servlet,将传入后台:"+request.getParameter("accountName")); //获得DAO服务 ZhglManage manage = serviceSession.getService(ZhglManage.class); //获得前台数据并往后台发送,同时接收返回的结果 String accounts = manage.searchAccountInOneResult(request.getParameter("accountName")); //往前端发送 PrintWriter out = response.getWriter(); System.out.println("返回servlet,即将返回获得的结果:"+accounts+" 给页面"); out.print(accounts); out.close(); } ``` DAO加Service代码如下: ``` public String searchAccountInOneResult(String inputing) throws Throwable { //尝试了Gson但也没成功 Gson gson = new Gson(); System.out.println("进入DAO,传入的参数是:"+inputing); //map方式 Map<String, String> rsMap = new HashMap<String,String>(); String account = ""; String key = ""; //获得连接 Connection conn = getConnection(); //准备SQL语句,获得单列账号信息 String sql = "SELECT @ROW := @ROW +1 AS ROW , t.F02 AS accountName FROM S61.T6110 t, ( SELECT @ROW :=0 )r WHERE t.F02 LIKE '"+inputing+"%' LIMIT 10"; PreparedStatement pstm = conn.prepareStatement(sql); //执行SQL ResultSet rs = pstm.executeQuery(); //获得结果 while(rs.next()){ //map方式 key = rs.getString("accountName"); account = rs.getString("accountName"); rsMap.put(key, account); } String temp = gson.toJson(rsMap); System.out.println("正在打印gson:"+temp); return temp; } ``` 然后控制台是这样的 进入servlet,将传入后台:1 进入DAO,传入的参数是:1 正在打印gson:{"12342@qq.com":"12342@qq.com","12344@qq.com":"12344@qq.com","100@qq.com":"100@qq.com"} 返回servlet,即将返回获得的结果:{"12342@qq.com":"12342@qq.com","12344@qq.com":"12344@qq.com","100@qq.com":"100@qq.com"} 给页面 firefox控制台和页面效果是这样的 ![图片说明](https://img-ask.csdn.net/upload/201505/18/1431943341_591979.png) 我对JS什么的不怎么懂,来请教下各位我哪里有问题,解决方法或者说解决思路应该是怎样的

Spring MVC + Spring + Mybatis + JqGrid 前台数据显示不出来

json ``` @Controller @RequestMapping("/crud") public class UserController { @Resource(name="userServiceImpl") private UserService userService; @RequestMapping(method = RequestMethod.GET) public @ResponseBody CustomUserResponse findAllUser(){ List<UserVO> users = userService.getAllUsers(); CustomUserResponse response = new CustomUserResponse(); response.setRows(users); response.setRecords( String.valueOf(users.size()) ); response.setPage( "1" ); response.setTotal( "10" ); return response;//返回给jqGrid } } ``` jsp ``` <script type ="text/javascript"> $(function () { $("#list").jqGrid({ url: "/GridApp/crud",//获取数据的地址 datatype: "json",//从服务器端返回的数据类型,默认xml mtype: "GET",//ajax提交方式。POST或者GET,默认GET colNames: ["编号", "姓名", "性别", "年龄", "备注"],//列显示名称,是一个数组对象 /* 常用到的属性:name 列显示的名称;index 传到服务器端用来排序用的列名称; width 列宽度;align 对齐方式;sortable 是否可以排序 */ colModel: [ { name: "id", width: 55 }, { name: "name", width: 90 }, { name: "sex", width: 80, align: "right" }, { name: "age", width: 80, align: "right" }, { name: "remark", width: 80, align: "right" } ], pager: "#pager", //定义翻页用的导航栏,必须是有效的html元素。翻页工具栏可以放置在html页面任意位置 rowNum: 10, //在grid上显示记录条数,这个参数是要被传递到后台 rowList: [10, 20, 30],//一个下拉选择框,用来改变显示记录数,当选择时会覆盖rowNum参数传递到后台 sortname: "invid",//默认的排序列。可以是列名称或者是一个数字,这个参数会被提交到后台 sortorder: "desc",//排序顺序,升序或者降序(asc or desc) viewrecords: true,//定义是否要显示总记录数 emptyrecords: "Empty records",//当返回的数据行数为0时显示的信息。只有当属性 viewrecords 设置为ture时起作用 gridview: true,//构造一行数据后添加到grid中,如果设为true则是将整个表格的数据都构造完成后再添加到grid中,但treeGrid, subGrid, or afterInsertRow 不能用 autoencode: true,//对url进行编码 caption: "My first grid",//表格名称 jsonReader : { root: "rows", page: "page", total: "total", records: "records", repeatitems: false, cell: "cell", id: "id" } }); }); </script> <body> <table id = "list" ><tr><td></td></tr></table> <div id = "pager"></div> </body> ``` 异常 严重: Servlet.service() for servlet [springmvc] in context with path [/GridApp] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class com.java.json.CustomUserResponse] with root cause java.lang.IllegalArgumentException: No converter found for return value of type: class com.java.json.CustomUserResponse at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:178) at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:153) at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:165) at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:80) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Intellij IDEA 实用插件安利

1. 前言从2020 年 JVM 生态报告解读 可以看出Intellij IDEA 目前已经稳坐 Java IDE 头把交椅。而且统计得出付费用户已经超过了八成(国外统计)。IDEA 的...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

魂迁光刻,梦绕芯片,中芯国际终获ASML大型光刻机

据羊城晚报报道,近日中芯国际从荷兰进口的一台大型光刻机,顺利通过深圳出口加工区场站两道闸口进入厂区,中芯国际发表公告称该光刻机并非此前盛传的EUV光刻机,主要用于企业复工复产后的生产线扩容。 我们知道EUV主要用于7nm及以下制程的芯片制造,光刻机作为集成电路制造中最关键的设备,对芯片制作工艺有着决定性的影响,被誉为“超精密制造技术皇冠上的明珠”,根据之前中芯国际的公报,目...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

差点跪了...

最近微信又搞出了一个大利器,甚至都上了热搜,当然消息最敏捷的自媒体人,纷纷都开通了自己的视频号。01 视频号是什么呢?视频号是微信体系内的短视频,它不同...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

Vue回炉重造之router路由(更新中)

你好,我是Vam的金豆之路,可以叫我豆哥。2019年年度博客之星、技术领域博客专家。主要领域:前端开发。我的微信是 maomin9761,有什么疑问可以加我哦,自己创建了一个微信技术交流群,可以加我邀请你一起交流学习。最后自己也创建了一个微信公众号,里面的文章是我自己精挑细选的文章,主要介绍各种IT新技术。欢迎关注哦,微信搜索:臻美IT,等你来。 欢迎阅读本博文,本博文主要讲述【】,文字通...

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐