servlet读取jsp中的file内容

jsp提交form表单的时候servlet接收时候怎么接收file信息,又怎么读取,怎么获取file的文件流,怎么获得file要求不使用框架,使用原生态方法解决问题

3个回答

HANLIPENGHANLIPENG
小牛学堂2019 谢谢
3 年多之前 回复
HANLIPENGHANLIPENG
小牛学堂2019 谢谢
3 年多之前 回复

这还不是使用了jar工具包,其实本质是获取请求的输入流,然后将输入流写入到输出流文件:

request.getInputStream();, 可以参考下这篇博客:http://www.cnblogs.com/goodwin/archive/2010/09/28/1837387.html

很简单直接request获取输入流,过得页面输入的字节数组,然后对其进行解析就可以得到你要的一切页面数据

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
支付宝接口jsp页面无法读取zfbinfo.properties文件
同样的方法,通过JSP无法读取,但是调用mian方法却能读取到。 而且jsp昨天是可以读取到的。 方法: Configs.init("zfbinfo.properties"); 异常提示: org.apache.jasper.JasperException: java.lang.IllegalStateException: can`t find file by path:zfbinfo.properties org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:556) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
HTTP Status 500 - Servlet.init()
HTTP Status 500 - Servlet.init() for servlet springmvc threw exception type Exception report message Servlet.init() for servlet springmvc threw exception description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exception org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745) root cause java.lang.IllegalArgumentException org.springframework.asm.ClassReader.<init>(Unknown Source) org.springframework.asm.ClassReader.<init>(Unknown Source) org.springframework.asm.ClassReader.<init>(Unknown Source) org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52) org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76) org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298) org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230) org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153) org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130) org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285) org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223) org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745) note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs. 请指点这是什么原因造成的哦,我在myeclipse开启tomcat就不会出现此错误 web中的配置是 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvcfirst1208</display-name> <!-- 加载spring的容器读取speing下面的配置文件 --> <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmvc前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- post乱码过虑器 --> <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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
用file上传的服务器,存到数据库中
jsp :代码 ``` <div class="main"> <h2>添加商品</h2> <div class="manage"> <form enctype="multipart/form-data" method="post" action="/emw/XFL.do" > <table class="form"> <tr> <td class="field">商品名称:</td> <td><input type="text" id="spmic" class="text" name="productName" onblur="return check()"/></td> </tr> <tr> <td class="field">所属分类:</td> <td> <select name="parentId"> <% List<XLm> li=new XLmBizimpl().getAll(); for(XLm n:li){ %> <option value="<%=n.getXflid() %>"><%=n.getXflname() %></option> <% } %> </select> </td> </tr> <tr> <td class="field">商品图片:</td> <td><input type="file" id="photo" class="text" name="filepath" /></td> </tr> <tr> <td class="field">商品价格:</td> <td><input type="text" id="jiage" class="text tiny" name="jiage" onblur="return moing()" /> 元</td> </tr> <tr> <td class="field">库存:</td> <td><input type="text" id="kucun" class="text tiny" name="kuchun" onblur="return moing1()" /></td> </tr> <tr> <td class="field">条码号:</td> <td><input type="text" id="tiaoma" class="text" name="tiaoma" onblur="return moing2()"/></td> </tr> <tr> <td></td> <td><label class="ui-blue"><input type="submit" name="submit" value="添加" /></label></td> </tr> </table> </form> ``` sevlre: package com.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.PageContext; import com.biz.impl.GoodsBizimpl; import com.biz.impl.XLmBizimpl; import com.entity.Goods; import com.entity.XLm; import com.jspsmart.upload.Files; import com.jspsmart.upload.SmartUpload; public class XFL extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String productName=request.getParameter("productName"); int parentId=Integer.parseInt(request.getParameter("parentId")); //String filepath=request.getParameter("filepath"); //int jiage=Integer.parseInt( request.getParameter("jiage")); double jiage=Double.parseDouble(request.getParameter("jiage")); int kuchun=Integer.parseInt( request.getParameter("kuchun")); String tiaoma=request.getParameter("tiaoma"); //创建一个上传的组件 SmartUpload su = new SmartUpload(); //初始化SmartUpload对象(重) su.initialize(JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8*1024, true)); //pageContext上下文 -- application com.jspsmart.upload.File file = null; //非IO包下的File类 String filepath = null; com.jspsmart.upload.Request req = null; //定义允许上传类型 String allowed = "gif,jpg,png,txt"; //定义不许上传类型 String denied = "jsp,asp,php,aspx,html,htm,exe,bat"; //文件上传类型,二选一,一般会选择允许上传类型 //定义上传文件大小 int file_size = 5*1024*1024; //不能超过2M String exceptionMsg = null; //异常信息对象 //int i = 0; try { //定义允许上传文件类型 su.setAllowedFilesList(allowed); //不允许上传文件类型 su.setDeniedFilesList(denied); //单个文件最大限制 su.setMaxFileSize(file_size); //设置上传对象的编码 su.setCharset("utf-8"); //GBK GB2312 //执行上传(重) su.upload(); //路径 //得到单个上传文件的信息 //file = su.getFiles().getFile(0); //su.getFiles()获得所有文件对象 //su.getFiles()获得所有文件对象 Files f= su.getFiles(); //循环读取文件对象 for(int i=0; i<f.getCount(); i++){ //取文件对象 file=f.getFile(i); //判断是否有对象 if(!file.isMissing()){ //设置文件在服务器的保存位置 filepath = "upload\\"; //保存到一个upload的文件夹下 //filepath += file.getFileName(); //拼接文件名字 filepath += System.currentTimeMillis()+ file.getFileName().substring( file.getFileName().lastIndexOf(".")); //文件另存为 file.setCharset("utf-8"); //保存(重) file.saveAs(filepath, SmartUpload.SAVE_VIRTUAL); //上传模式 } } } catch (Exception e) { exceptionMsg = e.getMessage(); e.printStackTrace(); } response.getWriter().print(filepath); System.out.println(productName+" "+ parentId+" "+ filepath+" "+ jiage +" "+kuchun +" "+tiaoma); } } 错误:SEVERE: Servlet.service() for servlet [XFL] in context with path [/emw] threw exception java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at com.servlet.XFL.doPost(XFL.java:42) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) 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.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) 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:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2517) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2506) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) -- 问题:获取的值是空值
jsp上传文件页面报无法解析的编译问题
index.jsp <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <html> <head> <title>带进度条的文件上传</title> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <link href="CSS/style.css" rel="stylesheet"> <script language="javascript" src="JS/AjaxRequest.js"></script> <script language="javascript"> //此处需要加&nocache="+new Date().getTime(),否则将出现进度不更新的情况 function getProgress(){ var loader=new net.AjaxRequest("showProgress.jsp?nocache="+new Date().getTime(),deal_p,onerror,"GET"); } function onerror(){ alert("上传文件出错!"); } function deal_p(){ var h=this.req.responseText; h=h.replace(/\s/g,""); //去除字符串中的Unicode空白符 document.getElementById("progressPercent").style.display=""; //显示百分比 progressPercent.innerHTML=h+"%"; //显示完成的百分比 document.getElementById("progressBar").style.display="block"; //显示进度条 document.getElementById("imgProgress").width=h*(255/100); //显示完成的进度 } function deal(form){ form.submit(); //提交表单 timer=window.setInterval("getProgress()",500); //每隔500毫秒获取一次上传进度 } </script> </head> <body> <form name="form1" enctype="multipart/form-data" method="post" action="UpLoad?action=uploadFile"> <table width="500" height="289" border="0" align="center" cellpadding="0" cellspacing="0" background="images/bg.jpg"> <tr> <td width="61" rowspan="2">&nbsp;</td> <td width="439" align="center"> <table width="80%" height="190" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center">&nbsp;</td> </tr> <tr> <td height="34" style="color:#FFFFFF">请选择上传的文件:</td> </tr> <tr> <td height="42"><input name="file" type="file" size="42"></td> </tr> <tr> <td height="50" style="color:#FFFFFF"> 注:文件大小请控制在50M以内。</td> </tr> <tr> <td height="29" align="center" style="color:#FFFFFF"><div id="progressBar" class="prog_border" align="left"><img src="images/progressBar.jpg" width="0" height="13" id="imgProgress"></div>  <span id="progressPercent" style="width:40px;display:none">0%</span></td> </tr> <tr> <td height="29" align="center"><img src="images/shangchuan.gif" width="61" height="23" onClick="deal(form1)"> <img src="images/chongzhi.gif" width="61" height="23" onClick="form1.reset();">&nbsp; </td></tr> </table> </td> </tr> </table> </form> </body> </html> upload.java package com.wgh.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * * @author administrator */ public class UpLoad extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if ("uploadFile".equals(action)) { this.uploadFile(request, response); // 上传文件 } } public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=GBK"); request.setCharacterEncoding("GBK"); HttpSession session = request.getSession(); session.setAttribute("progressBar", 0); // 定义指定上传进度的Session变量 String error = ""; int maxSize = 50 * 1024 * 1024; // 单个上传文件大小的上限 DiskFileItemFactory factory = new DiskFileItemFactory(); // 基于磁盘文件项目创建一个工厂对象 ServletFileUpload upload = new ServletFileUpload(factory); // 创建一个新的文件上传对象 try { List items = upload.parseRequest(request);// 解析上传请求 Iterator itr = items.iterator();// 枚举方法 while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // 获取FileItem对象 if (!item.isFormField()) {// 判断是否为文件域 if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件 long upFileSize = item.getSize(); // 上传文件的大小 String fileName = item.getName(); // 获取文件名 // System.out.println("上传文件的大小:" + item.getSize()); if (upFileSize > maxSize) { error = "您上传的文件太大,请选择不超过50M的文件"; break; } // 此时文件暂存在服务器的内存中 File tempFile = new File(fileName);// 构造临时对象 // String savePath=tempFile.getName(); // //返回上传文件在客户端的完整路径名称 // request.setAttribute("filename", savePath); File file = new File(request.getRealPath("/upload"), tempFile.getName()); // 获取根目录对应的真实物理路径 InputStream is = item.getInputStream(); int buffer = 1024; // 定义缓冲区的大小 int length = 0; byte[] b = new byte[buffer]; double percent = 0; FileOutputStream fos = new FileOutputStream(file); while ((length = is.read(b)) != -1) { percent += length / (double) upFileSize * 100D; // 计算上传文件的百分比 fos.write(b, 0, length); // 向文件输出流写读取的数据 session.setAttribute("progressBar", Math .round(percent)); // 将上传百分比保存到Session中 } fos.close(); Thread.sleep(1000); // 线程休眠1秒 } else { error = "没有选择上传文件!"; } } } } catch (Exception e) { e.printStackTrace(); error = "上传文件出现错误:" + e.getMessage(); } if (!"".equals(error)) { request.setAttribute("error", error); request.getRequestDispatcher("error.jsp") .forward(request, response); } else { request.setAttribute("result", "文件上传成功!"); request.getRequestDispatcher("upFile_deal.jsp").forward(request, response); } } } 问题 java.lang.Error: 无法解析的编译问题: 无法解析导入 org.apache.commons.fileupload.disk 无法解析导入 org.apache.commons.fileupload.servlet DiskFileItemFactory 无法解析为类型 DiskFileItemFactory 无法解析为类型 ServletFileUpload 无法解析为类型 ServletFileUpload 无法解析为类型 com.wgh.servlet.UpLoad.<init>(UpLoad.java:15) sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:423) java.lang.Class.newInstance(Class.java:442) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879) org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:610) org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1777) java.lang.Thread.run(Thread.java:745) 求救
java读取gif图片后,重新写一个gif图片,此图片没有动画效果
我用java读取一个gif图片,把它再重新写一个gif图片,但是新写出来的图片就没有动画了,为什么?? 急用 大家帮帮忙 我刚开始是这样写的,运行生成的gif图片不能看 List < BufferedImage > images = new ArrayList<BufferedImage>(); try{ File file=new File("e:\\awkoe.gif"); java.util.Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("gif"); ImageReader imageReader = (ImageReader)imageReaders.next(); imageReader.setInput(ImageIO.createImageInputStream(file)); for(int i = 0;true;++i){ try{ BufferedImage aa=imageReader.read(i); images.add(aa); }catch (Exception e) { break; } } BufferedImage[] bufimages= images.toArray(new BufferedImage[images.size()]); Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("gif"); ImageWriter imageWriter = (ImageWriter)imageWriters.next(); File outfile=new File("d:\\aa.gif"); outfile.delete(); imageWriter.setOutput(ImageIO.createImageOutputStream(outfile)); if(imageWriter.canWriteSequence()){ imageWriter.prepareWriteSequence(null); for(int i = 0;i < bufimages.length;++i){ imageWriter.writeToSequence(new IIOImage(bufimages[i],null,null),null); } imageWriter.endWriteSequence(); }else{ for(int i = 0;i < bufimages.length;++i){ imageWriter.write(bufimages[i]); } } }catch (Exception e) { e.printStackTrace(); } 现在用这个方法,生成的gif可以看,但是他不是动画 try { File file=new File("d:\\aa.gif"); Image image=ImageIO.read(new File("e:\\awkoe.gif")); GifEncoder encoder = new GifEncoder(image,new FileOutputStream(file)); encoder.encode(); } catch (Exception e) { } 请大家帮忙 谢谢 [b]问题补充:[/b] 我要的不是在本机移动, 我需要在一个jsp页面上有个 <img src='/image'>标签,他提交到一个servlet, 在servlet中读取本地的一个gif图片,把它返回到jsp页面。 这样怎么弄? [b]问题补充:[/b] 谢谢 stephen830 帮忙写点代码吧 过着说一下思路 急用 谢谢
javaWeb项目本地的文件下载没问题,部署到服务器上就无法文件下载
下载文件的代码如下: 项目在本地调试的时候,是可以正常下载本地磁盘的文件的,然后我部署到一台远程机器上,所要下载的文件能够得到他的路径,但是也不报错就是页面没有下载到文件,这是为什么? 备注:1.我在浏览器去访问那个文件的路径,404访问不到,虽然在WEB-INF下面放着。 访问路径:http://10.10.3.149:8080/alitm/WEB-INF/upload/d9209cf6856e427495dd78e4cf3d24d3_result.csv [b]package com.ecsemir.utils; import com.ecsemir.entity.ExceptUpload; import org.springframework.context.annotation.Scope; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by zhuxiaofan01 on 2017/11/7. * 文件上传 */ @Scope("prototype") public class DownloadFile { public static void getDownloadFile(HttpServletRequest request, HttpServletResponse response,ExceptUpload exceptUpload) throws IOException, ServletException { //得到要下载的文件路径 String fpath = exceptUpload.getPath_resultCsv(); String filepath = request.getSession().getServletContext().getRealPath(fpath); //获取时间 String res; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); String time=simpleDateFormat.format(new Date()); //得到文件名 int index1=filepath.lastIndexOf("_"); int index2=filepath.lastIndexOf("."); String fileName=time+filepath.substring(index1+1,index2)+".csv"; System.out.println("---------------------------fileName:"+fileName+"-----------------"+filepath); fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8"); //得到要下载的文件 File file = new File(filepath); //如果文件不存在 if (!file.exists()) { request.setAttribute("message", "您要下载的资源已被删除!!"); request.getRequestDispatcher("/except/downloadlist.jsp").forward(request, response); return; } //设置响应头,控制浏览器下载该文件 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); //读取要下载的文件,保存到文件输入流 FileInputStream in = new FileInputStream(file); //创建输出流 OutputStream out = response.getOutputStream(); //创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; //循环将输入流中的内容读取到缓冲区当中 while ((len = in.read(buffer)) > 0) { //输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } //关闭文件输入流 in.close(); //关闭输出流 out.close(); } }[/b]
Springmvc上传文件限制大小,异常处理返回报错信息后,eclipse控制台还报错
**1、web.xml配置:** ``` <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 注册主控制器DispatcherServlet --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定spring配置文件位置 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.from</url-pattern> </servlet-mapping> <!-- 指定读取所有文件的编码格式 --> <filter> <filter-name>encodingFilter</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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` **spring的applicationContext.xml配置:** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 定义自动扫描组件 --> <context:component-scan base-package="controller"></context:component-scan> <!-- 定义@RequestMapping映射的注解驱动 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 定义视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <!-- 注册spring web mvc中处理上传事件的组件CommonsMultipartResolver, 而具体怎样处理上传文件,则是由导入的包common-upload.jar和common-io.jar去处理--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10240"></property> <property name="resolveLazily" value="true"></property> </bean> </beans> ``` **java代码Controller处理:** ``` package controller; import java.io.File; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class UploadController { // 访问upload.jsp页面 @RequestMapping("/toUpload") public String toUpload() { return "upload"; } @RequestMapping("/upload") public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, ModelMap model) throws Exception { // 判断提交来的文件是否为空 if (file.isEmpty()) { // model.addAttribute("error", "上传文件不能为空"); // return "upload"; throw new RuntimeException("file is null"); } // 获取文件所要保存目录在服务器上所对应的实际路径 String path = request.getSession().getServletContext().getRealPath( "upload"); System.out.println(path); // 组成拥有真实路径的一个完整的地址字符串 String fileUrl = path + "\\" + file.getOriginalFilename(); // 封装上传文件名称到model对象中 model.addAttribute("fileName", file.getOriginalFilename()); // 根据这个完整地址字符串,生成提交文件所要保存到的目标文件或目录的对象 File targetFile = new File(fileUrl); // 判断目标文件或目录的对象是否已经存在 if (!targetFile.exists()) { targetFile.mkdirs(); } // 传送文件到目标对象 file.transferTo(targetFile); System.out.println("已上传文件:" + file); return "ok"; } @ExceptionHandler public ModelAndView doException(Exception e,HttpServletRequest request) throws Exception { Map<String,Object> map = new HashMap<String,Object>(); if (e instanceof MaxUploadSizeExceededException) { long maxSize = ((MaxUploadSizeExceededException) e) .getMaxUploadSize(); map.put("error", "上传文件太大,不能超过" + maxSize / 1024 + "k"); }else if(e instanceof RuntimeException){ map.put("error", "未选中文件"); }else{ map.put("error", "上传失败"); } return new ModelAndView("upload",map); } } ``` **上传文件页面upload.jsp:** ``` <%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>上传页面</title> </head> <body> <form action="upload.from" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="上传"/><font color="red">${error}</font> </form> </body> </html> ``` **上传成功页面ok.jsp:** ``` <%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ok.jsp</title> </head> <body> <h1>上传成功</h1> <a href="upload/${fileName}">${fileName}</a> </body> </html> ``` **eclipse控制台报错信息如下:** ``` 五月 01, 2015 10:27:01 下午 org.springframework.web.multipart.commons.CommonsMultipartResolver cleanupMultipart 警告: Failed to perform multipart cleanup for servlet request org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 10240 bytes exceeded; nested exception is org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (19243) exceeds the configured maximum (10240) at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:160) at org.springframework.web.multipart.commons.CommonsMultipartResolver$1.initializeMultipart(CommonsMultipartResolver.java:131) at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultipartFiles(AbstractMultipartHttpServletRequest.java:119) at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultiFileMap(AbstractMultipartHttpServletRequest.java:99) at org.springframework.web.multipart.commons.CommonsMultipartResolver.cleanupMultipart(CommonsMultipartResolver.java:188) at org.springframework.web.servlet.DispatcherServlet.cleanupMultipart(DispatcherServlet.java:1062) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:955) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829) 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:88) 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:220) 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:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2476) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2465) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (19243) exceeds the configured maximum (10240) at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:914) at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331) at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:349) at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126) at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156) ... 37 more ``` 上传文件超过限制大小,异常处理后页面返回了提示信息“上传文件太大,不能超过10k”,但是为啥eclipse的控制台还是有报错呢?
jsp中使用JavaBean出现“引用类不可用”
do_upload.jsp [code="java"]<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB2312"%> <%@ page import="org.apache.commons.fileupload.*"%> <%@ page import="org.apache.commons.fileupload.servlet.*"%> <%@ page import="org.apache.commons.fileupload.disk.*"%> <%@ page import="java.util.*"%> <%@ page import="java.io.*"%> <%@ page import="picDeal.*" %> <jsp:useBean id="pic" scope="page" class="picDeal.PicRgb"> </jsp:useBean> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>文件上传</title> </head> <body> <center>上传中.....</center> <% String uploadPath=application.getRealPath("/upload"); String picName=null; int width=0,height=0; //目标文件夹的路径必须使用绝对路径,不能用相对路径 boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart==true){ try{ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request);//得到所有的文件 Iterator<FileItem> itr = items.iterator(); while(itr.hasNext()){//依次处理每个文件 FileItem item=(FileItem)itr.next(); String fileName=item.getName();//获得文件名,包括路径 if(fileName!=null) { File fullFile=new File(item.getName()); picName=fullFile.getName(); File savedFile=new File(uploadPath,fullFile.getName()); item.write(savedFile); } } out.println("upload succeed!"); out.println("上传的图片如下:"); //分析图片, 获取图片的信息 pic.setData(picName); session.setAttribute("picture",pic); %> <form action="anaresult.jsp" method="post"> <table> <tr> <td>上传的图片如下:</td> </tr> <tr> <td><img src=<%= "upload/"+picName %>></td> </tr> <tr> <td><input type="submit" name="submit" value="提交分析"></td> </tr> </table> </form> <% } catch(Exception e){ e.printStackTrace(); out.print("failed!"); } } else{ out.println("the enctype must be multipart/form-data"); } %> </body> </html> [/code] PicRgb [code="java"]package picDeal; import java.awt.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; public class PicRgb { private int []rData; private int []gData; private int []bData; private int width; private int height; //分析图片,参数为图片的名字 public PicRgb() { } public void setData(String name){ Image image=null; try{ File sourceimage = new File("upload/"+name); image=ImageIO.read(sourceimage); } catch(IOException e){ } //读取图像的高度&宽度 this.width=image.getWidth(null); this.height=image.getHeight(null); System.out.println(width); System.out.println(height); //读取图片像素信息 Image im=Toolkit.getDefaultToolkit().getImage("upload/"+name); this.rData=new int[256]; this.gData=new int[256]; this.bData=new int[256]; int []pixels=new int[width*height]; try{ PixelGrabber pg=new PixelGrabber(im,0,0,width,height,pixels,0,width); pg.grabPixels(); }catch(InterruptedException e){ e.printStackTrace(); } ColorModel cm=ColorModel.getRGBdefault(); int red,green,blue; for(int i=0;i<width*height;i++){ red=cm.getRed(pixels[i]); this.rData[red]++; green=cm.getGreen(pixels[i]); this.gData[green]++; blue=cm.getBlue(pixels[i]); this.bData[blue]++; } } public void setRData(int[] r) { this.rData=r; } public void setGData(int[] g) { this.gData=g; } public void setBData(int[] b) { this.bData=b; } public void setWidth(int w) { this.width=w; } public void setHeight(int h) { this.height=h; } public int getWidth() { return this.width; } public int getHeight() { return this.height; } public int[] getRData() { return this.rData; } public int[] getGData() { return this.gData; } public int[] getBData() { return this.bData; } } [/code] 当使用up_load.jsp页面时 出现错误 提示 useBean使用的类不可用……弄了一下午,头都大了 - -
ssm 整合 service层使用Autowired注入dao 报红,可以使用,为什么?
![图片说明](https://img-ask.csdn.net/upload/201712/11/1512966681_57369.png) ### applicationContext.xml 配置 ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 读取数据库配置文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 启动上下文的注解配置 --> <context:annotation-config/> <!-- 扫描含有注解的包 --> <context:component-scan base-package="niit.dxs.lehuSSM.service"/> <!-- 配置数据源,使用阿里巴巴的druid数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!--初始化大小--><property name="initialSize" value="20"/> <!--连接池最大使用连接数量--> <property name="maxActive" value="20"/> <!--连接池最小空闲--> <property name="minIdle" value="0"/> <!--配置获取连接等待超时的时间--> <property name="maxWait" value="60000"/> <!--配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒--> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!--配置一个连接在池中最小生存的时间,单位是毫秒--> <property name="minEvictableIdleTimeMillis" value="300000"/> <!--连接空闲时测试是否有效--> <property name="testWhileIdle" value="false"/> <!--获取连接时测试是否有效--> <property name="testOnBorrow" value="false"/> <!--归还连接时是否测试有效--> <property name="testOnReturn" value="false"/> <!--打开PSCache缓存,并且指定每个连接上PSCache的大小--> <property name="poolPreparedStatements" value="true"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> </bean> <!-- 配置 mybatis 的SessionFactory 实例 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 指定映射文件位置 --> <property name="mapperLocations" value="classpath*:/niit/dxs/lehuSSM/mapper/*.xml"/> <!-- 指定别名 --> <property name="typeAliasesPackage" value="niit.dxs.lehuSSM.domain"/> </bean> <!--配置DAO接口所在的包--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="niit.dxs.lehuSSM.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!--配置一个事务管理器的bean --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> <!--配置声明式事务,在使用处加注解@Transactional--> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <!--用于文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" p:maxUploadSize="5242880"/> </beans> ``` ### spring_mvc-servlet.xml 配置 ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--启动MVC注解--> <mvc:annotation-driven/> <!--扫描含有注解的包,(控制器所在的包)--> <context:component-scan base-package="niit.dxs.lehuSSM.controller"/> <!--配置视图解析器,指定视图所在路径,视图文件后缀名--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/" p:suffix=".jsp"/> <!--保证静态资源不被拦截--> <mvc:default-servlet-handler/> <!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor> <!-- 表示拦截所有 --> <mvc:mapping path="/**"/> <!--<mvc:exclude-mapping path="/css/*.css"/>--> <!-- 指定拦截器 --> <bean class="niit.dxs.lehuSSM.interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> </beans> ``` ### web.xml 配置 ```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 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"> <display-name>lehuSSM</display-name> <!--默认启动页--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml,classpath:spring_mvc-servlet.xml</param-value> </context-param> <!-- 过滤器统一编码 --> <filter> <filter-name>Spring character encoding</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>Spring character encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring容器配置 ,当服务器启动,加载web.xml配置文件--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 控制器 当服务器启动,加载spring_mvc-servlet.xml配置文件--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring_mvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- mvc控制器映射 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ```
关于下载中文名称文件浏览器显示500
**DownServlet** public class DownServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request.setCharacterEncoding("utf-8"); // response.setContentType("text/html;charset=utf-8"); System.out.println("已经收到要下载的文件名称啦。。。。"); // 1 获取客户端请求下载的文件名称. String filename = request.getParameter("filename"); // 解决GET方式请求的参数中文乱码问题: filename = new String(filename.getBytes("ISO-8859-1"), "utf-8"); // 2 通过文件名称,查询数据表. QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource()); String sql = "SELECT * FROM filesave WHERE filename=?"; try { FileSave filesave = runner.query(sql, new BeanHandler<FileSave>(FileSave.class), filename); // 3 通过查询到的保存路径,读取具体文件. InputStream in = new FileInputStream(new File(filesave.getSavepath())); // 4 获取服务器端的响应输出流 OutputStream out = response.getOutputStream(); // 获取客户端请求头中的User-Agent String userAgent = request.getHeader("User-Agent"); if (userAgent.contains("MSIE")) { // IE浏览器 filename = URLEncoder.encode(filename, "utf-8"); filename = filename.replace("+", " "); } else { // 其他浏览器 BASE64Encoder base64Encoder = new BASE64Encoder(); filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?="; } /* * 通知浏览器:文件是需要下载的,而不是显示的. * 为下载设置ContentType和Content-Disposition */ response.setContentType(getServletContext().getMimeType(filename)); response.setHeader("Content-Disposition", "attachment;filename=" + filename); // 5 利用IOUtils工具类的copy()方法 IOUtils.copy(in, out); // 6 释放资源 in.close(); // out.close(); } catch (SQLException e) { e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` ``` **download.jsp** a href="${pageContext.request.contextPath }/servlet/DownServlet?filename=黑臀.jpg">黑臀.jpg</a> a href="${pageContext.request.contextPath }/servlet/DownServlet?filename=哈哈.xls">2.xls</a> a href="${pageContext.request.contextPath }/servlet/DownServlet?filename=3.html">3.html<a><br> a href="${pageContext.request.contextPath }/servlet/DownServlet?filename=4.txt">4.txt</a> ``` ```
spring整合mybatis问题
在进行spring/mybatis/springmvc整合的时候jsp调用controller方法时报错,求大神指导 报错信息 ``` ### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver' ### The error may exist in file [D:\workSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\springMvc\WEB-INF\classes\springMvc\mapper\mapper.xml] ### The error may involve springMvc.mapper.StudentMapper.getStudentById ### The error occurred while executing a query ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'] with root cause java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167) at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420) at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371) at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) at org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:82) at org.mybatis.spring.transaction.SpringManagedTransaction.getConnection(SpringManagedTransaction.java:68) at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:337) at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:84) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:62) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:325) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433) at com.sun.proxy.$Proxy11.selectOne(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:166) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53) at com.sun.proxy.$Proxy12.getStudentById(Unknown Source) at springMvc.service.impl.StudentServiceImpl.getStudentById(StudentServiceImpl.java:15) at springMvc.controller.testController.queryStudentById(testController.java:115) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:854) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:765) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) 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:622) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1519) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1475) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) ``` applicationContext.xml ``` <!-- 读取数据库配置文件 --> <bean id="config" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="location"> <value>classpath:resource/db.propertis</value> </property> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> ``` jar包 ![图片说明](https://img-ask.csdn.net/upload/201907/04/1562236859_41209.png) properties文件 ``` jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8 jdbc.username=root jdbc.password=123456 ```
tomcat启动struts1.3项目超时,如何解决?
我的struts1.3项目在以前的网络(A城市的电信)下是启动起来的,现在换了网络(B城市的移动)启动不起来了,我在怀疑是不是eclipse读取dtd文件的时候太慢了。导致启动失败,在工作过程中,我也有tomcat启动超过45秒的情况,一般是把tomcat timeout配置更长,可是这很不科学,因为他在启动的时候就卡住了,你把tomcat启动允许最大时间配置的再长也无法。 控制台输出如下: ``` 九月 05, 2016 9:29:17 下午 org.apache.catalina.core.AprLifecycleListener init 信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\jdk\jdk_7u79\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/jdk/jdk_7u79/bin/../jre/bin/client;C:/jdk/jdk_7u79/bin/../jre/bin;C:/jdk/jdk_7u79/bin/../jre/lib/i386;D:\app\Administrator\product\11.2.0\dbhome_1\bin;C:\jdk\jdk_7u79\bin;C:\Windows\System32;C:\Program Files\Subversion\bin;C:\Program Files\TortoiseSVN\bin;D:\maven\apache-maven-3.3.9\bin;;C:\Windows;C:\Windows\system32\wbem;D:\mysql-5.6.24-win32\bin;c:\Program Files\Microsoft SQL Server\90\Tools\binn\;D:\JavaTools\eclipse;;. 九月 05, 2016 9:29:18 下午 org.apache.tomcat.util.digester.SetPropertiesRule begin 警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:FileUpdateAndDownload' did not find a matching property. 九月 05, 2016 9:29:19 下午 org.apache.coyote.http11.Http11Protocol init 信息: Initializing Coyote HTTP/1.1 on http-6789 九月 05, 2016 9:29:19 下午 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 2486 ms 九月 05, 2016 9:29:19 下午 org.apache.catalina.core.StandardService start 信息: Starting service Catalina 九月 05, 2016 9:29:19 下午 org.apache.catalina.core.StandardEngine start 信息: Starting Servlet Engine: Apache Tomcat/6.0.44 九月 05, 2016 9:29:21 下午 org.apache.struts.action.ActionServlet initChain 信息: Loading chain catalog from jar:file:/D:/JavaProgram/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/FileUpdateAndDownload/WEB-INF/lib/struts-core-1.3.10.jar!/org/apache/struts/chain/chain-config.xml ``` 我的struts-config.xml配置如下: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-Apache Software Foundation//DTD struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <!-- 配置表单 --> <form-beans> <form-bean name="loginForm" type="com.shizongger.web.form.LoginForm" /> </form-beans> <!-- 配置action --> <action-mappings> <action path="/login" name="loginForm" type="com.shizongger.web.action.LoginAction" > <forward name="success" path="WEB-INF/users/main.jsp" /> <forward name="fail" path="WEB-INF/users/login.jsp" /> </action> </action-mappings> </struts-config> ``` web.xml配置如下: ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/config/struts-config.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> ```
fileupload 为什么InputStream getInputStream()方法无法获取临时文件里的文件
package com.wgh.servlet; import java.io.*; import java.util.*; import org.apache.commons.fileupload.*; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet("/UploadServlet") public class UploadServlet 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 { String uploadPath=getServletContext().getRealPath("/")+"upload"; //定义上传文件的地址 System.out.println(uploadPath); File folder = new File(uploadPath); if(!folder.exists()) folder.mkdirs(); String message=null; String content=null; String dtme=null; if(ServletFileUpload.isMultipartContent(request)){ //判断是否获取的是文件 System.out.print("是文件"); DiskFileItemFactory disk=new DiskFileItemFactory(); disk.setSizeThreshold(20*1024); //设置内存可存字节数 disk.setRepository(disk.getRepository()); //设置临时文件目录 ServletFileUpload up=new ServletFileUpload(disk); int maxsize=2*1024*1024; List list=null; try{ list=up.parseRequest(request); //获取上传列表 } catch(Exception e){ e.printStackTrace(); } Iterator i=list.iterator(); //创建列表的迭代器 while(i.hasNext()){ FileItem fm=(FileItem)i.next(); //遍历列表 if(!fm.isFormField()){ String filePath = fm.getName(); //获取文件全路径名 String fileName=""; int startIndex = filePath.lastIndexOf("\\"); if(startIndex!=-1){ //对文件名进行截取 fileName = filePath.substring(startIndex+1); }else{ fileName=filePath; } if(fm.getSize()>maxsize){ message="文件太大了,不要超过2MB"; break; } String fileSize=new Long(fm.getSize()).toString(); if((fileName==null)||(fileName.equals(""))&&(fileSize.equals("0"))){ message="文件名不能为空,文件大小也不能为零!"; break; } File saveFile=new File(uploadPath,fileName); System.out.println(uploadPath); try{ fm.write(saveFile); //向文件中写入数据 message="文件上传成功!"; <span style="color: #FF0000;">InputStream inStream=fm.getInputStream();</span>//这行报错 System.out.println("hhhhhh"); } catch(Exception e1){ e1.printStackTrace(); } } else{ String foename=fm.getFieldName(); //获取表单元素名 String con=fm.getString("UTF-8"); //获取表单内容,注意编码方式 //表单元素 if(foename.equals("upDe")){ content = con; System.out.println("ok1"); } else if(foename.equals("uptime")){ dtme = con; System.out.println("ok2"); } } } } else { System.out.println("不是文件"); } request.setAttribute("result",message); request.setAttribute("upDe",content); request.setAttribute("dtme",dtme); RequestDispatcher rd=request.getRequestDispatcher("message.jsp"); rd.forward(request, response); } public void init(ServletConfig config) throws ServletException { super.init(config); } } 当文件超过20k时就会报错, java.io.FileNotFoundException: C:\Users\wsn\AppData\Local\Temp\upload__1c3b5e7d_1476c27ed8a__7fff_00000006.tmp (系统找不到指定的文件。) 到底是怎样读取临时文件的文件流呢 这是index.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>通过commons-fileupload获取其他表单元素</title> <style type="text/css"> table{ font-size: 13px; } input{ font-size: 12px; } </style> </head> <body> <%! Date now=new Date(); String form=String.format("%tF",now); %> <form method="post" action="UploadServlet" enctype="multipart/form-data"> <table background="bg.jpg" width="400" height="200"> <tr> <td height="20" colspan="2"></td> </tr> <tr> <td align="center" colspan="2">【应用Commons-FileUpload获取其他表单元素】</td> </tr> <tr> <td height="20" colspan="2"></td> </tr> <tr> <td align="right">选择文件:</td> <td > <input type="file" name="file1"></td> </tr> <tr> <td align="right">文件描述:</td> <td > <input type="text" name="upDe" ></td> </tr> <tr> <td align="right">上传时间:</td> <td > <input type="text" name="uptime" value=<%=form%>></td> </tr> <tr> <td align="center"></td> <td > <input type="submit" value="开始上传"></td> </tr> <tr> <td height="40" colspan="2"></td> </tr> </table> </form> </body> </html>
做了一个简单的SSH应用,但启动tomcat时总抛NoClassDefFoundError异常
做了一个简单的SSH应用,但启动tomcat时总抛NoClassDefFoundError异常。 <br />会有<pre name="code" class="java">java.lang.ClassNotFoundException: javax.transaction.TransactionManager</pre> <br />各位一定要帮看看啊!(ssh未入门级) <br /> <br />开发工具:Eclipse3.2+Tomcat5.5+Mysql5.0 <br />建表 <br /><pre name="code" class="java">CREATE TABLE `people` ( `id` int(11) NOT NULL auto_increment, `name` varchar(100) default NULL, `location` varchar(100) default NULL, PRIMARY KEY (`id`) ) </pre> <br /> <br />首先,建立工程和package,以下是我的工程目录 <br />  action <br />      DeletePeopleAction.java     //删除人员action <br />      EditPeopleAction.java         //编辑人员action第一步,读取需要修改的人员资料 <br />       EditPeopleActionDo.java   //修改人员action <br />      ListPeopleAction.javaSave   //显示人员列表action <br />      SavePeopleAction.java         //新增人员action <br />      SearchPeopleAction.java     //查找人员action <br />dao <br />      IDAO.java    //数据库操作接口 <br />       StudentDAOImpl.java  //数据库操作实现 <br />domain <br />      AbstractPeople.java   //实体抽象类 <br />       People.hbm.xml         //数据库映射 <br />       People.java                 //实体类 <br />service <br />      IService.java   //服务层接口 <br />       StudentManagerImpl.java   //服务层实现 <br />util <br />     Character.java   //字符编码过滤器 <br />      PageSupport.java   //分页 <br />applicationContext.xml   //Spring配置文件(hibernate部分和Service部分) <br /> <br />JSP:不详细些了。 <br />   addStudent.jsp <br />   editStudent.jsp <br />   searchList.jsp <br />   searchStudent.jsp <br />   studentList.jsp <br /> <br />我觉得问题就出在 Spring 的xml部署上, <br />或者是我引入的包有冲突,要么就是根本不对。 <br />下面是应用的配置信息: <br />1.web.xml <br /><pre name="code" class="java"><!----> &lt;web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/classes/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;resource-ref&gt; &lt;description&gt;SqlServer Datasource example&lt;/description&gt; &lt;res-ref-name&gt;jdbc/StudentManager&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;res-auth&gt;Container&lt;/res-auth&gt; &lt;/resource-ref&gt; &lt;filter&gt; &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt; &lt;filter-class&gt; org.springframework.orm.hibernate3.support.OpenSessionInViewFilter &lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;singleSession&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;SpringContextServlet&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.context.ContextLoaderServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;SpringLog4jConfigServlet&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.util.Log4jConfigServlet &lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;web&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.servlet.DispatcherServlet &lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;action&lt;/servlet-name&gt; &lt;servlet-class&gt;org.apache.struts.action.ActionServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;config&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;debug&lt;/param-name&gt; &lt;param-value&gt;2&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;detail&lt;/param-name&gt; &lt;param-value&gt;2&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;2&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;action&lt;/servlet-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;/WEB-INF/jsp/index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-bean.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-bean.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-html.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-html.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-logic.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-logic.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-nested.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-nested.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;/web-app&gt; </pre> <br /> <br />2.struts-config.xml <br /><pre name="code" class="java"><!----> &lt;struts-config&gt; &lt;data-sources&gt; &lt;form-beans&gt; &lt;form-bean name="people" type="domain.People"&gt;&lt;/form-bean&gt; &lt;/form-beans&gt; &lt;global-exceptions&gt; &lt;global-forwards&gt; &lt;action-mappings&gt; &lt;action path="/savePeople" name="people" type="action.SavePeopleAction" scope="session" parameter="method"&gt; &lt;forward name="success" path="/listPeople.do"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/listPeople" name="people" type="action.ListPeopleAction"&gt; &lt;forward name="success" path="/studentList.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/deletePeople" name="people" type="action.DeletePeopleAction"&gt; &lt;forward name="success" path="/studentList.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/editPeople" name="people" type="action.EditPeopleAction"&gt; &lt;forward name="success" path="/editStudent.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/editPeopleDo" name="people" type="action.EditPeopleActionDo"&gt; &lt;forward name="success" path="/studentList.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/searchPeople" name="people" type="action.SearchPeopleAction"&gt; &lt;forward name="success" path="/searchList.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/test" name="people" type="action.Test"&gt;&lt;/action&gt; &lt;/action-mappings&gt; &lt;controller locale="true"&gt; &lt;message-resources parameter=""&gt; <!----> &lt;/struts-config&gt; </pre> <br /> <br /> <br />3.applicationContext.xml <br /><pre name="code" class="java"><!----> &lt;beans&gt; <!----> &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" depends-on="sessionFactory"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory"&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="studentManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"&gt; &lt;property name="transactionManager"&gt; &lt;ref bean="transactionManager"&gt;&lt;/ref&gt; &lt;/property&gt; &lt;property name="target"&gt; &lt;bean class="service.StudentManagerImpl"&gt; &lt;property name="studentDAO"&gt; &lt;ref bean="StudentDAO"&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/property&gt; &lt;property name="transactionAttributes"&gt; &lt;props&gt; &lt;prop key="save*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;prop key="list*"&gt;PROPAGATION_REQUIRED,readOnly&lt;/prop&gt; &lt;prop key="delete*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;prop key="get*"&gt;PROPAGATION_REQUIRED,readOnly&lt;/prop&gt; &lt;prop key="edit*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;prop key="search*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="proxyTargetClass"&gt; &lt;value&gt;true&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; <!----> &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName"&gt; &lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt; &lt;/property&gt; &lt;property name="url"&gt; &lt;value&gt;jdbc:mysql://localhost:3306/dbjee&lt;/value&gt; &lt;/property&gt; &lt;property name="username"&gt; &lt;value&gt;root&lt;/value&gt; &lt;/property&gt; &lt;property name="password"&gt; &lt;value&gt;123456&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; <!----> &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;property name="dataSource"&gt; &lt;ref local="dataSource"&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.cache.use_query_cache"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.cache.provider_class"&gt; org.hibernate.cache.HashtableCacheProvider&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; <!----> &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt;domain/People.hbm.xml&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="StudentDAO" class="dao.StudentDAOImpl"&gt; &lt;property name="sessionFactory"&gt; &lt;ref local="sessionFactory"&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </pre> <br /> <br />4.People.hbm.xml <br /><pre name="code" class="java"><!----> <!----> &lt;hibernate-mapping package="domain"&gt; &lt;class name="People" table="people"&gt; &lt;id name="id" type="java.lang.Integer"&gt; &lt;column name="id"&gt; &lt;generator class="increment"&gt;&lt;/generator&gt; &lt;/id&gt; &lt;property name="name" type="java.lang.String"&gt; &lt;column name="name" length="100"&gt; &lt;/property&gt; &lt;property name="location" type="java.lang.String"&gt; &lt;column name="location" length="100"&gt; &lt;/property&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </pre> <br /> <br /> <br /><span style="font-size: large;">附件里是我引入的jar包。 <br />希望各位能帮帮忙,困扰我2天,一直出不来。</span> <br /> <br />最后把启动Tomcat时报的错误也贴出来。 <br /><pre name="code" class="java">严重: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager java.lang.NoClassDefFoundError: javax/transaction/TransactionManager at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.getDeclaredMethods(Unknown Source) at java.beans.Introspector$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.beans.Introspector.getPublicDeclaredMethods(Unknown Source) at java.beans.Introspector.getTargetMethodInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at org.springframework.beans.CachedIntrospectionResults.&lt;init&gt;(CachedIntrospectionResults.java:149) at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:85) at org.springframework.beans.BeanWrapperImpl.setIntrospectionClass(BeanWrapperImpl.java:234) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:192) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:176) at org.springframework.beans.BeanWrapperImpl.&lt;init&gt;(BeanWrapperImpl.java:129) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:491) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:366) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:330) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:283) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:321) at org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:139) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:252) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190) at org.springframework.web.context.ContextLoaderServlet.init(ContextLoaderServlet.java:83) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:448) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 55 more 2008-11-14 20:08:31 org.apache.catalina.core.ApplicationContext log 严重: StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager java.lang.NoClassDefFoundError: javax/transaction/TransactionManager at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.getDeclaredMethods(Unknown Source) at java.beans.Introspector$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.beans.Introspector.getPublicDeclaredMethods(Unknown Source) at java.beans.Introspector.getTargetMethodInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at org.springframework.beans.CachedIntrospectionResults.&lt;init&gt;(CachedIntrospectionResults.java:149) at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:85) at org.springframework.beans.BeanWrapperImpl.setIntrospectionClass(BeanWrapperImpl.java:234) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:192) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:176) at org.springframework.beans.BeanWrapperImpl.&lt;init&gt;(BeanWrapperImpl.java:129) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:491) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:366) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:330) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:283) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:321) at org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:139) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:252) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190) at org.springframework.web.context.ContextLoaderServlet.init(ContextLoaderServlet.java:83) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:448) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 55 more 2008-11-14 20:08:31 org.apache.catalina.core.StandardContext loadOnStartup 严重: Servlet /SSHDemo threw load() exception java.lang.ClassNotFoundException: javax.transaction.TransactionManager at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232) at java.lang.ClassLoader.loadClassInternal(Unknown Source) at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.getDeclaredMethods(Unknown Source) at java.beans.Introspector$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.beans.Introspector.getPublicDeclaredMethods(Unknown Source) at java.beans.Introspector.getTargetMethodInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at org.springframework.beans.CachedIntrospectionResults.&lt;init&gt;(CachedIntrospectionResults.java:149) at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:85) at org.springframework.beans.BeanWrapperImpl.setIntrospectionClass(BeanWrapperImpl.java:234) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:192) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:176) at org.springframework.beans.BeanWrapperImpl.&lt;init&gt;(BeanWrapperImpl.java:129) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:491) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:366) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:330) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:283) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:321) at org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:139) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:252) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190) at org.springframework.web.context.ContextLoaderServlet.init(ContextLoaderServlet.java:83) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:448) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) 2008-11-14 20:08:32 org.apache.coyote.http11.Http11BaseProtocol start 信息: Starting Coyote HTTP/1.1 on http-8888 2008-11-14 20:08:32 org.apache.jk.common.ChannelSocket init </pre><br /><strong>问题补充</strong><br /><div class="quote_title">zzxplayful 写道</div><div class="quote_div">没有这个包 <br />java.lang.ClassNotFoundException: javax.transaction.TransactionManager  </div> <br />这段异常我看得懂, <br />包括下面的: <br /><pre name="code" class="java">org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager</pre> <br /> <br />都看得懂,我想知道的是解决办法。 <br />比如 <br />javax.transaction.TransactionManager <br />在什么包里? <br />要怎样解决?<br /><strong>问题补充</strong><br /><div class="quote_title">fywcc 写道</div><div class="quote_div">这个是spring里面的  你把SPRING的jar包重新覆盖进去试试</div> <br /> <br />我在Spring包里看了啊, <br />源码都是以 org.springframework.×××× 开始的啊, <br />没有 javax.transcation.** 啊, <br />怎么办?还是需要什么别的包,要么是我的包冲突了。 <br /> <br />我引入了: <br />antlr <br />commons-beanutils.jar <br />commons-digester.jar <br />commons-fileupload.jar <br />commons-logging.jar <br />commons-validator.jar <br />jakarta-oro.jar <br />struts.jar <br /> <br />spring.jar <br /> <br />hibernate3.jar<br /><strong>问题补充</strong><br /><div class="quote_title">jones 写道</div><div class="quote_div">放入jta.jar就行了,找找吧,spring里面应该有,要不就是Hibernate里面有</div> <br />谢谢你。 <br />我把缺少的包都放上了,终于启动Tomcat时候不抛异常,而且也能打开welcome页面了。 <br /> <br />但还有其他问题,明天搞。 <br /> <br />第一次搞SSH,多谢指点啊!
Spring集成Hibernate,使用JPA注解方式,新增数据无法提交
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>环境:</p> <p style="padding-left: 60px;">spring 3.1</p> <p style="padding-left: 60px;">hibernate 4.2.8 final </p> <p style="padding-left: 60px;">mysql 5.6</p> <p>问题描述:</p> <p style="padding-left: 30px;">调用controller的查询方法,可以正常返回数据</p> <p style="padding-left: 30px;">调用controller的创建方法,即:新增数据,控制台打印出了读取和修改序号表的sql,但是没有打印插入数据的sql,数据库表中也没有新增数据。</p> <p style="padding-left: 30px;">怀疑是spring控制的事务没有提交,但是排查了两三天,从网上找了各种方法,都没有解决问题。</p> <p style="padding-left: 30px;">请各位大侠拉小弟一把,实在是找不到事务为什么没有提交。</p> <p> </p> <p style="padding-left: 30px;">web.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;!-- 欢迎界面 --&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;!-- spring框架 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 上下文配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/applicationContext.xml, /WEB-INF/config/**/*.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- spring mvc --&gt; &lt;servlet&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;!-- 拦截所有url --&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- 回话有效期30分钟 --&gt; &lt;session-config&gt; &lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;/session-config&gt; &lt;!-- log4j日志 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- log4j日志配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/properties/log4j.properties&lt;/param-value&gt; &lt;/context-param&gt; &lt;/web-app&gt;</pre> <p> applicationContext.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 注解配置 --&gt; &lt;context:annotation-config /&gt; &lt;!--允许使用注解方式配置事务 --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 对标注@PersistenceContext的类经行增强,引入代理后的EntityManager实例 --&gt; &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&gt; &lt;!-- 对标注@Repository的类经行增强,将EntityManager异常转换为SpringDAO体系的异常 --&gt; &lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /&gt; &lt;!-- 属性文件 --&gt; &lt;context:property-placeholder location="/WEB-INF/properties/**/*.properties" /&gt; &lt;!-- 数据源 --&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;!-- JPA 实体管理工厂 --&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="persistenceUnitName" value="ServicePlatform" /&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt; &lt;property name="showSql" value="true" /&gt; &lt;property name="generateDdl" value="true" /&gt; &lt;property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- JPA 事务管理 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> dispatcher-servlet.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 默认的注解映射的支持 --&gt; &lt;mvc:annotation-driven /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 配置一下对json数据的转换 &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="messageConverters"&gt; &lt;list&gt; &lt;bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"&gt;&lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; --&gt; &lt;!-- 视图解析器 --&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/view" /&gt; &lt;property name="suffix" value=".jsp" /&gt; &lt;/bean&gt; &lt;!-- 对静态资源文件的访问 方案一 (二选一) --&gt; &lt;mvc:default-servlet-handler /&gt; &lt;!-- 对静态资源文件的访问 方案二 (二选一) &lt;mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/&gt; --&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">persistence.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"&gt; &lt;persistence-unit name="ServicePlatform" transaction-type="RESOURCE_LOCAL"&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">实体bean</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.entity; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "bd_id") public class Identity implements Serializable { private static final long serialVersionUID = -8763611811485844772L; @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @Column(length = 100) private String code; private Long value; @Column(length = 10) private String prefix; @Column(length = 10) private String suffix; @Column(length = 255) private String description; private Integer length; @Column(length = 30) private String creator; @Column(name = "create_date") private Timestamp createDate; @Column(length = 30) private String modifier; @Column(name = "modify_Date") private Timestamp modifyDate; private Boolean dr; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public Timestamp getModifyDate() { return modifyDate; } public void setModifyDate(Timestamp modifyDate) { this.modifyDate = modifyDate; } public Boolean getDr() { return dr; } public void setDr(Boolean dr) { this.dr = dr; } @Override public String toString() { return "Identity [id=" + id + ", code=" + code + ", value=" + value + ", prefix=" + prefix + ", suffix=" + suffix + ", description=" + description + ", length=" + length + ", creator=" + creator + ", createDate=" + createDate + ", modifier=" + modifier + ", modifyDate=" + modifyDate + ", dr=" + dr + "]"; } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">IdentityDaoImpl.java</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.dao; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.entity.Identity; @Repository public class IdentityDaoImpl implements IIdentityDao { @PersistenceContext private EntityManager em; @Transactional(propagation = Propagation.REQUIRED) public Identity create(Identity data) { em.persist(data); return data; } @Override public Identity retriver(String id) throws ServicePlatformException { Long pk = Long.valueOf(id); return em.find(Identity.class, pk); } @Override public Identity update(Identity data) throws ServicePlatformException { em.persist(data); return data; } @Override public void delete(String id) throws ServicePlatformException { em.remove(retriver(id)); } } </pre> <p> IdentityController.java</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.controller; import java.sql.Timestamp; import java.util.Calendar; import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.dao.IIdentityDao; import com.lxl.bsp.identity.entity.Identity; @Controller @RequestMapping("identity") public class IdentityController { private static Log log = LogFactory.getLog(IdentityController.class); @Resource private IIdentityDao dao; @RequestMapping("retriver") @ResponseBody public Identity retriver(@RequestParam String id) throws ServicePlatformException { return dao.retriver(id); } @RequestMapping("create") @ResponseBody public Identity create() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("code" + i); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.create(data); log.debug(returnData); return returnData; } @RequestMapping("update") @ResponseBody public Identity update() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("1"); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.update(data); log.debug(returnData); return returnData; } @RequestMapping("delete") public void delete(@RequestParam String id) throws ServicePlatformException { dao.delete(id); } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">数据表结构DDL</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="sql">-- ---------------------------- -- Table structure for bd_id -- ---------------------------- DROP TABLE IF EXISTS `bd_id`; CREATE TABLE `bd_id` ( `id` bigint(30) NOT NULL, `code` varchar(100) DEFAULT NULL, `create_date` datetime DEFAULT NULL, `creator` varchar(30) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `dr` tinyint(1) DEFAULT NULL, `length` int(11) DEFAULT NULL, `modifier` varchar(30) DEFAULT NULL, `modify_Date` datetime DEFAULT NULL, `prefix` varchar(10) DEFAULT NULL, `suffix` varchar(10) DEFAULT NULL, `value` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">附件中是项目压缩包,只要电脑上安装了数据库,解压即可运行,数据库名称是osd</p> <p> </p> </div>
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、PDF搜索网站推荐 对于大部
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入  假设现有4个人
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
【图解经典算法题】如何用一行代码解决约瑟夫环问题
约瑟夫环问题算是很经典的题了,估计大家都听说过,然后我就在一次笔试中遇到了,下面我就用 3 种方法来详细讲解一下这道题,最后一种方法学了之后保证让你可以让你装逼。 问题描述:编号为 1-N 的 N 个士兵围坐在一起形成一个圆圈,从编号为 1 的士兵开始依次报数(1,2,3…这样依次报),数到 m 的 士兵会被杀死出列,之后的士兵再从 1 开始报数。直到最后剩下一士兵,求这个士兵的编号。 1、方
致 Python 初学者
文章目录1. 前言2. 明确学习目标,不急于求成,不好高骛远3. 在开始学习 Python 之前,你需要做一些准备2.1 Python 的各种发行版2.2 安装 Python2.3 选择一款趁手的开发工具3. 习惯使用IDLE,这是学习python最好的方式4. 严格遵从编码规范5. 代码的运行、调试5. 模块管理5.1 同时安装了py2/py35.2 使用Anaconda,或者通过IDE来安装模
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
      11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下
日均350000亿接入量,腾讯TubeMQ性能超过Kafka
整理 | 夕颜出品 | AI科技大本营(ID:rgznai100) 【导读】近日,腾讯开源动作不断,相继开源了分布式消息中间件TubeMQ,基于最主流的 OpenJDK8开发的
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
so easy! 10行代码写个"狗屁不通"文章生成器
前几天,GitHub 有个开源项目特别火,只要输入标题就可以生成一篇长长的文章。背后实现代码一定很复杂吧,里面一定有很多高深莫测的机器学习等复杂算法不过,当我看了源代码之后这程序不到50
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
MySQL数据库总结
文章目录一、数据库简介二、MySQL数据类型(5.5版本)三、Sql语句(1)Sql语句简介(2)数据定义语言DDLcreate,alter,drop(3)数据操纵语言DMLupdate,insert,delete(4)数据控制语言DCLgrant,revoke(5)数据查询语言DQLselect(6)分组查询与分页查询group by,limit四、完整性约束(单表)五、多表查询六、MySQL数
记一次腾讯面试:进程之间究竟有哪些通信方式?如何通信? ---- 告别死记硬背
有一次面试的时候,被问到进程之间有哪些通信方式,不过由于之前没深入思考且整理过,说的并不好。想必大家也都知道进程有哪些通信方式,可是我猜很多人都是靠着”背“来记忆的,所以今天的这篇文章,讲给大家详细着讲解他们是如何通信的,让大家尽量能够理解他们之间的区别、优缺点等,这样的话,以后面试官让你举例子,你也能够顺手拈来。 1、管道 我们来看一条 Linux 的语句 netstat -tulnp | gr...
相关热词 如何提升c#开发能力 矩阵乘法c# c#调用谷歌浏览器 c# 去空格去转义符 c#用户登录窗体代码 c# 流 c# linux 可视化 c# mvc 返回图片 c# 像素空间 c# 日期 最后一天
立即提问