HttpServletRequest request .getSession() 报错,报错内容是获取不到Redis连接

HttpServletRequest request .getSession() 报错,报错内容是获取不到Redis连接,但是操作Redis没有任何问题。(框架是Spring + SpringMVC)
报错语句,如图

图片说明

报错详情,如图
图片说明

报错内容:

java.util.NoSuchElementException: Unable to validate object

[redis.clients.jedis.util.Pool.getResource(Pool.java:53), redis.clients.jedis.JedisPool.getResource(JedisPool.java:234), redis.clients.jedis.JedisPool.getResource(JedisPool.java:15), tomcat.request.session.data.cache.impl.redis.RedisManager.setnx(RedisManager.java:51), tomcat.request.session.data.cache.impl.redis.RedisCache.setnx(RedisCache.java:36), tomcat.request.session.redis.SessionManager.createSession(SessionManager.java:100), tomcat.request.session.redis.SessionManager.createSession(SessionManager.java:28), org.apache.catalina.connector.Request.doGetSession(Request.java:2981), org.apache.catalina.connector.Request.getSession(Request.java:2374), org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:908), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43), java.lang.reflect.Method.invoke(Method.java:498), org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:307), com.sun.proxy.$Proxy105.getSession(Unknown Source), com.dsh.live.login.controller.LoginController.userLogin(LoginController.java:64), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43), java.lang.reflect.Method.invoke(Method.java:498), org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222), org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137), org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110), org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814), org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737), org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85), org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959), org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893), org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969), org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871), javax.servlet.http.HttpServlet.service(HttpServlet.java:660), org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845), javax.servlet.http.HttpServlet.service(HttpServlet.java:741), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166), org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166), org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121), org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107), org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193), org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166), org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199), org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96), tomcat.request.session.redis.SessionHandlerValve.invoke(SessionHandlerValve.java:29), org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137), org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81), org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651), org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87), org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342), org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:409), org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66), org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754), org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376), org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49), java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142), java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617), org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61), java.lang.Thread.run(Thread.java:745)]

2个回答

检查下 Redis 连接的配置信息。

qq_38243173
星空下的西瓜地 redis连接没有问题,其他环境整个服务都是好的,当前项目也是可以正常使用redis
4 个月之前 回复

猜测你们的session是存在redis里面,后台部署是集群模式;
这种情况下,获取session要从redis中取出来
检查redis配置或者配置redis连接池

qq_38243173
星空下的西瓜地 谢谢回答,session没有放redis里面,还没有用集群的方式部署。
4 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
mvc启动报错(baseController注入的request是null)
自己学习spingboot,搭建的mvc项目,我的想法是: 登录的时候保存loginUser,然后在BaseController获取loginUser,所有的controller继承BaseController,这样在其他的controller中就可以直接使用loginUser。 现在项目启动报错,request是null, 希望帮忙看一下我这么写是有什么问题?或者有没有别的办法可以实现我想要的结果 ``` public class BaseController { private static Logger log = LoggerFactory.getLogger(BaseController.class); @Autowired(required = false) private HttpServletRequest request; public LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser"); public void saveLoginUserInBase(LoginUser loginUser){ request.getSession().setAttribute("loginUser",loginUser); } } ```
HttpServletRequest
我的web工程已经导入了一个Servlet 架包了,但是在 HttpServletRequest request=ServletActionContext.getRequest(); 还是报错:Type mismatch: cannot convert from HttpServletRequest to HttpServletRequest ,我就根据提示强转:HttpServletRequest request=(HttpServletRequest) ServletActionContext.getRequest(); 但是这样根本做不到:javax.servlet.http.HttpSession session = request.getSession(true); 我的JDK是1.7,是不是版JDK版本的问题呢!
javaweb转发forward报错
工具eclipse——本意是通过filter过滤,如下: ``` public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if (req.getSession().getAttribute("hotproductlist") != null) { chain.doFilter(req, response); } else { req.getRequestDispatcher(req.getContextPath() + "/findHotProduct").forward(req, response); } } ``` 这里一切正常,但是servlet的forward报错: ``` public void doGet(HttpServletRequest request, HttpServletRequest response) throws ServletException, IOException { ProductService service=new ProductService(); List<Product> hotproductlist=new ArrayList<Product>(); hotproductlist=service.findHotProduct(); request.getSession().setAttribute("hotproductlist", hotproductlist); request.getRequestDispatcher(request.getContextPath()+"/index.jsp").forward(request, response);; } ``` 这里的forward报错The method forward(ServletRequest, ServletResponse) in the type RequestDispatcher is not applicable for the arguments (HttpServletRequest, HttpServletRequest) 我觉得是编译器的原因,但是怎么都弄不好,求大佬们指点!!!
ajax 报错,400 bad request
前台页面: function getCityTList() { //更改用户权限 var provinceId=$("#selectedProvinceId").find("option:selected").val(); if (provinceId !=null) { $.post("<%=basePath%>pstnTerminal/setPstnUserPriv.do", { "provinceId" : provinceId }, function() { alert(ok); }); } } 后台代码: @RequestMapping(value="/setPstnUserPriv", method = RequestMethod.POST) @ResponseBody public void setPstnUserPriv(HttpServletRequest request,HttpServletResponse response,String provinceId){ User user=(User) request.getSession().getAttribute("userInfo"); if(!provinceId.equals("")&&!provinceId.equals("-1")){//如果选择了省就将权限降级例外情况都是全国 user.setJG_CODE(provinceId);;//将其机构代码变为省的编码 Orga orga = orgaService.getOrgaByCode(user.getJG_CODE()); if(null != orga){ user.setOrga(orga); } //改掉原来的 request.getSession().setAttribute("userInfo", user); } } 浏览器报错: jquery-1.8.3.js:8434 POST http://localhost:8080/HS/%3C%=basePath%%3Epst nTerminal/setPstnUserPriv.do 400 (Bad Request) jquery-1.8.3.js:8434
timer定时器报空指针异常为什么?
今天想到用timer写一个定时清空session值得定时器,但报空指针。 代码如下: ``` public void removeYZM( HttpServletRequest request, String code) { Timer timer = new Timer(); System.out.println("验证码:------"+request.getSession().getAttribute(code)); timer.schedule(new TimerTask() { public void run() { // 删除session中存的验证码 request.getSession().removeAttribute(code); timer.cancel(); } }, 1 * 60 * 1000); } ``` 报错信息 ``` Exception in thread "Timer-1" java.lang.NullPointerException at com.temp.ssm.controller.UserClientController$1.run(UserClientController.java:51) at java.util.TimerThread.mainLoop(Timer.java:555) at java.util.TimerThread.run(Timer.java:505) ```
web.xml的配置好像不对,运行项目控制台总是报错说找不到类,是不是路径错了
LoginAction.java: package campsg.qunawan.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.mbeans.UserMBean; public class LoginAction extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("执行LoginAction方法"); doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); if("login".equals(method)){//登录 String username = request.getParameter("username"); String password = request.getParameter("password"); if(username==null||"".equals(username.trim())||password==null||"".equals(password.trim())){ System.out.println("用户名或密码不能为空!"); response.sendRedirect("login.html"); return; } boolean isValid = false; if(isValid){ System.out.println("登录成功!"); request.getSession().setAttribute("username", username); response.sendRedirect("index.html"); return; }else{ System.out.println("用户名或密码错误,登录失败!"); response.sendRedirect("login.html"); return; } }else if("logout".equals(method)){//退出登录 System.out.println("退出登录!"); request.getSession().removeAttribute("username"); response.sendRedirect("login.html"); return; } } } ![图片说明](https://img-ask.csdn.net/upload/201612/16/1481849480_663914.png) ![图片说明](https://img-ask.csdn.net/upload/201612/16/1481849494_867200.png) ![图片说明](https://img-ask.csdn.net/upload/201612/16/1481849783_238355.png)
java 写的登录验证问题
public class LoginCheck extends HttpServlet { /** * Constructor of the object. */ public LoginCheck() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); String userid = request.getParameter("userid"); String password = request.getParameter("password"); System.out.println(userid+password+"===================="); if(request.getSession().getAttribute("loginUser")!=null){ request.getRequestDispatcher("/index.html").forward(request, response); }else{ Integer loginuserid=Integer.parseInt(userid); Management managementlogin = null ; ManagementService managementServicelogin = new ManagementService(); managementlogin = managementServicelogin.getoneManagementbyID(loginuserid); if(!(managementlogin.getName() == null) ){ String Chechpwd = managementlogin.getPwd(); if(Chechpwd.equals(password)){ request.getSession().setAttribute("loginUser", managementlogin); request.getRequestDispatcher("/index.html").forward(request, response); }else{ request.getRequestDispatcher("/login.jsp").forward(request, response); } }else{ request.getRequestDispatcher("/login.jsp").forward(request, response); } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } } ``` 当输入正确的用户ID和密码时候,成功登录,当输入一个错误的用户id时候报错:type Exception report message description The server encountered an internal error that prevented it from fulfilling this request. exception java.lang.NullPointerException com.jclg.control.LoginCheck.doGet(LoginCheck.java:41) com.jclg.control.LoginCheck.doPost(LoginCheck.java:66) javax.servlet.http.HttpServlet.service(HttpServlet.java:643) javax.servlet.http.HttpServlet.service(HttpServlet.java:723) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.43 logs. ```
求助 java 导入Excel日志本地可以 服务器报错
源代码 服务器报错 jxl.read.biff.biffexception: the input file was not found private String importUserlog(HttpServletRequest request,Parameters params) throws Exception{ String userName = ((Parameters) (request.getSession().getAttribute("_current"))).getString("managerName"); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile excelFile = multipartRequest.getFile("Filedata"); //String tempPath = request.getSession().getServletContext().getRealPath("/")+"/template/"+"rzgl/"+"viewJournal/"+"userlog.xls";//未加密前的文件 //File tempPath = new File(request.getSession().getServletContext().getRealPath("/")+"//template//rzgl//viewJournal//userlog.xls"); File tempPath1 = new File(request.getSession().getServletContext().getRealPath("/")+"/template/rzgl/viewJournal/userlog.xls"); System.out.println(tempPath1+"-------------------用户日志导入"); if(tempPath1.exists()&&tempPath1.length()>0) tempPath1.delete(); FileUtils.copyInputStreamToFile(excelFile.getInputStream(), tempPath1); if(!tempPath1.exists()){ request.setAttribute("error", "文件不存在!"); return "rzgl/viewJournal/upload"; } Workbook book = Workbook.getWorkbook(tempPath1); Sheet sheet = book.getSheet(0); int num=0; for(int i = 1; i < sheet.getRows(); i ++){ Loginfo info = new Loginfo(); if(sheet.getCell(0, i).getContents().trim().equals("")&&sheet.getCell(1, i).getContents().trim().equals("")&&sheet.getCell(2, i).getContents().trim().equals("")){ continue; } info.setLoginName(sheet.getCell(0, i).getContents().trim()); info.setLogTime(sheet.getCell(1, i).getContents().trim()); info.setLogIp(sheet.getCell(2, i).getContents().trim()); info.setLogInfo(sheet.getCell(3, i).getContents().trim()); info.setActionObject(sheet.getCell(4, i).getContents().trim()); info.setActionType(sheet.getCell(5, i).getContents().trim()); info.setTerminal(sheet.getCell(6, i).getContents().trim()); info.setStauts("1"); try{ int temp = logService.addUserInfo(info); if(temp>0) num++; }catch(Exception e){ e.printStackTrace(); } } int err = sheet.getRows()-num-1; if(tempPath1.exists())tempPath1.delete();//删除解密前的原文件 this.tempsuccess = num; this.temperror = err; book.close(); Manager user = new Manager(); user.setLoginName(userName); user.setLogIp(request.getRemoteAddr()); user.setLogInfo(userName+"导入用户日志:成功"+num+"条,失败"+err+"条"); user.setObjectId("用户日志"); user.setActionType("导入"); recordService.addRecord(user); return helper(request,num,err); 看了网上了 没解决
第一个控制器将登陆后将账户密码存入session,但是第二个控制器无法找到参数
第一个控制器 @Resource(name = "userServiceImpl") private UserServiceImpl users; @RequestMapping(value = "/entity") public String entity(HttpServletRequest request, HttpServletResponse response) { // 获取session HttpSession session = request.getSession(); // 获取账户和密码 String account = request.getParameter("account"); String codes = request.getParameter("codes"); // 新建一个哈希map集合接受账户和密码的集合 HashMap entity = new HashMap(); entity = users.selectEntityUser(); session.setAttribute("account", account); session.setAttribute("codes", codes); /*session.setAttribute("account", request.getParameter("account")); session.setAttribute("codes", request.getParameter("codes")); */// 判断账户是否匹配,并且根据用户名获取密码,并判断是否匹配 if (entity.containsKey(account) && entity.get(account).equals(codes)) { // 登陆成功 return "success"; } else { // 登陆失败返回首页 String msg = "用户名或密码错误"; session.setAttribute("msgs", msg); return "index"; } } 第二个控制器 @RequestMapping(value = "/information") public <Account> void information(HttpServletRequest request, HttpServletResponse response) { request.getSession().getAttribute("account"); //调用工具包 JosnUntils josn=new JosnUntils(); //获取sesion HttpSession session= request.getSession(); //获取存取的session值账户和密码并且强制装换 String account=String.valueOf(session.getAttribute("account")); //强制转换 String codes=String.valueOf(session.getAttribute("codes")); //获取一个对象将对象打包成josn传到jsp上面 User user= users.information(account, codes); //转化为josn String use=josn.toJosn(user); //存入 session.setAttribute("information", use); //返回页面 } 报错为:HTTP Status 500 - Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'account' not found. Available parameters are [1, 0, param1, param2] 具体:type Exception report message Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'account' not found. Available parameters are [1, 0, param1, param2]
这个为什么没办法插入到数据库?
servlet里调用impl中的方法 public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ //将订单写入数据库 int count = 1; HttpSession ses = request.getSession(); List<Member> member = (List<Member>) ses.getAttribute("member"); HashMap<Integer, Product> shopCart = (HashMap<Integer, Product>) ses.getAttribute("SelectedGoods"); Order order = new Order(); for (HashMap.Entry<Integer, Product> entry : shopCart.entrySet()) { for (int i = 0; i < member.size(); i++) { order.setAddress(member.get(i).getAddress()); order.setMname(member.get(i).getName()); order.setTelephone(member.get(i).getTelephone()); } order.setPname(entry.getValue().getName()); order.setPrice(entry.getValue().getPrice()); order.setNum(entry.getValue().getAmount()); order.setNote(entry.getValue().getNote()); order.setOrderid("o"+count); count++; try { DAOFactory.getOrderDAOInstance().doCreate(order); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //跳转 request.getRequestDispatcher("psuccess.jsp").forward(request, response); HttpSession session = request.getSession(); session.removeAttribute("SelectedGoods"); } impl中的方法 public boolean doCreate(Order order)throws Exception{ boolean flag = false; String sql = "INSERT INTO order(orderid,mname,address,telephone,pname,note,price,num)VALUES(?,?,?,?,?,?,?,?)"; this.pstmt = this.conn.prepareStatement(sql); /*System.out.println(order.getOrderid()); System.out.println(order.getMname()); System.out.println(order.getAddress()); System.out.println(order.getTelephone()); System.out.println(order.getPname()); System.out.println(order.getNote()); System.out.println(order.getPrice()); System.out.println(order.getNum());*/ this.pstmt.setString(1,order.getOrderid()); this.pstmt.setString(2,order.getMname()); this.pstmt.setString(3,order.getAddress()); this.pstmt.setString(4,order.getTelephone()); this.pstmt.setString(5,order.getPname()); this.pstmt.setString(6,order.getNote()); this.pstmt.setDouble(7,order.getPrice()); this.pstmt.setInt(8,order.getNum()); if(this.pstmt.executeUpdate()>0){ flag = true; } this.pstmt.close(); return flag; } 报错信息: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order(orderid,mname,address,telephone,pname,note,price,num)VALUES('o1','qwe','qw' at line 1
麻烦大家帮我看看这个异常信息怎么处理?
Cannot add or update a child row: a foreign key constraint fails (`xiaonei/photo1`, CONSTRAINT `FKC50C883FA1694277` FOREIGN KEY (`albumId`) REFERENCES `album` (`id`)) public ActionForward oneAlbumUI(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub //System.out.println("oneAlbumUI..."); //这里,我们要完成把图片上传到服务器,并保存记录到Photo对象 //先考虑用户上传一张图片的情况 AlbumForm albumForm = (AlbumForm) form; Admin admin = (Admin) request.getSession().getAttribute("admin"); //Users loginUser = (Users) request.getSession().getAttribute("loginuser"); FormFile photo1 = albumForm.getPhoto1(); if(!"".equals(photo1.getFileName())){ //说明用户上传了第一张图片 //把图片上传上去 //再把信息保存到数据库 String newFileName = MyTools.uploadPhoto(request, photo1, admin.getId()+"", albumForm.getId()); Photo1 myPhoto1 = new Photo1(); myPhoto1.setIndate(new Date()); myPhoto1.setAlbum((Album) albumService1.findById(Album.class, Integer.valueOf(albumForm.getId()))); //该图片属于哪个相册 myPhoto1.setPhoto(newFileName); //这句话就是把信息保存到数据库 albumService1.save(myPhoto1); } } 我在上一页面上调用Action保存了Album的信息,然后跳转到一下个页面调用Action保存Photo信息,但是报错,这是为什么?
到底哪出错了 ,老报错,使用session就可以
<% List<Users> usersli = (List) request.getAttribute("usersli"); Users users; /*Debug*/System.out.println("show_users.jsp"); if (usersli !=null) { for (int i = 0; i < usersli.size(); i++) { users = (Users)usersli.get(i); %> < tr> < td><%=users.getUser()%></td> < td><%=users.getPassword()%></td> < td><%=users.getNumber()%></td> < td><%=users.getRoot()%></td> < td> < form id="form2" name="form2" method="post" action=""> < input type="submit" name="updata" id="updata" value="编辑" /> < input type="submit" name="del" id="del" value="删除" /> < /form> < /td> < /tr> <% } } %> ---------------------------------------------------------------------- SERVLET代码: private void show(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ String root =(String)request.getParameter("chooseroot"); String user = (String)request.getParameter("condition"); /*Debug*/System.out.println("ShowServlet.show(),权限="+root+",条件="+user); UsersDAO usersDAO = new UsersDAO(); List<?> usersli= new ArrayList<Object>(); usersli = usersDAO.show(root,user); //list传递 request.setAttribute("usersli", usersli); request.getRequestDispatcher("../show/show_users.js").forward(request,response); //request.getSession().setAttribute("usersli",usersli ); //response.sendRedirect("../show/show_users.jsp"); }
关于tomcat 报错原因
description The server encountered an internal error () that prevented it from fulfilling this request. exception java.lang.ClassCastException: com.sany.web.session.WebSession cannot be cast to java.lang.String com.sany.web.filter.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:34)》<!---> note The full stack trace of the root cause is available in the Apache Tomcat/6.0.35 logs. /** * */ package com.sany.web.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import com.sany.util.log.ILogger; public class SetCharacterEncodingFilter implements Filter { private static final ILogger logger = ILogger.getInstance().getILogger(SetCharacterEncodingFilter.class); public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain fileter) throws IOException, ServletException { // TODO Auto-generated method stub request.setCharacterEncoding("GBK"); HttpServletRequest req = (HttpServletRequest) request; // response.setCharacterEncoding("GBK"); try{ fileter.doFilter(request, response); } catch(Exception e){ logger.error((String)req.getSession().getAttribute("user"),"doFilter(ServletRequest request=" + request + ", ServletResponse response=" + response + ") - [方法错误]", e); e.printStackTrace(); } } public void destroy() { // TODO Auto-generated method stub } }
hibernate项目运行一段时间后,JDBC报错
type Exception report message JDBC commit failed description The server encountered an internal error that prevented it from fulfilling this request. exception org.hibernate.TransactionException: JDBC commit failed org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:161) filter.TestFilter.doFilter(TestFilter.java:34) root cause com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Communications link failure during commit(). Transaction resolution unknown. sun.reflect.GeneratedConstructorAccessor21.newInstance(Unknown Source) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:526) com.mysql.jdbc.Util.handleNewInstance(Util.java:425) com.mysql.jdbc.Util.getInstance(Util.java:408) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) com.mysql.jdbc.ConnectionImpl.commit(ConnectionImpl.java:1559) org.hibernate.transaction.JDBCTransaction.commitAndResetAutoCommit(JDBCTransaction.java:170) org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:146) filter.TestFilter.doFilter(TestFilter.java:34) 项目使用的是hibernate+struts2+Mysql;项目不是跑起来就报错,是运行一段时间后就报错。服务器重启就可以了,但一段时间后又报错。mysql驱动用3.0的时候也是这个情况,不过抱错是No operations allowed after connection closed;现在换成最新的5.o就报这个个错误。求高手解决。。。 事务我直接用了个过滤器 public class TestFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest requ, ServletResponse respo, FilterChain chain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest)requ; request.setCharacterEncoding("utf-8"); Session session=HibernateSessionFactory.getSession(); Transaction tr=session.beginTransaction(); chain.doFilter(request, respo); tr.commit();------报错在这行,34行 HibernateSessionFactory.closeSession(); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
想把用户名存在session中 在方法中加request参数后运行报错 求指教~
我用的是spring+hibernate~ 修改后: public class LoginAction extends SimpleFormController{ private Login login; private String viewPage; private String successPage; //实现onSubmit()方法 public ModelAndView onSubmit(Object command,HttpServletRequest request) throws Exception { //强制转换成User User user = (User)command; Map model = new HashMap(); //进行登录的业务逻辑处理 getLogin().login(user); //存放消息 request.getSession().setAttribute("userName", user.getUsername()); model.put("user", user); model.put("userId", user.getId()); model.put("msg", getLogin().getMsg()); if ("登录成功".equals(getLogin().getMsg())) { //返回到登录成功的页面 return new ModelAndView(getSuccessPage(), model); } return new ModelAndView(getViewPage(), model); } 修改前: public class LoginAction extends SimpleFormController{ private Login login; private String viewPage; private String successPage; //实现onSubmit()方法 public ModelAndView onSubmit(Object command) throws Exception { //强制转换成User User user = (User)command; Map model = new HashMap(); //进行登录的业务逻辑处理 getLogin().login(user); //存放消息 model.put("user", user); model.put("userId", user.getId()); model.put("msg", getLogin().getMsg()); if ("登录成功".equals(getLogin().getMsg())) { //返回到登录成功的页面 return new ModelAndView(getSuccessPage(), model); } return new ModelAndView(getViewPage(), model); } 报错: 严重: Servlet.service() for servlet [dispatcherServlet] in context with path [/mySurvey] threw exception [successView isn't set] with root cause javax.servlet.ServletException: successView isn't set at org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:416) at org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:380) at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:267) at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:250) at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153) at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:819) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:754) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:399) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:364) 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.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:957) 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$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:662)
SpringBoot中@Autowired注入bean失败:Error creating bean with name“XXXController”?
# 报错信息: ``` org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizeController': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userMapper' defined in file [E:\STS-WorkSpace\Forum\target\classes\com\Forum\mapper\UserMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$141/1866850137.getObject(Unknown Source) ~[na:na] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at com.Forum.ForumApplication.main(ForumApplication.java:19) [classes/:na] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userMapper' defined in file [E:\STS-WorkSpace\Forum\target\classes\com\Forum\mapper\UserMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$141/1866850137.getObject(Unknown Source) ~[na:na] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] ... 20 common frames omitted Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required at org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.mybatis.spring.support.SqlSessionDaoSupport.checkDaoConfig(SqlSessionDaoSupport.java:123) ~[mybatis-spring-2.0.1.jar:2.0.1] at org.mybatis.spring.mapper.MapperFactoryBean.checkDaoConfig(MapperFactoryBean.java:73) ~[mybatis-spring-2.0.1.jar:2.0.1] at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44) ~[spring-tx-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] ... 31 common frames omitted ``` # Mapper代码: ``` package com.Forum.mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import com.Forum.Model.User; @Mapper public interface UserMapper{ @Insert("insert into user (name,account_id,token,gmt_create,gmt_modified) values (#{name},#{accountId}),#{token},#{gmtCreate},#{gmtModified}") public void insert(User user); } ``` # 启动代码: ``` package com.Forum; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @ComponentScan(basePackages = {"com.Forum.*"}) @MapperScan(basePackages = {"com.Forum.mapper"}) public class ForumApplication { public static void main(String[] args) { SpringApplication.run(ForumApplication.class, args); } } ``` # Controller代码: ```package com.Forum.Controller; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import com.Forum.Dto.AccesstokenDTO; import com.Forum.Dto.GitHubUser; import com.Forum.Model.User; import com.Forum.Provider.GitHubProvider; import com.Forum.mapper.UserMapper; @Controller public class AuthorizeController{ @Autowired private GitHubProvider gitHubProvider; @Value("${github.client.id}") private String clientId; @Value("${github.client.secret}") private String clientSecret; @Value("${github.redirect.uri}") private String redirectUri; @Autowired public UserMapper userMapper; @GetMapping("/callback") public String callback(@RequestParam(name="code") String code, @RequestParam(name="state") String state, HttpServletRequest request ) { AccesstokenDTO accesstokenDTO = new AccesstokenDTO(); accesstokenDTO.setCode(code); accesstokenDTO.setRedirect_uri("redirectUri"); accesstokenDTO.setClient_id(clientId); accesstokenDTO.setClient_secret(clientSecret); accesstokenDTO.setState(state); String accessToken = gitHubProvider.getAccessToken(accesstokenDTO); GitHubUser githubUser = gitHubProvider.getUser(accessToken); if(githubUser != null) { // 登录成功,写cookie和session User user = new User(); user.setToken(UUID.randomUUID().toString()); user.setName(githubUser.getName()); user.setAccountId(String.valueOf(githubUser.getId())); user.setQmtCreate(System.currentTimeMillis()); user.setQmtModified(user.getQmtCreate()); userMapper.insert(user); request.getSession().setAttribute("user", githubUser); return "redirect:/"; // 去掉地址后缀 }else { // 登录失败,重新登录 return "redirect:/"; } } } ```
springmvc 图片上传报错,页面报500,有没有大神遇见过,求帮助!!!!!!!!!
前端是: <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> <form name="Form2" action="http://localhost:8081/jg/merchants/updatespringUpload" method="post" enctype="multipart/form-data"> <h1>使用spring mvc提供的类的方法上传文件</h1> <input type="file" name="file"> <input type="submit" value="upload"/> </form> </body> </html> controller : @RequestMapping(value = "/updatespringUpload") public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException { long startTime=System.currentTimeMillis(); //将当前上下文初始化给 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver( request.getSession().getServletContext()); //检查form中是否有enctype="multipart/form-data" if(multipartResolver.isMultipart(request)) { //将request变成多部分request MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request; //获取multiRequest 中所有的文件名 Iterator iter=multiRequest.getFileNames(); while(iter.hasNext()) { //一次遍历所有文件 MultipartFile file=multiRequest.getFile(iter.next().toString()); if(file!=null) { String path="E:/springUpload"+file.getOriginalFilename(); //上传 file.transferTo(new File(path)); } } } long endTime=System.currentTimeMillis(); System.out.println("方法三的运行时间:"+String.valueOf(endTime-startTime)+"ms"); return "/success"; } 报错内容是: HTTP Status 500 - Request processing failed; nested exception is com.alibaba.fastjson.JSONException: toJSON error
springMVC上传文件报错404
学习springMVC文件上传的时候,选择了文件提交以后报错404 jsp ``` <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上传</title> </head> <body> <h3>文件上传</h3> <form action="/User/fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="upload"><br/> <input type="submit" value="上传"> </form> </body> </html> ``` spring-MVC配置如下 ``` <?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--开启注解扫描--> <context:component-scan base-package="com.ryn"/> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--配置解析器--> <property name="suffix" value=".jsp"/> <!--配置目录--> <property name="prefix" value="/WEB-INF/pages/"/> </bean> <!--配置静态资源--> <mvc:resources location="/upload/" mapping="/upload/**" /> <mvc:resources mapping="/js/**" location="js/"/> <!--配置文件解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> <property name="maxUploadSize" value="10485760"/> </bean> <!--开启springMVC框架注解的支持--> <mvc:annotation-driven/> </beans> ``` web.xml配置 ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!--配置前端控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` uploadController ``` /** * 文件上传 * @return */ @RequestMapping("/fileUpload") public String fileUpload(HttpServletRequest request, @RequestParam("upload") MultipartFile upload) throws Exception{ System.out.println("文件上传"); //指定上传位置 String path = request.getSession().getServletContext().getRealPath("/upload/"); //判断文件夹是否存在 File file = new File(path); if (!file.exists()){ //若不存在,则创建文件夹 file.mkdirs(); } String filename = upload.getOriginalFilename(); //使用write方法上传文件 String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); filename = uuid + "_" + filename; upload.transferTo(new File(path,filename)); return "success"; } ``` 报错信息如下 ![图片说明](https://img-ask.csdn.net/upload/201911/14/1573725685_322217.jpg) 求各位大佬帮我看看问题到底出在哪了!!!弄了半个小时不知道怎么回事
servlet2.4监听器里有这个event.getRequest()方法吗?
在实现HttpSessionListener接口 实现sessionDestroyed方法 时报错: 我用的是Tomcat5.5.27中的servlet_api.jar 包,看tomcat说明里说5.5是servlet2.4标准,为什么没有这个方法? 怎么解决?想实现session失效跳转的功能。 public void sessionDestroyed(HttpSessionEvent event){ //下面这句报错,没有event.getRequest的方法 HttpServletRequest request = event.getRequest(); HttpServletResponse response = event.getResponse(); event.getSession().getServletContext().getRequestDispatcher( "/login.jsp ").forward(request,response); [b]问题补充:[/b] 那在监听里如何获得到request和response对象?有办法吗?
相见恨晚的超实用网站
搞学习 知乎:www.zhihu.com 简答题:http://www.jiandati.com/ 网易公开课:https://open.163.com/ted/ 网易云课堂:https://study.163.com/ 中国大学MOOC:www.icourse163.org 网易云课堂:study.163.com 哔哩哔哩弹幕网:www.bilibili.com 我要自学网:www.51zxw
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
字节跳动视频编解码面经
引言 本文主要是记录一下面试字节跳动的经历。 三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时
开源一个功能完整的SpringBoot项目框架
福利来了,给大家带来一个福利。 最近想了解一下有关Spring Boot的开源项目,看了很多开源的框架,大多是一些demo或者是一个未成形的项目,基本功能都不完整,尤其是用户权限和菜单方面几乎没有完整的。 想到我之前做的框架,里面通用模块有:用户模块,权限模块,菜单模块,功能模块也齐全了,每一个功能都是完整的。 打算把这个框架分享出来,供大家使用和学习。 为什么用框架? 框架可以学习整体
源码阅读(19):Java中主要的Map结构——HashMap容器(下1)
(接上文《源码阅读(18):Java中主要的Map结构——HashMap容器(中)》) 3.4.4、HashMap添加K-V键值对(红黑树方式) 上文我们介绍了在HashMap中table数组的某个索引位上,基于单向链表添加新的K-V键值对对象(HashMap.Node&lt;K, V&gt;类的实例),但是我们同时知道在某些的场景下,HashMap中table数据的某个索引位上,数据是按照红黑树
c++制作的植物大战僵尸,开源,一代二代结合游戏
    此游戏全部由本人自己制作完成。游戏大部分的素材来源于原版游戏素材,少部分搜集于网络,以及自己制作。 此游戏为同人游戏而且仅供学习交流使用,任何人未经授权,不得对本游戏进行更改、盗用等,否则后果自负。 目前有六种僵尸和六种植物,植物和僵尸的动画都是本人做的。qq:2117610943 开源代码下载 提取码:3vzm 点击下载--&gt; 11月28日 新增四种植物 统一植物画风,全部修
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)
最近翻到一篇知乎,上面有不少用Python(大多是turtle库)绘制的树图,感觉很漂亮,我整理了一下,挑了一些我觉得不错的代码分享给大家(这些我都测试过,确实可以生成喔~) one 樱花树 动态生成樱花 效果图(这个是动态的): 实现代码 import turtle as T import random import time # 画樱花的躯干(60,t) def Tree(branch
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
Python 基础(一):入门必备知识
目录1 标识符2 关键字3 引号4 编码5 输入输出6 缩进7 多行8 注释9 数据类型10 运算符10.1 常用运算符10.2 运算符优先级 1 标识符 标识符是编程时使用的名字,用于给变量、函数、语句块等命名,Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。 以下划线开头的标识符有特殊含义,单下划线开头的标识符,如:_xxx ,表示不能直接访问的类属性,需通过类提供
深度学习图像算法在内容安全领域的应用
互联网给人们生活带来便利的同时也隐含了大量不良信息,防范互联网平台有害内容传播引起了多方面的高度关注。本次演讲从技术层面分享网易易盾在内容安全领域的算法实践经验,包括深度学习图
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 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)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题: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孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
Python 编程实用技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法,并会持续更新。
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
"狗屁不通文章生成器"登顶GitHub热榜,分分钟写出万字形式主义大作
GitHub 被誉为全球最大的同性交友网站,……,陪伴我们已经走过 10+ 年时间,它托管了大量的软件代码,同时也承载了程序员无尽的欢乐。 万字申请,废话报告,魔幻形式主义大作怎么写?兄dei,狗屁不通文章生成器了解一下。这个富有灵魂的项目名吸引了众人的目光。项目仅仅诞生一周,便冲上了GitHub趋势榜榜首(Js中文网 -前端进阶资源教程)、是榜首哦
推荐几款比较实用的工具,网站
1.盘百度PanDownload 这个云盘工具是免费的,可以进行资源搜索,提速(偶尔会抽风????) 不要去某站买付费的???? PanDownload下载地址 2.BeJSON 这是一款拥有各种在线工具的网站,推荐它的主要原因是网站简洁,功能齐全,广告相比其他广告好太多了 bejson网站 3.二维码美化 这个网站的二维码美化很好看,网站界面也很...
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
相关热词 c#处理浮点数 c# 生成字母数字随机数 c# 动态曲线 控件 c# oracle 开发 c#选择字体大小的控件 c# usb 批量传输 c#10进制转8进制 c#转base64 c# 科学计算 c#下拉列表获取串口
立即提问