servlet里面进行if语句的判断,由一个jsp页面显示不同结果

将注册信息提交到treatUser.java里面后要进行处理,其中包括姓名或密码为空,密码和确认密码不一致,注册成功。然后要在treatResult.jsp里面显示处理结果。要怎么做?
这是treatUser.java部分代码:
response.setContentType("text/html;charset=GBK");
ServletContext application = getServletContext();
String name=request.getParameter("name");
String passw=request.getParameter("passw");
String repassw=request.getParameter("repassw");
String sex=request.getParameter("sex");
String hobby=request.getParameter("hobby");
String intro=request.getParameter("introduction");
if((name!=null&&passw!=null)&&(passw.equals(repassw))){

        application.setAttribute("userName",name);
        application.setAttribute("userPassword",passw);
        application.setAttribute("userPassword1",repassw);
        application.setAttribute("sex",sex);
        application.setAttribute("hobby",hobby);
        application.setAttribute("introduction",intro);
    }
    String url = "/zhuceResult.jsp";
    ServletContext sc = getServletContext();//sc即application
    RequestDispatcher rd = sc.getRequestDispatcher(url);
    rd.forward(request, response);

}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
servlet内部跳转if语句不执行,也不报错
} else if ("shoppingCartBooks".equals(flag)) { String username = req.getParameter("username"); System.out.println(username+"****"); if (username != null) { List<Book> list = bs.getAllBooksInShoppingCart(username); req.setAttribute("list", list); req.getRequestDispatcher("jsp/shopping.jsp").forward(req, resp); } else if(username==null) { //req.setAttribute("errorMess", "请登录!"); System.out.println("跳转了!!"); req.getRequestDispatcher("BookServlet?flag=allBooks").forward( req, resp); } 一切正常,username也为空,打出来看了,也取到了,唯独,不进入if()条件句里面,怎么回事??也没有异常!!一切正常!!
java查询数据库中的数据会输出,输出的不是我的数据????
# ```数据封装在build,builds中 可是输出的不是数据库中的数据而是 ![图片说明](https://img-ask.csdn.net/upload/202004/02/1585822586_24417.jpg) # DormBuildDaoImpl.java package zj.shizhan.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import zj.shizhan.bean.DormBuild; import zj.shizhan.util.ConnectionFactory; public class DormBuildDaoImpl implements DormBuildDao { @Override public DormBuild findByName(String dormBuildName) { //获取连接(数据库地址 用户名 密码) Connection connection = ConnectionFactory.getConnection(); try { String sql = "select * from dormbuild where dormBuildName = ? "; //执行SQL语句 获取集装箱 或者说是 车 PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, dormBuildName); ResultSet rs = preparedStatement .executeQuery(); //因为查询出来的信息包括表头信息,所以指针下移一行,看是否有查询出的数据 //如有数据,就进入循环体封装该行数据 while (rs.next()) { DormBuild build = new DormBuild(); build.setDormBuildId(rs.getInt("dormBuildId")); build.setDormBuildName(rs.getString("dormBuildName")); build.setDetail(rs.getString("detail")); return build; } } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public void save(DormBuild build) { //获取连接(数据库地址 用户名 密码) Connection connection = ConnectionFactory.getConnection(); try { String sql = "INSERT INTO dormbuild(dormBuildName,detail)VALUES(?,?)"; //执行SQL语句 获取集装箱 或者说是 车 PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, build.getDormBuildName()); preparedStatement.setString(2, build.getDetail()); preparedStatement .executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } @Override public List<DormBuild> find() { //获取连接(数据库地址 用户名 密码) Connection connection = ConnectionFactory.getConnection(); try { String sql = "select * from dormbuild "; //执行SQL语句 获取集装箱 或者说是 车 PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet rs = preparedStatement .executeQuery(); //因为查询出来的信息包括表头信息,所以指针下移一行,看是否有查询出的数据 //如有数据,就进入循环体封装该行数据 List<DormBuild> builds = new ArrayList<DormBuild>(); while (rs.next()) { DormBuild build = new DormBuild(); build.setDormBuildId(rs.getInt("dormBuildId")); build.setDormBuildName(rs.getString("dormBuildName")); build.setDetail(rs.getString("detail")); builds.add(build); } return builds; } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public DormBuild findById(Integer dormBuildId) { //获取连接(数据库地址 用户名 密码) Connection connection = ConnectionFactory.getConnection(); try { String sql = "select * from dormbuild where dormBuildId = ? "; //执行SQL语句 获取集装箱 或者说是 车 PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, dormBuildId); ResultSet rs = preparedStatement .executeQuery(); //因为查询出来的信息包括表头信息,所以指针下移一行,看是否有查询出的数据 //如有数据,就进入循环体封装该行数据 while (rs.next()) { DormBuild build = new DormBuild(); build.setDormBuildId(rs.getInt("dormBuildId")); build.setDormBuildName(rs.getString("dormBuildName")); build.setDetail(rs.getString("detail")); return build; } } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public void update(DormBuild build ) { //获取连接(数据库地址 用户名 密码) Connection connection = ConnectionFactory.getConnection(); try { String sql = "UPDATE dormbuild SET dormBuildName = ?,detail = ? WHERE dormBuildId = ?"; //执行SQL语句 获取集装箱 或者说是 车 PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, build.getDormBuildName()); preparedStatement.setString(2, build.getDetail()); preparedStatement.setInt(3, build.getDormBuildId()); //执行更新 preparedStatement .executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } } ``` # DormBuildServlet.java ``` package zj.shizhan.servlet; import java.io.IOException; import java.util.ArrayList; 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 zj.shizhan.bean.DormBuild; import zj.shizhan.service.DormBuildService; import zj.shizhan.service.DormBuildServiceImpl; /** * Servlet implementation class DormBuildServlet */ @WebServlet("/dormBuild.action") public class DormBuildServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DormBuildServlet() { super(); } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); String action = request.getParameter("action"); //通过request.getParameter("id")方式获取的值都是String类型的 String dormBuildId = request.getParameter("dormBuildId"); System.out.println("action:"+action); DormBuildService dormBuildService = new DormBuildServiceImpl(); if(action !=null & action.equals("list")) { List<DormBuild> builds = new ArrayList<DormBuild>(); if( dormBuildId== null || dormBuildId.equals("")) { //查询所有宿舍楼信息,跳转到宿舍楼列表页 builds = dormBuildService.find(); }else if(dormBuildId != null && !dormBuildId.equals("")) { //点击查询按钮搜索某一栋宿舍楼的信息 DormBuild build = dormBuildService.findById(Integer.parseInt(dormBuildId)); builds.add(build); System.out.println("build:"+build); } //查询所有宿舍楼。在select中遍历 List<DormBuild> buildSelects = dormBuildService.find(); request.setAttribute("buildSelects", buildSelects); request.setAttribute("dormBuildId", dormBuildId); System.out.println("builds:"+builds); request.setAttribute("builds", builds); request.getRequestDispatcher("BuildList.jsp").forward(request, response); }else if (action !=null & "preAdd".equals(action)) { //表示跳转到宿舍楼添加页面 request.getRequestDispatcher("AddOrAlterBuild.jsp").forward(request, response); }else if (action !=null & "save".equals(action)) { //保存数据 String n = request.getParameter("dormBuildName"); String dormBuildName = new String(n.getBytes("ISO-8859-1"), "utf-8"); String m = request.getParameter("detail"); String detail = new String(m.getBytes("ISO-8859-1"), "utf-8"); System.out.println("dormBuildName:"+dormBuildName+"detail:"+detail+"id:"+dormBuildId); //判断宿舍楼名字是否已存在 DormBuild dormBuild = dormBuildService.findByName(dormBuildName); System.out.println("dormBuildName:"+dormBuildName); System.out.println("id2:"+dormBuildId); if(dormBuildId !=null && !"".equals(dormBuildId)) { System.out.println("id3:"+dormBuildId); //修改 if (dormBuild != null && !dormBuild.getDormBuildId().equals(Integer.parseInt(dormBuildId))) { request.setAttribute("error", "该宿舍楼已存在"); //格局宿舍楼id,查询宿舍楼 DormBuild build = dormBuildService.findById(Integer.parseInt(dormBuildId)); //保存宿舍楼信息,到前端页面展示 request.setAttribute("build", build); request.getRequestDispatcher("AddOrAlterBuild.jsp").forward(request, response); }else { dormBuild = dormBuildService.findById(Integer.parseInt(dormBuildId)); dormBuild.setDormBuildName(dormBuildName); dormBuild.setDetail(detail); dormBuildService.update(dormBuild); //更新完成后,跳转到宿舍楼管理列表页,查询所有宿舍楼 List<DormBuild> builds = dormBuildService.find(); request.setAttribute("builds", builds); request.getRequestDispatcher("BuildList.jsp").forward(request, response); } }else { //保存 System.out.println("id4:"+dormBuildId); if (dormBuild != null) { //该宿舍楼已存在 request.setAttribute("error", "该宿舍楼已存在"); request.getRequestDispatcher("AddOrAlterBuild.jsp").forward(request, response); }else { //该宿舍楼已不存在 DormBuild build = new DormBuild(); build.setDormBuildName(dormBuildName); build.setDetail(detail); dormBuildService.save(build); List<DormBuild> builds = dormBuildService.find(); request.setAttribute("builds", builds); request.getRequestDispatcher("BuildList.jsp").forward(request, response); } } }else if (action !=null & "preUpdate".equals(action)) { //格局宿舍楼id,查询宿舍楼 DormBuild build = dormBuildService.findById(Integer.parseInt(dormBuildId)); System.out.println("id1:"+dormBuildId); //保存宿舍楼信息,到前端页面展示 request.setAttribute("build", build); //表示跳转到宿舍楼修改页面 request.getRequestDispatcher("AddOrAlterBuild.jsp").forward(request, response); } } } ``` # DormBuild.java ``` package zj.shizhan.bean; public class DormBuild { private Integer dormBuildId; private String dormBuildName; private String detail; public DormBuild() { super(); } public DormBuild(Integer dormBuildId,String dormBuildName, String detail) { super(); this.dormBuildId = dormBuildId; this.dormBuildName = dormBuildName; this.detail = detail; } public String getDormBuildName() { return dormBuildName; } public void setDormBuildName(String dormBuildName) { this.dormBuildName = dormBuildName; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public Integer getDormBuildId() { return dormBuildId; } public void setDormBuildId(Integer dormBuildId) { this.dormBuildId = dormBuildId; } } ```
jsp页面调用Servlet后进入Servlet页面空白不跳转了
各位大大,小弟正在用java做毕业设计,遇到一个问题,就是想实现获取页面的学生姓名sname和学号sno,然后到数据库中执行查询,将这个学生的成绩从数据库中输出到新的页面。可是,问题来了:在查询页面点击提交按钮后,页面跳转到ChengjiServlet2页面,web浏览器就一片空白,在ChengjiServlet2页面的sendRedirect也没了作用。。。希望各位大大们看在我操心做毕业设计的份儿上帮帮我吧,说白了就是一个查询输出,望大大们指点!跪谢!! //查询页面,jsp。放在一个文件夹里。路径没出错 不支持直接使用html标签,所以我改了一下 《body》 《form id="form1" name="chengjiFrom" method="post" action="../ChengjiServlet2"》《h1 align="center"》成绩查询页面《/h1》 《p>姓名: 《input name="sname" type="text" id="sname" /> 《/p> 《p>学号: 《input name="sno" type="text" id="sno" /> 《/p> 《p> 《input type="submit" name="Submit" value="查询成绩" /> 《/p> 《/form> 《/body> >//这是我编写的ChengjiServlet2类 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List chengji = new ArrayList(); //获取chengjichaxun.jsp页面的各个控件属性 String Sname = request.getParameter("sname"); String Sno = request.getParameter("sno"); String SelectScore = request.getParameter("select"); ChengjiSQLUtil chengjiSql = new ChengjiSQLUtil(); Connection conn =null; Statement stmt=null; ResultSet rs = null; conn = chengjiSql.getConn_Bendi(); try { if(SelectScore.equals("score_1")) { //创建Statement实例,并执行sql语句 String sql = "SELECT * FROM 'renwu'.'score_da1' where sno='"+Sno+"' and sname='"+Sname+"'"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while(rs.next()) { String sno = rs.getString("sno"); String sname = rs.getString("sname"); String ke1_a = rs.getString("ke1_a"); String ke1_b = rs.getString("ke1_b"); String ke1_c = rs.getString("ke1_c"); String ke1_d = rs.getString("ke1_d"); String ke1_e = rs.getString("ke1_e"); String ke1_f = rs.getString("ke1_f"); chengji.add(sno); chengji.add(sname); chengji.add(ke1_a); chengji.add(ke1_b); chengji.add(ke1_c); chengji.add(ke1_d); chengji.add(ke1_e); chengji.add(ke1_f); } HttpSession session = request.getSession(); session.setAttribute("score", chengji); response.sendRedirect("chaxun_chengji/chengji_jieguo.jsp"); } else if(SelectScore.equals("score_2")) { String sql = "SELECT * FROM 'renwu'.'score_da2' where sno='"+Sno+"' and sname='"+Sname+"'"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while(rs.next()) { String sno = rs.getString("sno"); String sname = rs.getString("sname"); String ke2_a = rs.getString("ke2_a"); String ke2_b = rs.getString("ke2_b"); String ke2_c = rs.getString("ke2_c"); String ke2_d = rs.getString("ke2_d"); String ke2_e = rs.getString("ke2_e"); String ke2_f = rs.getString("ke2_f"); chengji.add(sno); chengji.add(sname); chengji.add(ke2_a); chengji.add(ke2_b); chengji.add(ke2_c); chengji.add(ke2_d); chengji.add(ke2_e); chengji.add(ke2_f); } HttpSession session = request.getSession(); session.setAttribute("score", chengji); response.sendRedirect("chaxun_chengji/chengji_jieguo.jsp"); } else if(SelectScore.equals("score_3")) { String sql = "SELECT * FROM 'renwu'.'score_da3' where sno='"+Sno+"' and sname='"+Sname+"'"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while(rs.next()) { String sno = rs.getString("sno"); String sname = rs.getString("sname"); String ke3_a = rs.getString("ke3_a"); String ke3_b = rs.getString("ke3_b"); String ke3_c = rs.getString("ke3_c"); String ke3_d = rs.getString("ke3_d"); String ke3_e = rs.getString("ke3_e"); String ke3_f = rs.getString("ke3_f"); chengji.add(sno); chengji.add(sname); chengji.add(ke3_a); chengji.add(ke3_b); chengji.add(ke3_c); chengji.add(ke3_d); chengji.add(ke3_e); chengji.add(ke3_f); } HttpSession session = request.getSession(); session.setAttribute("score", chengji); response.sendRedirect("chaxun_chengji/chengji_jieguo.jsp"); } else if(SelectScore.equals("score_4")) { String sql = "SELECT * FROM 'renwu'.'score_da4' where sno='"+Sno+"' and sname='"+Sname+"'"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while(rs.next()) { String sno = rs.getString("sno"); String sname = rs.getString("sname"); String ke4_a = rs.getString("ke4_a"); String ke4_b = rs.getString("ke4_b"); String ke4_c = rs.getString("ke4_c"); String ke4_d = rs.getString("ke4_d"); String ke4_e = rs.getString("ke4_e"); String ke4_f = rs.getString("ke4_f"); chengji.add(sno); chengji.add(sname); chengji.add(ke4_a); chengji.add(ke4_b); chengji.add(ke4_c); chengji.add(ke4_d); chengji.add(ke4_e); chengji.add(ke4_f); } HttpSession session = request.getSession(); session.setAttribute("score", chengji); response.sendRedirect("chaxun_chengji/chengji_jieguo.jsp"); } }catch(Exception e) { e.printStackTrace(); }finally { chengjiSql.releaseResources(conn, stmt, rs); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } > //这块是web.xml的相关信息 <servlet> <servlet-name>chengjiServlet2</servlet-name> <servlet-class>org.afan.course.servlet.ChengjiServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>chengjiServlet2</servlet-name> <url-pattern>/chengjiServlet2</url-pattern> </servlet-mapping> //这块是查询成功后要跳转的页面代码,目前还没能走到这个页面。我用list将数据输出,因为不会其他的将java类查询结果输出到jsp页面的方法。。 《body><P>成绩情况</P> 《table> <% List list = (List)session.getAttribute("score"); for(int i=0;i<list.size();i++) { out.print("成绩:" + list.get(i) + "<br/>"); } %> 《/table> 《/body>
servlet里面的一条语句不执行,无报错
下面request语句不执行,debug逐句运行,到这句就直接跳到finally,把if去掉也是一样 User user=new User(userName,password); Connection con=null; try { con=dbUtil.getCon(); User currentUser=userDao.login(con, user); if(currentUser==null){ request.setAttribute("error", "用户名或密码错误!"); // 服务器跳转 request.getRequestDispatcher("index.jsp").forward(request, response); }else{ // 客户端跳转 response.sendRedirect("main.jsp"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { dbUtil.closeCon(con); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
关于通过servlet查询jsp传过来的数据后显示在jsp页面的问题
本人写了个系统,经过测试以及能够运行到sql语句了,现在卡在不知道如何查询后的结果显示在jsp上,请教各位大神 ,代码如下 <br> servlet中的post方法 ``` protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String card = request.getParameter("card"); String type = request.getParameter("type"); String cardsearch = request.getParameter("cardsearch"); CardSearchDAO cd = new CardSearchDAOImpl(); List monsterlist; if(card.equals("monster")) { monsterlist = cd.getMonsetCardList(type, cardsearch); request.setAttribute("monsterlist", monsterlist); request.getRequestDispatcher("searchresult.jsp").forward(request, response); } if(card.equals("magic")) { cd.getMagicandtrapCardList(type, cardsearch); } } ``` DAOImpl中的getMonsterCardList方法 ``` public List getMonsterCardList(String type, String cardsearch) { StringBuffer sbf = new StringBuffer("select * from monstercard where 1=1"); if(type!=null) {sbf.append(" and type='"+type+"'");} if(cardsearch!=null) {sbf.append(" and cardname='"+cardsearch+"'");} String sql = sbf.toString(); System.out.println(sql); List monsterlist = new ArrayList(); conn = DBConnection.getConnectDb(); try { PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while(rs.next()) { MonsterCard mc = new MonsterCard(); mc.setCardname(rs.getString("cardname")); mc.setAtk(rs.getString("atk")); mc.setDef(rs.getString("def")); mc.setCardpack(rs.getString("cardpack")); mc.setEffect(rs.getString("effect")); mc.setQA(rs.getString("QA")); mc.setStauts(rs.getString("status")); mc.setType(rs.getString("type")); mc.setCardid(rs.getString("cardid")); monsterlist.add(mc); } } catch (SQLException e) { e.printStackTrace(); }finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return monsterlist; } ```
过滤器正常使用,可以拦截非法操作,但是合法注册无法跳转到登入页面
过滤器正常使用,可以拦截非法操作,但是合法注册无法跳转到登入页面。 ``` /** * Servlet Filter implementation class RegisterFilter */ @WebFilter("/RegisterFilter") public class RegisterFilter implements Filter { /** * Default constructor. */ public RegisterFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); //用户名过滤器 String userName = req.getParameter("userName"); PrintWriter out = resp.getWriter(); if(userName.equals("")) { out.write("<script>"); out.write("alert('用户名称不能为空');"); out.write("location.href='register.jsp';"); out.write("</script>"); out.close(); return; } //验证码过滤器 HttpSession session = req.getSession(); String verycode = req.getParameter("veryCode"); String sysCode = (String)session.getAttribute("code"); if(!sysCode.equals(verycode)) { out.write("<script>"); out.write("alert('验证码输入有误');"); out.write("location.href='register.jsp';"); out.write("</script>"); out.close(); return; } //return;//不通过则直接 // pass the request along the filter chain chain.doFilter(req, resp);// 通过则使用这条语句 } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } } ```
Java web页面内嵌的if语句报错
org.apache.jasper.JasperException: An exception occurred processing JSP page /Left.jsp at line 18 15: <tr> 16: <td height="5" align="center"><img src="Images/ic.gif" width="1" height="1"></td> 17: </tr> 18: <%if(session.getAttribute("type").toString().equals("1")){%> 19: <tr> 20: <td height="30" align="center" background="Images/left2.jpg" style="text-align:left; padding-left:40px;"><a href="TeacherManager.action">楼宇管理员管理</a></td> 21: </tr> Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:574) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause java.lang.NullPointerException org.apache.jsp.Index_jsp._jspService(Index_jsp.java:168) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) note The full stack trace of the root cause is available in the Apache Tomcat/8.0.35 logs.
一个JSP界面有多个按钮 对应一个servlet 其中一个按钮实现多表查询并显示出查询数据
一个JSP界面有多个按钮 对应一个servlet 其中一个按钮实现多表查询并显示出查询数据 跳转到JSP界面没有显示出任何结果 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html"); System.out.println("111111111"); PrintWriter out = response.getWriter(); String value=(String)request.getParameter("btnType"); if(value.equals("账单")){ User user = (User)request.getSession().getAttribute("userNow"); String name = user.getUser();//获取房东ID AccountCheck ac = new AccountCheck(); request.setAttribute( "ValueA",ac.getAllAccount(name)); response.sendRedirect("zhangdan.jsp"); //request.getRequestDispatcher("zhangdan.jsp").forward(request,response); } if(value.equals("闲置房号")){ } if(value.equals("即将到期的租客")){ } } 数据库操作: //查询所有账单的方法 public List getAllAccount(String name){ List list=new ArrayList(); try { url="jdbc:sqlserver://localhost:1433;DatabaseName=rh"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//加载驱动 Connection con = DriverManager.getConnection(url, "rh", "123");//获得连接对象 //查询语句 String sql="select 姓名,house.地址,租金,起始日期,终止日期 from house,renthouse,userinfro where house.代号=renthouse.代号 and renthouse.身份证号码=userinfro.身份证号码 and renthouse='"+name+"'"; //stmt.setString(1, name); stmt = con.prepareStatement(sql); System.out.println(sql); ResultSet rs = stmt.executeQuery(sql); //循环结果集,存储在list里面 while(rs.next()){ list.add(rs.getString("1")); list.add(rs.getString("2")); list.add(rs.getString("3")); list.add(rs.getString("4")); list.add(rs.getString("5")); for(int i = 0;i<list.size();i++){ System.out.println(list.get(i)); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } //返回List return list; } } from提交 <form id="form3" name="form3" method="post" action="LandlordServlet"> <div class="divcss5"> <input type='hidden' id='btnType' name='btnType'/> <input type='submit' btnType="action1" value="账单" style="width:200px;height:100px;background-color:#0997F7" onclick="document.getElementById('btnType').value=this.type;this.from.submint()"> <input type='submit' btnType="action2" value="闲置房号 "style="width:200px;height:100px;background-color:#DD9222" onclick="document.getElementById('btnType').value=this.type;this.from.submint()"> <input type='submit' btnType="action3" value="即将到期的租客" style="width:200px;height:100px;background-color:#22DD92" onclick="document.getElementById('btnType').value=this.type;this.from.submint()"> </div> <div class="divcss1"> <input type='submit' value="首页" style="width:80px;height:40px;background-color:#FFFFFF"onclick="window.location.href='Home.jsp'"> <br><br> <input type='submit' btnType="action4" value=租客信息 style="width:80px;height:40px;background-color:#FFFFFF" onclick="document.getElementById('btnType').value=this.type;this.from.submint()"> <br><br> </div> </form> 显示查询结果的JSP界面 <table border="1" width="60%" > <tr> <th>租客姓名</th> <th>地址</th> <th>租金</th> <th>租房日期</th> <th>租房截至日期</th> </tr> <% List list=(List)request.getAttribute(""); // if(list==null||list.size()%5!=0) // return; for(int i=0;i<list.size();i+=5) out.print("<td>"+(String)list.get(i)+"</td><td>"+(String)list.get(i+1)+"</td>"+(String)list.get(i+1)+"<td>"+(String)list.get(i+1)+"</td><td>"+(String)list.get(i+1)+"</td><td>"+(String)list.get(i+1)+"</td>/tr>"); %> </table> 在线等
JSP+servlet实现网页数据插入mysql问题求解
本意是将网页上表格数据插入到mysql的表中 数据获取和类的构造 L_datainsert.java package a; import java.io.IOException; import java.util.Date; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public abstract class L_datainsert implements javax.servlet.Servlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/html"); request.setCharacterEncoding("UTF-8"); String[] thi=request.getParameterValues("thi"); String[] the=request.getParameterValues("the"); String[] fl=request.getParameterValues("fl"); String[] chu=request.getParameterValues("chu"); String[] hh=request.getParameterValues("hh"); for(int n=0;n<10;n++){ Hs hs = new Hs(); hs.setThi(Double.parseDouble(thi[n])); hs.setThe(Double.parseDouble(the[n])); hs.setFl(Double.parseDouble(fl[n])); hs.setChu(Double.parseDouble(chu[n])); hs.setHh(Double.parseDouble(hh[n])); Hsinsert db = new Hsinsert(); boolean canLogin = db.addHs(hs);} } } class Hs { private double thi; private double the; private double fl; private double chu; private double hh; public Hs(double i, double e, double l,double u, double h) { thi = i; the = e; fl = l; chu = u; hh = h; } public Hs() { } public void setThi(double thi){ this.thi = thi; } public double getThi(){ return thi; } public void setThe(double the){ this.the = the; } public double getThe(){ return the; } public void setFl(double fl){ this.fl = fl; } public double getFl(){ return fl; } public void setChu(double chu){ this.chu = chu; } public double getChu(){ return chu; } public void setHh(double hh){ this.hh = hh; } public double getHh(){ return hh; } } 插入方法实现:Hsinsert.java package a; import java.sql.*; public class Hsinsert { boolean bInited = false; //加载驱动 public void initJDBC() throws ClassNotFoundException { //加载MYSQL JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); bInited = true; System.out.println("Success loading Mysql Driver!"); } public Connection getConnection() throws ClassNotFoundException, SQLException{ if(!bInited){ initJDBC(); } //连接URL为 jdbc:mysql//服务器地址/数据库名 //后面的2个参数分别是登陆用户名和密码 Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/login?characterEncoding=utf8&useSSL=true","root",""); return conn; } public boolean addHs(Hs hs){ boolean returnValue = false; try{ Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动,注册到驱动管理器 Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/login?characterEncoding=utf8&useSSL=true","root",""); //创建connection连接, String sql="insert into hs(thi,the,fl,chu,hh) values(?,?,?,?,?)"; //添加图书信息的sql语句 PreparedStatement ps=conn.prepareStatement(sql); //获取PreparedStatement ps.setDouble(2,hs.getThi());//对sql语句中的第1个参数赋值 ps.setDouble(3,hs.getThe());//对sql语句中的第2个参数赋值 ps.setDouble(4,hs.getFl());//对sql语句中的第3个参数赋值 ps.setDouble(5,hs.getChu());//对sql语句中的第4个参数赋值 ps.setDouble(6,hs.getHh()); int row=ps.executeUpdate();//执行更新操作,返回所影响的行数 if(row>0){ returnValue = true; } ps.close(); conn.close(); }catch (ClassNotFoundException e) { e.printStackTrace(); }catch (SQLException e) { e.printStackTrace(); } return returnValue; } } 但是运行没办法实现 弹出![图片说明](https://img-ask.csdn.net/upload/201706/01/1496308529_290964.png) 是因为我没有设置好xml文件吗 还是别的原因?我的xml文件内容如下:![图片说明](https://img-ask.csdn.net/upload/201706/01/1496312692_144002.png) 工程内容截图为:![图片说明](https://img-ask.csdn.net/upload/201706/01/1496312785_296623.png) 我重新配置了xml文件:![图片说明](https://img-ask.csdn.net/upload/201706/02/1496367553_524699.png) 但还是没好,运行错误为![图片说明](https://img-ask.csdn.net/upload/201706/02/1496367922_913258.png) ![图片说明](https://img-ask.csdn.net/upload/201706/02/1496367937_625333.png)
struts2 我在jsp页面中获取到了list集合中的对象但是就是不显示值
我用struts2在jsp中遍历了一个集合,集合中也有数据就是没法显示,如果用el表达式取对象 可以打印出来,但是取对象的属性就报错 先上代码 // action层 @Controller public class NreportAction extends BaseAction { /** * 内部审计S相关的封装 */ @Resource private NreportService nreportService; // 内审service private List<Nreport> nreportList; private Nreport nreport; public NreportAction(){ System.out.println("进来了"); } // 内审填报页面 public String addUI(){ System.out.println("时空裂缝"); try { // System.out.println("1.先查出上一年没有完成的任务"); // System.out.println("2.查询出纪检监察室下发状态 , 如果下发了,就显示一条记录,让下级部门填写"); nreportList = nreportService.findNotDoPro(); if(nreportList!=null && nreportList.size()>0){ System.out.println("上一年未完成的项目有"+nreportList.size()+"个"); } } catch (Exception e) { System.out.println(e.getMessage()); } return "reportUI"; } DAO层 public class NreportDaoImpl extends BaseDaoImpl<Nreport> implements NreportDao { @Override public List<Nreport> findNotDoPro() { Calendar c=new GregorianCalendar();//新建日期对象 int year=c.get(Calendar.YEAR);//获取年份 int month=c.get(Calendar.MONTH);/ // 获取当前年份 int year=c.get(Calendar.YEAR); // sql语句 select proid from record where state=1 and (year like '%2015%') // 从【记录表】查询 出上一年没有完成的记录,然后根据记录从【内部表】查出项目的List List list = getSession().createSQLQuery( "select proid from record where state=0 and deptType = '内部审计' and (year like \'%" + String.valueOf(year-1) + "%\')").list(); // 遍历List然后根据这个id来去查找林外一张表 String sql = "select * from nreport where nid in("; for(int i=0;i<list.size();i++){ // sql = "where id in(1,2,3)"; // 如果当前获取的这个id不是最后一个id,那么加上‘,’ if(list.get(i)!= list.get(list.size()-1)){ sql+=list.get(i)+","; }else{ sql+=list.get(i)+")"; } } System.out.println(sql+"看看sql长啥样"); // 从【内部表】查出未完成项目的List List<Nreport> list2= getSession().createSQLQuery(sql).list(); return list2; } } jsp <form action="" method="post" enctype="multipart/form-data"> <table width="100%" border="0"> <tr class="t_tit"> <td width="40" align="center">序号</td> <td width="80" align="center">项目名称</td> <td width="80" align="center">审计类型</td> <td width="40" align="center">送审金额</td> <td width="40" align="center">预计审计费</td> <td width="160" align="center">预计审计时间</td> <td width="140" align="center">经费来源</td> <td width="100" align="center">资金性质</td> <td width="60" align="center">状态</td> <td width="60" align="center">备注</td> <td width="60" align="center">删除</td> </tr> <!-- 如果有上一年的已经启动但是没有完成的计划也显示在这里 --> <s:iterator value="nreportList" status="st"> ${nreportList[0] } <s:if test="nreportList!=null"> <tr <s:if test="#st.odd">bgcolor="f8f8f8"</s:if> > <td align="center"><s:property value="nid"/></td> <td align="center"><s:property value="proname"/></td> <td align="center"><s:property value="audittype"/></td> <td align="center"><s:property value="ssmoney"/></td> <td align="center"><s:property value="expeauditmoney"/></td> <td align="center"><s:property value="expeaudittime"/></td> <td align="center"><s:property value="moneyfrom"/></td> <td align="center"><s:property value="moneyfunds"/></td> <td align="center"><s:property value="state"/></td> <td align="center"><s:property value="memo"/></td> </tr></s:if> <s:else>没数据?</s:else> </s:iterator> 如果我 我jsp中写成上面这样 ${nreportList[0] } 就会输出toString格式的对象 [Ljava.lang.Object;@20d77d7d 如果写成 ${nreportList[0].getNid }就报错 错误信息: 十一月 17, 2016 5:09:16 下午 org.apache.catalina.core.ApplicationDispatcher invoke 严重: Servlet.service() for servlet jsp threw exception java.lang.NumberFormatException: For input string: "getNid" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at javax.el.ArrayELResolver.coerce(ArrayELResolver.java:161) at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:45) ... ... 页面显示出来表格了,是迭代出来的就是没有数据,都是空的格子 ![图片说明](https://img-ask.csdn.net/upload/201611/17/1479374227_31350.jpg) 求大神指导怎么才能迭代出来数据??? 没有C币 , 下次有了一定加倍赏。。。
jsp+servlet实现分页
我在做jsp+servlet数据分页的时候,无法实现前后翻页, 下面是我的分层结构 jsp [code="java"] <%@page contentType="text/html;charset=gbk" %> <%@page language="java" import="java.util.*" %> <%@ include file="inc/cmnAuthenticate.jsp" %> <%@page language="java" import="ch05.*" %> <% Vector vMails = null; int totalPage=0; int curPage=0; int countPerPage=10; int pageNumber=1; Hashtable myValues = (Hashtable)session.getAttribute(CommonConst.VIEWID_INBOXLIST); if ( myValues != null ) { vMails = (Vector)myValues.get("mails"); if ( vMails == null ) { vMails = new Vector(); } if(myValues.get("totalPage")!=null){ totalPage=((Integer)myValues.get("totalPage")).intValue(); } if(myValues.get("curPage")!=null){ curPage=((Integer)myValues.get("curPage")).intValue(); } } %> <html> <head> <title>收件箱</title> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> <script language="JAVASCRIPT" src="common\cmnScript.js"></script> <script language="JAVASCRIPT" src="inbox.js"></script> <link rel="stylesheet" type="text/css" href="common\cmnStyle.css" TITLE="common"></link> <script language="JAVASCRIPT"> <% if ( session.getAttribute("errMsg") != null ) { %> var sErrMsg = "<%=session.getAttribute("errMsg")%>"; <% } else { %> var sErrMsg = ""; <% } %> </script> </head> <%@ include file="inc/cmnPagePart1.jsp" %> <table border=0 cellpadding=0 cellspacing=0 width=650 align=center> <tr> <td height=15>&nbsp;</td> </tr> <tr> <td height=30>你当前共有 <font color=blue><%=vMails.size()%></font> 封邮件。</td> </tr> <tr> <td> <table border=1 bordercolor="#13A7FD" cellpadding=2 cellspacing=0 width=650 align=center> <tr> <td width=130> <b>发件人</b> </td> <td width=400> <b>主题</b> </td> <td width=120> <b>发信时间</b> </td> </tr> <% if ( vMails.size() > 0 ) { for ( int i=0; i<vMails.size(); i++ ) { if(i<countPerPage){ MailContent mailContent = (MailContent)vMails.get(i); String sFrom = mailContent.getSender(); String sSubject = mailContent.getSubject(); String sSendTime = mailContent.getSendTime(); String sReadFlg = mailContent.getReadFlg(); if ( sReadFlg.equals("0") ) { %> <tr> <td> <b><%=sFrom%></b> </td> <td> <b><a href="javascript:gotoMail('<%=i%>')"><%=sSubject%></a></b> </td> <td> <%=sSendTime%> </td> </tr> <% } else { %> <tr> <td> <%=sFrom%> </td> <td> <a href="javascript:gotoMail('<%=i%>')"><%=sSubject%></a> </td> <td> <%=sSendTime%> </td> </tr> <% } } } } else { %> <tr> <td colspan=3> 没有任何邮件! </td> </tr> <% } %> </table> </td> </tr> <tr> <td height=20>&nbsp;</td> </tr> </table> <form name="form_main" action="servlet/Inbox" method="post" > <input type="hidden" name="mailIndex" value=""> <div align="right"> 共 <font color=blue><%=totalPage%></font> 页,当前是第 <font color=blue><%=(totalPage==0?0:curPage+1)%></font> 页 &nbsp; <% if ( curPage > 0 ) { %> <a href="javascript: gotoPagePosition('0')">首页</a> &nbsp; <a href="javascript: gotoPagePosition('<%=curPage-1%>')">前一页</a> &nbsp; <% } else { %> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; <% } if ( curPage < totalPage-1 ) { %> <a href="javascript: gotoPagePosition('<%=curPage+1%>')">后一页</a> &nbsp; <a href="javascript: gotoPagePosition('<%=totalPage-1%>')">末页</a> &nbsp; <% } else { %> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp; <% } %> <input type="hidden" name="pageId" value="S0101"> <input type="hidden" name="gotoPageNo" value=""> </div> </form> <%@ include file="inc/cmnPagePart2.jsp" %> [/code] servlet [code="java"]/* * This product includes software developed by the * Apache Software Foundation (http://www.apache.org/). */ package ch05.controller; import java.io.*; import java.util.Hashtable; import javax.servlet.*; import javax.servlet.http.*; import ch05.*; import ch05.module.*; /** * 针对收件箱页面的Servlet * @author Administrator * @version 1.0 */ public class Inbox extends HttpServlet implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; public void doGet ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { //设置提交表单的中文编码 request.setCharacterEncoding("GBK"); HttpSession mySession = request.getSession(true); //清空错误消息 mySession.setAttribute("errMsg",""); //是否非法进入本页面 if ( mySession.getAttribute("username") == null ) { response.sendRedirect("/ch05/login.jsp"); return; } //是否进入默认页面 if ( !request.getParameterNames().hasMoreElements() ) { //设置session中的页面值域 mySession.setAttribute(CommonConst.VIEWID_INBOXLIST, new Hashtable() ); //取得最新邮件 MInbox mInbox = new MInbox(); boolean bGetResult = mInbox.getNewestMail( mySession ); String sGotoPage = request.getParameter("gotoPageNo"); Hashtable myValues = (Hashtable)mySession.getAttribute(ch05.CommonConst.VIEWID_INBOXLIST); myValues.put( "curPage", new Integer(sGotoPage) ); mySession.setAttribute("curPage","inbox"); response.sendRedirect("/ch05/inbox.jsp"); return; } //得到用户输入信息 String sMailIndex = request.getParameter("mailIndex"); String sMailOption = request.getParameter("mailOption"); //如果用户是提交表单 if ( sMailIndex != null && sMailIndex.length() > 0 ) { //设置session中的详细页面值域 mySession.setAttribute(CommonConst.VIEWID_INBOXDETAIL, new Hashtable() ); //获得对应的邮件信息 MInbox mInbox = new MInbox(); boolean bGetResult = mInbox.getDetailMail( mySession, sMailIndex ); if ( bGetResult ) { response.sendRedirect("/ch05/inboxDetail.jsp"); } else { response.sendRedirect("/ch05/inbox.jsp"); } } //如果用户是从详细页面迁移过来的 else if ( sMailOption != null && sMailOption.length() > 0 ) { String sSender = request.getParameter("sender"); String sSendTime = request.getParameter("sendTime"); String sSubject = request.getParameter("subject"); String sContent = request.getParameter("content"); //删除邮件 if ( sMailOption.equals("delete") ) { MInbox mInbox = new MInbox(); boolean bDeleteResult = mInbox.deleteMail( mySession, sSender, sSendTime ); mInbox.getNewestMail( mySession ); response.sendRedirect("/ch05/inbox.jsp"); return; } //回复邮件 else if ( sMailOption.equals("reply") ) { //设置session中的写邮件页面值域 mySession.setAttribute(CommonConst.VIEWID_SENDBOXDETAIL, new Hashtable() ); MInbox mInbox = new MInbox(); boolean bReplyResult = mInbox.replyMail( mySession, sSender, sSubject, sContent ); mySession.setAttribute("curPage","composite"); response.sendRedirect("/ch05/composite.jsp"); return; } try { MInbox mInbox=new MInbox(); mInbox.gotoPage(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //如果用户非法进入这个页面 else { response.sendRedirect("/ch05/login.jsp"); } } public void doPost ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doGet( request, response ); } }[/code] 数据库处理 [code="java"]/* * This product includes software developed by the * Apache Software Foundation (http://www.apache.org/). */ package ch05.module; import java.sql.*; import java.util.*; import java.text.*; import javax.mail.*; import javax.mail.internet.*; import javax.servlet.http.*; import ch05.*; /** * 针对收件箱页面的后台处理类 * @author Administrator * @version 1.0 */ public class MInbox { public boolean getNewestMail ( HttpSession mySession ) { //设置用户信息用 Hashtable myValues = (Hashtable)mySession.getAttribute(CommonConst.VIEWID_INBOXLIST); String sHost = ""; String sUser = ""; String sPass = ""; //尝试查找用户邮箱设置 try { //载入SQLServer的JDBC驱动类 Class.forName(CommonConst.DB_DRIVER_CLASSNAME); //获得数据库连接 Connection conn = DriverManager.getConnection( CommonConst.DB_CONN_STRING ); Statement stmt = null; ResultSet rs = null; String sUsername = (String)mySession.getAttribute("username"); try { //设置数据库的rollback点 conn.setAutoCommit(false); //检查数据库中是否已经有该用户的邮箱设置 stmt = conn.createStatement(); //执行SQL语句 String sQuery = "select * from mail_setting where username='" + sUsername + "'"; rs = stmt.executeQuery( sQuery ); if (rs.next() ) { sHost = rs.getString(2); sUser = rs.getString(3); sPass = rs.getString(4); } else { mySession.setAttribute("errMsg","请首先进行邮箱设置!"); return false; } //尝试连接Pop3服务器 Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); //获得收件箱 Store store = session.getStore("pop3"); store.connect( sHost, sUser, sPass); //获得Folder,并按照只读打开 Folder folder = store.getFolder( "INBOX" ); folder.open( Folder.READ_WRITE ); //获得所有邮件,并依次获取内容 Message messages[] = folder.getMessages(); //往数据库中登录 for ( int i=0; i<messages.length; i++ ) { //只要不是html格式,大概没有乱码问题。。。 String sFrom = MailContent.getFrom( messages[i].getFrom()[0].toString() ); String sTo = MailContent.getFrom( messages[i].getRecipients( Message.RecipientType.TO )[0].toString() ); String sDate = (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")).format(messages[i].getSentDate()); String sSubject = messages[i].getSubject(); String sContent = ""; //如果纯文本邮件内容 if ( messages[i].getContent() instanceof String ) { sContent = (String) messages[i].getContent(); } //如果HTML格式邮件内容 else { sContent = ((MimeMultipart)messages[i].getContent()).getBodyPart(0).getContent().toString(); } //插入数据库 String sUpdateQuery = "insert into inbox values('" + sUsername + "', '" + sFrom + "', '" + sTo + "', '" + sDate + "', '" + sSubject + "', '" + sContent + "', '0') "; stmt.executeUpdate( sUpdateQuery ); } conn.commit(); conn.setAutoCommit(true); //删除服务器上的邮件 for ( int i=0; i<messages.length; i++ ) { messages[i].setFlag( Flags.Flag.DELETED, true ); } folder.close(true); store.close(); //重新获取数据库中的所有邮件,并表示在页面上 Vector vMails = new Vector(); sQuery = "select * from inbox where username='" + sUsername + "' order by send_time desc"; rs = stmt.executeQuery( sQuery ); while ( rs.next() ) { String sFrom = rs.getString(2); String sTo = rs.getString(3); String sDate = rs.getString(4); String sSubject = rs.getString(5); String sContent = rs.getString(6); String sReadFlg = rs.getString(7); MailContent mc = new MailContent(); mc.setSender(sFrom); mc.setReceiver(sTo); mc.setSendTime(sDate); mc.setSubject(sSubject); mc.setContent(sContent); mc.setReadFlg(sReadFlg); vMails.add( mc ); } myValues.put( "mails", vMails ); //计算总页数 int countPerPage=10; int totalMail=vMails.size(); int totalPage=0; if(totalMail%countPerPage==0){ totalPage=totalMail/countPerPage; } else{ totalPage=totalMail/countPerPage+1; } int curPage=0; myValues.put("curPage", new Integer(curPage)); myValues.put("totalPage", new Integer(totalPage)); } catch(Exception e) { e.printStackTrace(); mySession.setAttribute("errMsg","查找邮件时出现错误!"); return false; } finally { try { rs.close(); stmt.close(); }catch(Exception ex) { } } }catch(Exception ex) { ex.printStackTrace(); mySession.setAttribute("errMsg","查找邮件时出现错误!"); return false; } return true; } } }[/code] js [code="java"]window.onload = windowLoad; //--------------------------------- //页面载入时调用 function windowLoad() { cmnWindowLoad(); } //查看具体邮件 function gotoMail( index ) { form_main.mailIndex.value = index; form_main.submit(); } //前后翻页 function gotoPagePosition( gotoCount ) { form_main.pageId.value = "goto"; form_main.gotoPageNo.value = gotoCount; form_main.submit(); }[/code]
Java WEB 连接数据库的登录界面失败?
连接数据库是成功的,但是输入用户名和密码后跳转到错误页面 有几段代码不太确定对不对,请帮忙看一看 //login.jsp ``` <form name="form1" method="post" action="manager.do?action=login"> ``` //struts-config.xml ``` <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> ``` //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"); 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"); } } } ``` //ConnDB.java ``` //执行查询语句 public ResultSet executeQuery(String sql) { try { conn=getConnection(); stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); rs=stmt.executeQuery(sql); } catch(SQLException ex){ System.err.println(ex.getMessage()); } return rs; } ``` //ManagerDAO.java ``` //管理员身份验证 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; } ``` 大概应该是这几段代码的原因,但是不清楚应该怎么修改,请帮忙看一下
jsp页面登录错误,doPost代码问题
![图片说明:这是登录界面](https://img-ask.csdn.net/upload/201603/09/1457526889_21465.jpg) ![点登录按钮后,出现下图错误,求大神指教](https://img-ask.csdn.net/upload/201603/09/1457526903_884525.jpg) 这是ManageSevlet.java部分代码: package wyf.zrk; import javax.servlet.http.*; import java.io.*; import javax.servlet.*; import java.util.*; import org.springframework.web.context.support.*; import org.springframework.web.context.*; import org.springframework.beans.factory.*; import java.text.DateFormat; public class ManageServlet extends HttpServlet{ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ this.doPost(request,response); //调用doPost方法 } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ request.setCharacterEncoding("gbk"); //设置请求编码格式 response.setCharacterEncoding("gbk"); //设置响应编码 response.setContentType("text/html;charset=gbk"); //设置请求页面格式 PrintWriter out = response.getWriter(); //得到输出流对象 HttpSession session = request.getSession(); UserBean userBean = (UserBean)session.getAttribute("userBean"); if(userBean==null){ userBean = new UserBean(); } //获取WebApplicationContext WebApplicationContext wac= WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); DButil db = (DButil)wac.getBean("DButil"); DBinsert dbin = (DBinsert)wac.getBean("DBinsert"); DBupdate dbup = (DBupdate)wac.getBean("DBupdate"); DBdelete dbde = (DBdelete)wac.getBean("DBdelete"); String action = request.getParameter("action").trim(); //得到请求动作 if(action.equals("login")){ //动作为登陆时 String aname = request.getParameter("uname").trim();//得到用户名 String apwd = request.getParameter("upwd").trim(); //得到密码 aname = new String(aname.getBytes(),"ISO-8859-1"); //将用户名转码 apwd = new String(apwd.getBytes(),"ISO-8859-1"); //将密码转码 System.out.println(aname+"\t"+apwd); String hql = "from AdminInfo as p "+ //hql语句 "where p.aname='"+aname+"' and p.apwd='"+apwd+"'"; List<AdminInfo> list = (List<AdminInfo>)db.getInfo(hql); String url = ""; //记录提示信息 if(!list.isEmpty()){ AdminInfo ai = list.get(0); url = "/index.jsp"; session.setAttribute("admin",aname); //将管理员名存入session session.setAttribute("alevel",ai.getAlevel()); //将管理员级别存入session } else{ String msg = "对不起,登陆失败!!!"; request.setAttribute("msg",msg); //将错误信息添加到请求中 url = "/info.jsp"; } ServletContext sc = getServletContext(); //得到上下文 RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request,response); //页面跳转 } else if(action.equals("logout")){ //当管理员注销时 request.getSession(true).invalidate(); //使session失效 response.sendRedirect("adminlogin.jsp"); //页面跳转 } 求大神指教,在做一个进销存管理系统,菜鸟一个呀 ![这里是对应的代码段](https://img-ask.csdn.net/upload/201603/10/1457579739_417489.jpg)
servlet调用数据库封装类提示,无法获取Connection对象!!!
servlet调用数据库封装类进行查询时,提示ps = conn.preparedStatement(sql);语句是NUllPOINTEREXCEPTION,但在main方法中测试数据库正常连接 我把有问题的代码提炼成一个新的模板,因为我查了很多,都是说Connection conn对象获取异常。网上说的一些解决办法,我都试过了,如提升Tomcat版本,还是不行。下面的代码中无法获取conn对象,跟我的demo问题一摸一样,不知道如何解决!!! index.jsp文件源码 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <!DOCTYPE HTML> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <% String temp =(String) request.getAttribute("info"); if(temp != null){ out.print(temp); } %> <h1>index.jsp页面!!!</h1> <hr> <form action = "ConnectionServlet" method="post"> <input type ="submit" value = "提交"/> </form> </body> </html> ConnectionServlet.java源码 import java.io.IOException; import java.sql.Connection; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ConnectionServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection conn = ConnectionClass.getConnection(); if(conn != null){ request.setAttribute("info", conn); } else { request.setAttribute("info", "conn为空!!!"); } request.getRequestDispatcher("index.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } } ConnectionClass.java源码 import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionClass { public static Connection getConnection(){ Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","sunliqian"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } } web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true"> <servlet> <servlet-name>ConnectionServlet</servlet-name> <servlet-class>ConnectionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ConnectionServlet</servlet-name> <url-pattern>/ConnectionServlet</url-pattern> </servlet-mapping> </web-app> 求大佬解决!!! 没有金币。。。
怎么maven项目部署之后不能访问servlet?
1.我用的myeclipse,servlet中的是ShowTable.java 在浏览器中能访问src/main/webapp中的index.jsp, 访问路径是http://localhost:8080/magSystem/index.jsp,能够显示出内容; 但是想要用servlet:http://localhost:8080/magSystem/ShowTable却404,还不会报错。。 http://localhost:8080/magSystem/servlet/ShowTable 会显示404并且有错误信息: ``` Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary. java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835) at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455) at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207) at java.sql.DriverManager.getConnection(DriverManager.java:664) at java.sql.DriverManager.getConnection(DriverManager.java:247) at com.zkz.magSystem.dao.BaseDAO.getConnection(BaseDAO.java:16) at com.zkz.magSystem.dao.BaseDAO.runSelect(BaseDAO.java:20) at com.zkz.magSystem.servlet.ShowTable.service(ShowTable.java:43) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2234) at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2258) at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319) at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966) at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ... 31 more ``` 我的其他配置以及目录如下: ## web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>ShowTable</servlet-name> <display-name>This is the display name of my J2EE component</display-name> <description>This is the description of my J2EE component</description> <servlet-class>com.zkz.magSystem.servlet.ShowTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowTable</servlet-name> <url-pattern>/servlet/ShowTable</url-pattern> </servlet-mapping> </web-app> ``` ## ShowTable.java ``` package com.zkz.magSystem.servlet; import java.io.IOException; 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.jsp.jstl.sql.Result; import com.zkz.magSystem.dao.BaseDAO; @WebServlet("/uploadsevlet") public class ShowTable extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * Constructor of the object. */ public ShowTable() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub try { Result result = BaseDAO.runSelect("select * from ex1"); request.setAttribute("rows", result.getRows()); request.getRequestDispatcher("index.jsp").forward(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); response.sendRedirect("error.jsp"); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } } ``` ## BaseDAO.java ``` package com.zkz.magSystem.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.jsp.jstl.sql.Result; import javax.servlet.jsp.jstl.sql.ResultSupport; public class BaseDAO { public static Connection getConnection() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection("jdbc:mysql://localhost:3306/exam","root","qianmoZONGHENG"); } public static Result runSelect(String sql) throws Exception{ Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); //将在线结果集转化为离线结果集 Result result = ResultSupport.toResult(rs); close(conn,ps,rs); return result; } //数据库关闭语句 public static void close(Connection conn, PreparedStatement ps, ResultSet rs) { try { if (rs != null) { rs.close(); rs = null; } if (ps != null) { ps.close(); ps = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException se) { se.printStackTrace(); } } } ``` ## index.jsp ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ taglib prefix = "c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.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> <table> <tr> <th>编号</th> <th>姓名</th> <th>电话</th> <th>状态</th> </tr> <c:forEach var="row" items="${rows }"> <tr> <td>${row.id }</td> <td>${row.name }/td> <td>${row.phone }</td> <td>${row.state }</td> </tr> </c:forEach> </table> </body> </html> ``` ![图片说明](https://img-ask.csdn.net/upload/201905/07/1557239537_160797.png) ![图片说明](https://img-ask.csdn.net/upload/201905/07/1557239544_525903.png)
java web怎样实现商品分类显示
自己写了一个小的javaweb项目,用的jsp+servlet。 想实现商品的分类显示,但是不知道怎样从jsp页面传值给dao层,以及查询语句怎么写? 求大神帮助。 这是jsp页面: ``` <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <%@ page import="cn.edu.qust.bookcitys.entity.Items"%> <%@ page import="cn.edu.qust.bookcitys.dao.ItemsDao"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>展示</title> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/common.css" rel="stylesheet"> <link href="css/show.css" rel="stylesheet"> </head> <body> <header> <!-- logo --> <div class="index-header-top"> <img src="images/logo.png" class="logo"> </div> <!--导航栏--> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <ul class="nav navbar-nav"> <li><a href="index.jsp">首页</a></li> <li class="active"><a href="show.jsp" target="_self">展示</a></li> <li><a href="cart.jsp" target="_self">购物车</a></li> <li><a href="login.jsp" target="_self">登录</a></li> </ul> </div> </nav> </header> <div class="details_container"> <div class="details_left"> <dl> <dt class="book"> <a href="show.jsp?sort=1">文学</a> </dt> <dd> <a href="#">作品集</a> </dd> <dd> <a href="#">名著</a> </dd> <dd> <a href="#">小说</a> </dd> </dl> <dl> <dt class="xbook"> <a href="show.jsp?sort=2">青春</a> </dt> <dd> <a href="#">青春</a> </dd> <dd> <a href="#">励志</a> </dd> <dd> <a href="#">校园</a> </dd> </dl> <dl> <dt class="book"> <a href="show.jsp?sort=3">生活</a> </dt> <dd> <a href="#">作品集</a> </dd> <dd> <a href="#">名著</a> </dd> <dd> <a href="#">小说</a> </dd> </dl> </div> <div class="details_right"> <div style="width: 1000px;"> <% ItemsDao itemsDao = new ItemsDao(); String sort = request.getParameter("sort"); ArrayList<Items> list = itemsDao.getAllItems(); if (list != null && list.size() > 0) { for (int i = 0; i < list.size(); i++) { Items item = list.get(i); request.setAttribute("item",item); %> <div style="width: 180px; height: 220px; float: left;"> <a href="details.jsp?id=${item.id }"><img style="float: left;" src="images/${item.picture }" width="170px" height="120px" border="1" /></a> <span style="float: left; margin: 5px 0px 0px 5px; color: blue">${item.name }</span> <span style="float: left; margin: 5px 0px 0px 5px; color: #000">作者:${item.author }&nbsp;&nbsp; 价格: ${item.price }¥ </span> </div> <% } } %> </div> </div> </div> <div class="details_bottom"> <footer> Copyright &copy; Made By 泥石流 </footer> </div> <!-- 如果要使用Bootstrap的js插件,必须先调入jQuery --> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script> <!-- 包括所有bootstrap的js插件或者可以根据需要使用的js插件调用 --> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </body> </html> ``` ``` 这是dao层: package cn.edu.qust.bookcitys.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import cn.edu.qust.bookcitys.entity.Items; import cn.edu.qust.bookcitys.util.DBHelper; //商品的业务逻辑类 public class ItemsDao { //获得所有的商品信息 public ArrayList<Items> getAllItems(){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; ArrayList<Items> list = new ArrayList<Items>();//商品集合 try{ conn = DBHelper.getConnection(); // String sql = "select * from items where sort=?;";//sql语句 String sql = "select * from items ;";//sql语句 stmt = conn.prepareStatement(sql); // stmt.setInt(1, sort); rs = stmt.executeQuery(); while(rs.next()){ Items item = new Items(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setAuthor(rs.getString("author")); item.setNumber(rs.getInt("number")); item.setPrice(rs.getInt("price")); item.setPicture(rs.getString("picture")); item.setSort(rs.getInt("sort")); list.add(item);//每次遍历把一个商品加入集合 } return list; } catch(Exception e){ e.printStackTrace(); return null; } finally{ //释放数据集对象 if(rs!=null){ try{ rs.close(); rs = null; } catch(Exception e){ e.printStackTrace(); } } //释放语句对象 if(stmt!=null){ try{ stmt.close(); stmt = null; } catch(Exception e){ e.printStackTrace(); } } } } //根据商品编号获得商品资料 public Items getItemsById(int id){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try{ conn = DBHelper.getConnection(); String sql = "select * from items where id=?;";//sql语句 stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); if(rs.next()){ Items item = new Items(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setAuthor(rs.getString("author")); item.setNumber(rs.getInt("number")); item.setPrice(rs.getInt("price"));; item.setPicture(rs.getString("picture")); item.setSort(rs.getInt("sort")); return item; } else{ return null; } } catch(Exception e){ e.printStackTrace(); return null; } finally{ //释放数据集对象 if(rs!=null){ try{ rs.close(); rs = null; } catch(Exception e){ e.printStackTrace(); } } //释放语句对象 if(stmt!=null){ try{ stmt.close(); stmt = null; } catch(Exception e){ e.printStackTrace(); } } } } //获取最近浏览的前3条信息 public ArrayList<Items> getViewList(String list){ System.out.println("list:"+list); ArrayList<Items> itemlist = new ArrayList<Items>(); int iCount = 3; if(list!=null&&list.length()>0){ String[] arr = list.split("#"); System.out.println("arr.length="+arr.length); //如果商品记录大于等于3条 if(arr.length>=3){ for(int i=arr.length-1;i>=arr.length-iCount;i--){ itemlist.add(getItemsById(Integer.parseInt(arr[i]))); } } else{ for(int i = arr.length-1;i>=0;i--){ itemlist.add(getItemsById(Integer.parseInt(arr[i]))); } } return itemlist; } else{ return null; } } } ``` ``` 想把sort的值传到dao层并实现分类显示。
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什么的不怎么懂,来请教下各位我哪里有问题,解决方法或者说解决思路应该是怎样的
Servlet遇到java.lang.NullPointerException问题无法解决,恳求帮助
各位大佬,最近用Jsp+servlet写教务管理系统,其中servlet端有一个问题始终无法解决 ``` 严重: Servlet.service() for servlet [com.jwglxt.data.searchStudent] in context with path [/jwglxt] threw exception java.lang.NullPointerException ``` 目的是根据从前台传来的查询类型和查询关键词在数据库中进行检索,目前前后端数据传递正常,NullPointerException这个问题始终得不到解决,尝试了很多办法都不行,恳请各位大佬施以援手! 代码如下: ```java package com.jwglxt.data; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; 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 org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; //思路:绑定一个弹出框在“搜索”按钮上,弹出框里放置一个datagrid,url为searchStudent @WebServlet("/searchStudent") public class searchStudent extends HttpServlet { @SuppressWarnings({ "null", "null", "null" }) protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码格式 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/json; charset=utf-8"); //获取学生信息主码-学号(sno) String name=request.getParameter("name"); System.out.println("搜索类型:"+name); String value=request.getParameter("value"); System.out.println("搜索值:"+value); //姑且赋值 /*String name="sno"; String value="990101";*/ //连接数据库 Connection connection=null; String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";//SQL数据库引擎 String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=tjl";//数据源 !!!注意若出现加载或者连接数据库失败一般是这里出现问题 String Name="sa"; String Pwd="19990713"; ResultSet rs=null; String sql="sql"; //定义JSON数组,用于保存从数据库查出来的数据 JSONArray array = new JSONArray(); try { Class.forName(driverName); connection=DriverManager.getConnection(dbURL,Name,Pwd); System.out.println("搜索学生:连接数据库成功"); } catch (ClassNotFoundException e2) { e2.printStackTrace(); }catch (SQLException e) { e.printStackTrace(); } //处理搜索类型 尝试switch语句 /*switch(name) { case "sno":{ try { sql="select * from student where sno=?"; connection.prepareStatement(sql); pstmt.setString(1,value); //rs=pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); };break; }//case }//switch */ //处理搜索类型 尝试If语句 if(name!=null) { if("sno".equals(name)){ try { //仅构造SQL语句,暂不运行 sql="select * from student where sno=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } else if("sname".equals(name)){ try { //仅构造SQL语句,暂不运行 sql="select * from student where sname=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } else if("sex".equals(name)){ try { //仅构造SQL语句,暂不运行 sql="select * from student where sex=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } else if("dno".equals(name)){ try { //仅构造SQL语句,暂不运行 sql="select * from student where dno=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } else { try { //仅构造SQL语句,暂不运行 sql="select * from student where dormno=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } System.out.println(sql); } try { // 获取列数 ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); while (rs.next()) { JSONObject jsonObj = new JSONObject(); // 遍历每一列 for (int i = 1; i <= columnCount; i++) { String columnName =metaData.getColumnLabel(i); String value2 = rs.getString(columnName); try { jsonObj.put(columnName, value2); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } array.put(jsonObj); } } catch (SQLException e1) { e1.printStackTrace(); } //关闭 try { if(rs!=null) rs.close(); //pstmt.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } //PrintWriter out = response.getWriter(); System.out.println(array); }//总类 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public static void main(String args[]) { searchStudent ss=new searchStudent(); try { ss.doGet(null, null); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ```
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
我在支付宝花了1分钟,查到了女朋友的开房记录!
在大数据时代下,不管你做什么都会留下蛛丝马迹,只要学会把各种软件运用到极致,捉奸简直轻而易举。今天就来给大家分享一下,什么叫大数据抓出轨。据史料证明,马爸爸年轻时曾被...
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
20道你必须要背会的微服务面试题,面试一定会被问到
写在前面: 在学习springcloud之前大家一定要先了解下,常见的面试题有那块,然后我们带着问题去学习这个微服务技术,那么就会更加理解springcloud技术。如果你已经学了springcloud,那么在准备面试的时候,一定要看看看这些面试题。 文章目录1、什么是微服务?2、微服务之间是如何通讯的?3、springcloud 与dubbo有哪些区别?4、请谈谈对SpringBoot 和S...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
2020 年,大火的 Python 和 JavaScript 是否会被取而代之?
Python 和 JavaScript 是目前最火的两大编程语言,但是2020 年,什么编程语言将会取而代之呢? 作者 |Richard Kenneth Eng 译者 |明明如月,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: Python 和 JavaScript 是目前最火的两大编程语言。然而,他们不可能永远屹立不倒。最终,必将像其他编程语言一...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
最全最强!世界大学计算机专业排名总结!
我正在参与CSDN200进20,希望得到您的支持,扫码续投票5次。感谢您! (为表示感谢,您投票后私信我,我把我总结的人工智能手推笔记和思维导图发送给您,感谢!) 目录 泰晤士高等教育世界大学排名 QS 世界大学排名 US News 世界大学排名 世界大学学术排名(Academic Ranking of World Universities) 泰晤士高等教育世界大学排名 中国共...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
使用 Python 和百度语音识别生成视频字幕
文章目录从视频中提取音频根据静音对音频分段使用百度语音识别获取 Access Token使用 Raw 数据进行合成生成字幕总结 从视频中提取音频 安装 moviepy pip install moviepy 相关代码: audio_file = work_path + '\\out.wav' video = VideoFileClip(video_file) video.audio.write_...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
那个在阿里养猪的工程师,5年了……
简介: 在阿里,走过1825天,没有趴下,依旧斗志满满,被称为“五年陈”。他们会被授予一枚戒指,过程就叫做“授戒仪式”。今天,咱们听听阿里的那些“五年陈”们的故事。 下一个五年,猪圈见! 我就是那个在养猪场里敲代码的工程师,一年多前我和20位工程师去了四川的猪场,出发前总架构师慷慨激昂的说:同学们,中国的养猪产业将因为我们而改变。但到了猪场,发现根本不是那么回事:要个WIFI,没有;...
为什么程序猿都不愿意去外包?
分享外包的组织架构,盈利模式,亲身经历,以及根据一些外包朋友的反馈,写了这篇文章 ,希望对正在找工作的老铁有所帮助
Java校招入职华为,半年后我跑路了
何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...
世界上有哪些代码量很少,但很牛逼很经典的算法或项目案例?
点击上方蓝字设为星标下面开始今天的学习~今天分享四个代码量很少,但很牛逼很经典的算法或项目案例。1、no code 项目地址:https://github.com/kelseyhight...
Python全栈 Linux基础之3.Linux常用命令
Linux对文件(包括目录)有很多常用命令,可以加快开发效率:ls是列出当前目录下的文件列表,选项有-a、-l、-h,还可以使用通配符;c功能是跳转目录,可以使用相对路径和绝对路径;mkdir命令创建一个新的目录,有-p选项,rm删除文件或目录,有-f、-r选项;cp用于复制文件,有-i、-r选项,tree命令可以将目录结构显示出来(树状显示),有-d选项,mv用来移动文件/目录,有-i选项;cat查看文件内容,more分屏显示文件内容,grep搜索内容;>、>>将执行结果重定向到一个文件;|用于管道输出。
立即提问