@Override public boolean findUserInfoByIdAndName(@RequestParam Integer name, @RequestParam String age) throws Exception { if (name == null) { throw new Exception("用户名不能为空"); } if (age == null) { throw new Exception("年龄不能为空"); } String ageStr = "18"; if (age < 120) { return true; } throw new Exception("年龄必须大于18且小于120"); UserInfo userInfo = deviceInfoMapper.findUserInfoByIdAndName(name,age); if (userInfo == null) { throw new Exception("未找到符合条件的用户信息"); }

时间: 2024-02-15 16:28:47 浏览: 6
这段代码是一个Java方法,它的作用是根据用户名和年龄查询用户信息。方法的参数包括一个整型的name和一个字符串类型的age,返回一个布尔类型的值。 在方法中,首先会进行参数的非空校验,如果参数为空,则抛出异常。然后会对年龄进行判断,如果年龄小于18或大于120,则抛出异常。 接下来会调用一个名为findUserInfoByIdAndName的方法,该方法会根据传入的用户名和年龄进行查询用户信息的操作。如果查询结果为null,则表示未找到符合条件的用户信息,会抛出异常。 最后,如果整个方法执行成功,会返回true。
相关问题

@Override public boolean findUserInfoByIdAndName(@RequestParam Integer name, @RequestParam String age) throws Exception { if (name == null) { throw new Exception("用户名不能为空"); } if (age == null) { throw new Exception("年龄不能为空"); } String ageStr = "18"; if (age < 120) { return true; } throw new Exception("年龄必须大于18且小于120"); UserInfo userInfo = deviceInfoMapper.findUserInfoByIdAndName(name,age); if (userInfo == null) { throw new Exception("未找到符合条件的用户信息"); }优化下面的代码

以下是对该段代码的一些优化建议: 1. 参数校验可以使用注解@NotBlank和@NotNull来简化代码。 2. 年龄的判断可以改为使用Integer类型进行比较。 3. 异常信息可以封装成常量或枚举类型,方便维护和修改。 4. 代码中有一行无法执行到的语句,应该进行删除。 优化后的代码如下所示: ``` @Override public boolean findUserInfoByIdAndName(@NotBlank(message = "用户名不能为空") Integer name, @NotNull(message = "年龄不能为空") Integer age) throws Exception { final Integer MIN_AGE = 18; final Integer MAX_AGE = 120; if (age < MIN_AGE || age > MAX_AGE) { throw new Exception("年龄必须大于18且小于120"); } UserInfo userInfo = deviceInfoMapper.findUserInfoByIdAndName(name, age); if (userInfo == null) { throw new Exception("未找到符合条件的用户信息"); } return true; } ```

优化代码中的问题,简洁的代码 @Override public boolean findUserInfoByIdAndName(int age, String name) throws Exception { if (StringUtils.isEmpty(name)) { throw new Exception("用户名不能为空"); } if (age == null) { throw new Exception("年龄不能为空"); } final Integer MIN_AGE = 18; final Integer MAX_AGE = 120; if (age < MIN_AGE || age > MAX_AGE) { throw new Exception("年龄必须大于18且小于120"); } UserInfo userInfo = deviceInfoMapper.findUserInfoByIdAndName(name, age); if (userInfo == null) { throw new Exception("未找到符合条件的用户信息"); } return true; } }

可以优化的地方如下: 1. 可以使用Java8的Optional类来避免null的判断,也可以使用Objects.requireNonNull方法来抛出空指针异常。 2. 可以在方法签名中使用基本数据类型,而不是其包装类型。 3. 可以使用自定义异常类来替换Exception,以便更好地描述错误原因。 4. 可以使用静态导入来简化代码。 下面是优化后的代码示例: ``` @Override public boolean findUserInfoByIdAndName(int age, String name) throws UserNotFoundException, InvalidParameterException, NullPointerException { Objects.requireNonNull(name, "用户名不能为空"); if (age < 18 || age > 120) { throw new InvalidParameterException("年龄必须大于18且小于120"); } UserInfo userInfo = deviceInfoMapper.findUserInfoByIdAndName(name, age); if (userInfo == null) { throw new UserNotFoundException("未找到符合条件的用户信息"); } return true; } ``` 注意,这个示例中的UserNotFoundException和InvalidParameterException需要自定义实现。

相关推荐

以下代码存在读取文件乱码的情况请给与优化 public static void main(String[] args) { String sourceDirectory = "D:\Java\pas\trunk-5.X+\D05源代码\后台\达梦"; String destinationFile = "D:\Java\project\demo\src\main\resources\dm-init.sql"; try { // 创建输出文件,如果文件不存在则自动创建 File file = new File(destinationFile); if (!file.exists()) { file.createNewFile(); } // 打开输出流 FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); // 递归读取源目录中的文件,并将其写入输出文件 readAndWriteFiles(sourceDirectory, bw); // 关闭输出流 bw.close(); System.out.println("文件已写入 " + destinationFile); } catch (IOException e) { e.printStackTrace(); } } private static void readAndWriteFiles(String sourceDirectory, BufferedWriter writer) throws IOException { // 创建目录文件对象 File directory = new File(sourceDirectory); // 检查目录是否存在并且是一个目录 if (!directory.exists() || !directory.isDirectory()) { throw new FileNotFoundException("目录不存在: " + sourceDirectory); } // 列出该目录下的所有文件和子目录,包括隐藏文件 File[] files = directory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && (pathname.getName().endsWith(".sql") || pathname.getName().endsWith(".txt")); } }); // 遍历文件列表 for (File file : files) { // 读取文件内容并写入输出文件 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK")); String line = null; while ((line = br.readLine()) != null) { writer.write(line); writer.newLine(); } br.close(); } // 遍历目录中的子目录并递归读取 File[] subDirectories = directory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() && !pathname.isHidden(); } }); for (File subDirectory : subDirectories) { readAndWriteFiles(subDirectory.getAbsolutePath(), writer); } }

@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { String method = request.getMethod(); String requestURI = request.getRequestURI(); if (o instanceof ResourceHttpRequestHandler || o instanceof ParameterizableViewController) { return true; } String accessName = "无"; HandlerMethod handlerMethod = (HandlerMethod) o; ApiOperation methodAnnotation = handlerMethod.getMethodAnnotation(ApiOperation.class); if (Validator.valid(methodAnnotation)) { accessName = methodAnnotation.value(); log.warn("########## requestURI: {} , method: {} , HandlerMethod: {} , IP: {} ##########", requestURI, method, accessName, IPUtil.getIPAddress(request)); } else { log.error("########## requestURI: {} , HandlerMethod: {} , IP: {} ##########", requestURI, method, IPUtil.getIPAddress(request)); } for (String url : passUrl) { if (UrlUtils.isLike(requestURI, url)) { return !method.equals("OPTIONS"); } } boolean hasPerm = false; if (!method.equals("OPTIONS")) { try { String token = request.getHeader("token"); System.out.println("token -------->>>>>> " + token); if (!Validator.valid(token)) { throw new BusinessException(CommonErrorCode.TOKEN_REMIND, "token不能为空"); } token = (String) permRedisManager.get(token); if (!Validator.valid(token)) { throw new BusinessException(CommonErrorCode.TOKEN_REMIND, "请重新登录"); } Map<String, Claim> result = JWTBuilder.parseJWT(token); if (Validator.valid(result.get(AuthUtil.SYS_EMPLOYEE_NAME))) { // hasPerm = true; DepositBox depositBox = setAttribute(request, result, AuthUtil.SYS_EMPLOYEE_NAME, token); //操作记录 String finalAccessName = accessName; } else if ((Validator.valid(result.get(AuthUtil.MEMBER_NAME)))) { if (requestURI.startsWith("/bg")) { throw new BusinessException(CommonErrorCode.NO_SESSION); } hasPerm = true; setAttribute(request, result, AuthUtil.MEMBER_NAME, token); } } catch (BusinessException e) { throw e; } catch (Exception e) { if (e instanceof NullPointerException) { throw new BusinessException(CommonE rrorCode.TOKEN_REMIND, "token无效"); } else if (e instanceof JWTDecodeException) { throw new BusinessException(CommonErrorCode.TOKEN_REMIND, "token信息不完整"); } else { throw new BusinessException(e.toString()); } } } if (!method.equals("OPTIONS") && !hasPerm) { throw new BusinessException(CommonErrorCode.NO_SESSION); } return !method.equals("OPTIONS"); }解释代码

@Component public class AuthorizationInterceptor implements HandlerInterceptor { public static final String LOGIN_TOKEN_KEY = "Token"; @Autowired private TokenService tokenService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //支持跨域请求 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,request-source,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization"); response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // 跨域时会首先发送一个OPTIONS请求,这里我们给OPTIONS请求直接返回正常状态 if (request.getMethod().equals(RequestMethod.OPTIONS.name())) { response.setStatus(HttpStatus.OK.value()); return false; } IgnoreAuth annotation; if (handler instanceof HandlerMethod) { annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class); } else { return true; } //从header中获取token String token = request.getHeader(LOGIN_TOKEN_KEY); /** * 不需要验证权限的方法直接放过 */ if(annotation!=null) { return true; } TokenEntity tokenEntity = null; if(StringUtils.isNotBlank(token)) { tokenEntity = tokenService.getTokenEntity(token); } if(tokenEntity != null) { request.getSession().setAttribute("userId", tokenEntity.getUserid()); request.getSession().setAttribute("role", tokenEntity.getRole()); request.getSession().setAttribute("tableName", tokenEntity.getTablename()); request.getSession().setAttribute("username", tokenEntity.getUsername()); return true; } PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); try { writer = response.getWriter(); writer.print(JSONObject.toJSONString(R.error(401, "请先登录"))); } finally { if(writer != null){ writer.close(); } } // throw new EIException("请先登录", 401); return false; } }

Also create a ControllerCreate class that extends Controller.The create method takes as arguments the name of a new library user, a number of books (as a string), and an integer representing the role of user to create (where the integer 0 means a lender and the integer 1 means a borrower). The create method of the controller then transforms the book number from a string to an integer (using the Integer.parseInt static method), creates an object from the correct class (based on the role specified by the user input: lender or borrower) and calls the addUser method of the library to add the new user object to the library. • If no exception occurs then the create method of the controller returns the empty string. • If the constructor of the Borrower class throws a NotALenderException then the create method of the controller must catch this exception and return as result the error message from the exception object. • If the parseInt method of the Integer class throws a NumberFormatException (because the user typed something which is not an integer) then the create method of the controller must catch this exception and return as result the error message from the exception object. Modify the run method of the GUI class to add a ViewCreate view that uses a ControllerCreate controller and the same model as before (not a new model!) Do not delete the previous views. Note: if at the end of Question 7 you had manually added to your library (model object) some users for testing, then you must now remove those users from the run method of the anonymous class inside the GUI class. You do not need these test users anymore because you have now a graphical user interface to create new users! Run your GUI and check that you can correctly use the new view to create different users for your library, with different types of roles. • Check that, when you create a new user, the simple view is automatically correctly updated to show the new total number of books borrowed by all users. • Also use the “get book” view to check that the users are correctly created with the correct names and correct number of books. • Also check that trying to create a borrower with a negative number of books correctly shows an error message. Also check that trying to create a user with a number of books which is not an integer correctly shows an error message (do not worry about the content of the error message). After you created a new user, you can also check whether it is a lender or a borrower using the “more book” view to increase the number of books of the user by a big negative number: • if the new user you created is a lender, then increasing the number of books by a big negative value will work and the number of books borrowed by the user will just become a larger value (you can then check that using the “get book” view); • if the new user you created is a borrower, then increasing the number of books by a big negative value will fail with an error message and the number of books borrowed by the user will not change (you can then check that using the “get book” view). 完成符合以上要求的java代码

模拟银行账户存款、取款和查询功能,账户余额最少保留10元,存款为负数是无效。 要求:用异常处理存款出现负数和余额小于10元的情况 按照任务描述,要求如下: 定义银行类Bank,五个属性账号countNo、地址address、余额balance、最小存款min默认值为10、储户姓名name,一个构造方法初始化账号、地址、余额、姓名,三个方法:存款void save(double num)、取款boolean take(double num)、查询double query()。 定义异常类DepositException——当无效钱数(小于0)存入时。该类继承Exception,覆盖public String toString()方法,返回提示信息“存款不能为负数”。 定义异常类OverDrawnException——当取出钱后余额小于10的情况。该类继承Exception,覆盖public String toString()方法,返回提示信息“账户余额最少保留10元”。 修改void save(double num)方法,如果发现num小于0,则抛出一个DepositException异常,并在save方法中声明异常自身不处理,由调用它的函数(这里是TestBank类的main()方法)处理 修改Bank类的boolean take(double num)方法。如果发现(余额-num)<10则抛出一个OverDrawnException,并在take方法中进行捕获,捕获后打印异常的toString返回的信息。 测试类TestBank,写代码实现下列过程。新建一个账户,开户信息为“001”、“张三”、“天源路789号”,200,存入90元,再存入-90元,取款281元,再取款280元。捕获所有可能发生的异常

最新推荐

recommend-type

Java开发案例-springboot-19-校验表单重复提交-源代码+文档.rar

Java开发案例-springboot-19-校验表单重复提交-源代码+文档.rar Java开发案例-springboot-19-校验表单重复提交-源代码+文档.rar Java开发案例-springboot-19-校验表单重复提交-源代码+文档.rar Java开发案例-springboot-19-校验表单重复提交-源代码+文档.rar Java开发案例-springboot-19-校验表单重复提交-源代码+文档.rarJava开发案例-springboot-19-校验表单重复提交-源代码+文档.rar Java开发案例-springboot-19-校验表单重复提交-源代码+文档.rar
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

HSV转为RGB的计算公式

HSV (Hue, Saturation, Value) 和 RGB (Red, Green, Blue) 是两种表示颜色的方式。下面是将 HSV 转换为 RGB 的计算公式: 1. 将 HSV 中的 S 和 V 值除以 100,得到范围在 0~1 之间的值。 2. 计算色相 H 在 RGB 中的值。如果 H 的范围在 0~60 或者 300~360 之间,则 R = V,G = (H/60)×V,B = 0。如果 H 的范围在 60~120 之间,则 R = ((120-H)/60)×V,G = V,B = 0。如果 H 的范围在 120~180 之间,则 R = 0,G = V,B =
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

MATLAB柱状图在数据分析中的作用:从可视化到洞察

![MATLAB柱状图在数据分析中的作用:从可视化到洞察](https://img-blog.csdnimg.cn/img_convert/1a36558cefc0339f7836cca7680c0aef.png) # 1. MATLAB柱状图概述** 柱状图是一种广泛用于数据可视化的图表类型,它使用垂直条形来表示数据中不同类别或组别的值。在MATLAB中,柱状图通过`bar`函数创建,该函数接受数据向量或矩阵作为输入,并生成相应的高度条形。 柱状图的优点在于其简单性和易于理解性。它们可以快速有效地传达数据分布和组别之间的比较。此外,MATLAB提供了广泛的定制选项,允许用户调整条形颜色、
recommend-type

已知自动控制原理中通过更高的频率特征来评估切割频率和库存——相位稳定。确定封闭系统的稳定性。求Wcp 和ψ已知W(p)=30•(0.1p+1)•(12.5p+1)/p•(10p+1)•(0.2p+1)•(p+1)

根据相位稳定的定义,我们需要找到一个频率 Wcp,使得相位满足 -ψ = -180°,即 ψ = 180°。此时系统的相位裕度为 0°,系统处于边缘稳定状态。 首先,我们需要将 W(p) 表示成极点和零点的形式。将分母和分子分别因式分解,得到: W(p) = 30 • (0.1p+1) • (12.5p+1) / [p • (10p+1) • (0.2p+1) • (p+1)] = 375p/(p+1) - 3750/(10p+1) + 750p/(0.2p+1) - 3750p/(10p+1) + 150p/(p+1) + 30 因此,系统的极点为 -1、-0.1、-0.2、
recommend-type

c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf

校园超市商品信息管理系统课程设计旨在帮助学生深入理解程序设计的基础知识,同时锻炼他们的实际操作能力。通过设计和实现一个校园超市商品信息管理系统,学生掌握了如何利用计算机科学与技术知识解决实际问题的能力。在课程设计过程中,学生需要对超市商品和销售员的关系进行有效管理,使系统功能更全面、实用,从而提高用户体验和便利性。 学生在课程设计过程中展现了积极的学习态度和纪律,没有缺勤情况,演示过程流畅且作品具有很强的使用价值。设计报告完整详细,展现了对问题的深入思考和解决能力。在答辩环节中,学生能够自信地回答问题,展示出扎实的专业知识和逻辑思维能力。教师对学生的表现予以肯定,认为学生在课程设计中表现出色,值得称赞。 整个课程设计过程包括平时成绩、报告成绩和演示与答辩成绩三个部分,其中平时表现占比20%,报告成绩占比40%,演示与答辩成绩占比40%。通过这三个部分的综合评定,最终为学生总成绩提供参考。总评分以百分制计算,全面评估学生在课程设计中的各项表现,最终为学生提供综合评价和反馈意见。 通过校园超市商品信息管理系统课程设计,学生不仅提升了对程序设计基础知识的理解与应用能力,同时也增强了团队协作和沟通能力。这一过程旨在培养学生综合运用技术解决问题的能力,为其未来的专业发展打下坚实基础。学生在进行校园超市商品信息管理系统课程设计过程中,不仅获得了理论知识的提升,同时也锻炼了实践能力和创新思维,为其未来的职业发展奠定了坚实基础。 校园超市商品信息管理系统课程设计的目的在于促进学生对程序设计基础知识的深入理解与掌握,同时培养学生解决实际问题的能力。通过对系统功能和用户需求的全面考量,学生设计了一个实用、高效的校园超市商品信息管理系统,为用户提供了更便捷、更高效的管理和使用体验。 综上所述,校园超市商品信息管理系统课程设计是一项旨在提升学生综合能力和实践技能的重要教学活动。通过此次设计,学生不仅深化了对程序设计基础知识的理解,还培养了解决实际问题的能力和团队合作精神。这一过程将为学生未来的专业发展提供坚实基础,使其在实际工作中能够胜任更多挑战。