
暂无个人介绍
1. 在Project项目中![image],找到.idea的目录下的workspace 2. 打开文件,查找RunDashBoard,找到 component标签name属性为RunDashboard,在该标签内添加如代码 <option name="configurationTypes"> <set> <option value="SpringBootApplicationConfigurationType" /> </set> </option> 3. 效果如下,使用非常方便 • 参考网址:http://www.cnblogs.com/july4/p/9279996.html
重载 : 在同一个类中,拥有多个相同名的方法,但是这些方法的参数列表不同(参数个数,参数类型) (即:方法名相同,参数列表不同,返回值类型可以不同!) 重写 : 在子父类之间,子类有父类相同名的方法 (即:方法名,参数列表和返回值类型都相同)
1.导包(坐标) <!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!-- 配置使用redis启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 2.使用 2.1存数据: @Autowired private RedisTemplate<String, String> redisTemplate; public void run(){ /* 参数一: key 参数二:value 参数三:title 参数四:时间类型 */ redisTemplate.opsForValue().set(customer.getTelephone(), activecode, 24,TimeUnit.HOURS); } 2.2取数据 String getUUid = redisTemplate.opsForValue().get(telephone);
-1.导包(坐标) <!-- 导入javamail的坐标 javax--> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> -2.公共工具配置 package com.czxy.bos.util; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class MailUtil { public static void sendMail(String to,String subject,String text) throws Exception{ //1 创建属性对象 Properties props = new Properties(); //2 设置邮件服务器的地址 smtp.163.com smtp.126.com smtp.qq.com smtp.gmail.com props.put("mail.smtp.host","smtp.163.com"); //3 设置是否打开校验 , 是否验证用户名和密码 必须要设置为 true props.put("mail.smtp.auth",true); //4 获取与邮件服务器的连接 Session session = Session.getDefaultInstance(props); //5 新建一封邮件 MimeMessage message = new MimeMessage(session); //6 设置发送者 InternetAddress fromAddress = new InternetAddress("sqczdx@163.com"); message.setFrom(fromAddress); //7 设置接收者 InternetAddress toAddress = new InternetAddress(to); // to 接收者 cc 抄送 bcc 密送 message.setRecipient(Message.RecipientType.TO,toAddress); //8 设置主题 message.setSubject(subject); //9 设置正文 // message.setText(text); //第一个参数:内容 //第二个参数:内容格式 message.setContent(text,"text/html;charset=utf-8"); //10 坐火箭 Transport transport = session.getTransport("smtp");//参数必须添加 transport.connect("sqczdx@163.com","q7w8e9a4s5d6");// 密码是授权码 // 所有的接收者 to cc bcc transport.sendMessage(message,message.getAllRecipients()); // 关闭连接 transport.close(); System.out.println("ok"); } public static void main(String[] args) { try { MailUtil.sendMail("1638064027@qq.com","好好学习","天天向上"); } catch (Exception e) { e.printStackTrace(); } } } 3.使用 // 拼接链接地址 String activeUrl = Constants.FORE_MANAGEMENT_HOST + "/regist/activeMail?telephone="+customer.getTelephone()+"&activeCode="+activeCode; String content = "<a href='"+activeUrl+"'>速运快递账号激活</a>"; // 发送邮件 try { MailUtil.sendMail(customer.getEmail(),"世纪佳缘网账号激活",content); } catch (Exception e) { e.printStackTrace(); }
1.导包 <!-- 引入阿里大鱼的jar包 --> <dependency> <groupId>com.aliyuncs</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>com.aliyuncs.dysmsapi</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.0.0</version> </dependency> 2.配置Utils 公共类 package com.czxy.bos.util; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest; import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.dysmsapi.transform.v20170525.SendSmsResponseUnmarshaller; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpResponse; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; /** * Created on 17/6/7. * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可) * 工程依赖了2个jar包(存放在工程的libs目录下) * 1:aliyun-java-sdk-core.jar * 2:aliyun-java-sdk-dysmsapi.jar * * 备注:Demo工程编码采用UTF-8 * 国际短信发送请勿参照此DEMO */ public class SmsUtil { //产品名称:云通信短信API产品,开发者无需替换 static final String product = "Dysmsapi"; //产品域名,开发者无需替换 static final String domain = "dysmsapi.aliyuncs.com"; // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找) static final String accessKeyId = "自己的key"; static final String accessKeySecret = "自己的key"; public static SendSmsResponse sendSms(String telephone,String code) throws ClientException { //可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); //初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); //组装请求对象-具体描述见控制台-文档部分内容 SendSmsRequest request = new SendSmsRequest(); //必填:待发送手机号 request.setPhoneNumbers(telephone); //必填:短信签名-可在短信控制台中找到 request.setSignName("老袁a洗脚6"); //必填:短信模板-可在短信控制台中找到 request.setTemplateCode("SMS_85550034"); //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.setTemplateParam("{\"code\":\""+code+"\"}"); //选填-上行短信扩展码(无特殊需求用户请忽略此字段) //request.setSmsUpExtendCode("90997"); //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 request.setOutId("yourOutId"); //hint 此处可能会抛出异常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); return sendSmsResponse; } public static void main(String[] args) throws ClientException, InterruptedException { //发短信 SendSmsResponse response = sendSms("15151772559","6987"); System.out.println("短信接口返回的数据----------------"); System.out.println("Code=" + response.getCode()); System.out.println("Message=" + response.getMessage()); System.out.println("RequestId=" + response.getRequestId()); System.out.println("BizId=" + response.getBizId()); } } 3.使用方法 public void recive(Message message) { try { /* 参数一:手机号 参数二:短信验证码 */ //发送短信,调用SMSutil SmsUtil.sendSms(message.telephone,message.code); } catch (Exception e) { } }
-1.导包 <!-- ActiveMQ的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> -2.配置信息 @Configuration public class ActiveMQConfig { // 提供生产bean的方法 @Bean public Queue createQueue() { return new ActiveMQQueue("bos.queue"); } @Bean public Topic createTopic() { return new ActiveMQTopic("bos.topic"); } } -3.使用 --生产者 @Autowired private Queue queue; @Autowired private JmsMessagingTemplate jmsMessagingTemplate; public void run(){ /* 前台获取数据 telephone:137****7790 code:*** */ //准备消息 ActiveMQMapMessage mapMessage = new ActiveMQMapMessage(); mapMessage.setString("telephone",telephone); mapMessage.setString("code",code); //发送消息 jmsMessagingTemplate.convertAndSend(queue,mapMessage); } -4.消费者 --消费 package com.czxy.sms.consumer; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; import javax.jms.MapMessage; import javax.jms.Message; @Component public class SmsConsumer { @JmsListener(destination = "java1.bos.sms") public void recive(Message message) { try { MapMessage mapMessage = (MapMessage) message; String telephone = mapMessage.getString("telephone"); String code = mapMessage.getString("code"); System.out.println(telephone + ":" + code); // 发送短信,调用SMSutil // SmsUtil.sendSms(telephone,code); } catch (Exception e) { } } }
-1. Excel (POI) 1.1 导入poi报表需要的jar包 <poi.version>3.11</poi.version> <!-- <!-- Excel解析工具类 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>${poi.version}</version> </dependency> --> <!-- excel2003使用的包 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.11</version> </dependency> <!-- excel2007+使用的包 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.11</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.11</version> </dependency> 1.2.访问 $("#exportXlsBtn").click(function(){ // 下载效果 不能是ajax异步 <!-- $.ajax({ type: "GET", url: "/report/exportXls" }); --> location.href = "/excelInpost/downLoad?filename=运单模板表.xlsx"; }); 1.3 用法(页面) <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>运单批量导入</title> <!-- 导入jquery核心类库 --> <script type="text/javascript" src="../../js/jquery-1.8.3.js"></script> <!-- 导入easyui类库 --> <link rel="stylesheet" type="text/css" href="../../js/easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="../../js/easyui/themes/icon.css"> <link rel="stylesheet" type="text/css" href="../../js/easyui/ext/portal.css"> <link rel="stylesheet" type="text/css" href="../../css/default.css"> <script type="text/javascript" src="../../js/easyui/jquery.easyui.min.js"></script> <script type="text/javascript" src="../../js/easyui/ext/jquery.portal.js"></script> <script type="text/javascript" src="../../js/easyui/ext/jquery.cookie.js"></script> <script src="../../js/easyui/locale/easyui-lang-zh_CN.js" type="text/javascript"></script> <script type="text/javascript" src="../../js/jquery.ocupload-1.1.2.js"></script> <script type="text/javascript"> $(function(){ $("#grid").datagrid({ url : '/wayBill/pageQuery', method:"GET", toolbar : [ { id : 'btn-download', text : '模板下载', iconCls : 'icon-save', handler : function(){ $.messager.confirm("提示","您确定下载模板吗?",function () { location.href = "/excelInpost/downLoad?filename=运单模板表.xlsx"; }) } },{ id : 'btn-upload', text : '批量导入', iconCls : 'icon-redo' },{ id : 'btn-refresh', text : '刷新', iconCls : 'icon-reload', handler : function(){ $("#grid").datagrid('reload'); } } ], columns : [[ { field : 'id', title : '编号', width : 120 , align : 'center' },{ field : 'goodsType', title : '产品', width : 120 , align : 'center' },{ field : 'sendProNum', title : '快递产品类型', width : 120 , align : 'center' },{ field : 'sendName', title : '发件人姓名', width : 120 , align : 'center' },{ field : 'sendMobile', title : '发件人电话', width : 120 , align : 'center' },{ field : 'sendAddress', title : '发件人地址', width : 120 , align : 'center' },{ field : 'recName', title : '收件人姓名', width : 120 , align : 'center' },{ field : 'recMobile', title : '收件人电话', width : 120 , align : 'center' },{ field : 'recCompany', title : '收件人公司', width : 120 , align : 'center' },{ field : 'recAddress', title : '收件人地址', width : 120 , align : 'center' } ]], pageList: [10,20,30], pagination : true, striped : true, singleSelect: true, rownumbers : true, fit : true // 占满容器 }); /*// 一键上传 $("#btn-upload").upload({ name: 'upload', // <input name="file" /> action: '/excelInpost/excelUp', // 提交请求action路径 enctype: 'multipart/form-data', // 编码格式 autoSubmit: true, // 选中文件提交表单 onComplete: function(response) { if(response=="success"){ $.messager.alert("提示信息","数据导入成功!","info"); $("#grid").datagrid("reload"); }else{ $.messager.alert("错误提示",response,"error"); } }// 请求完成时 调用函数 });*/ $("#btn-upload").upload({ action:"/excelInpost/excelUp", name:"myFile", onComplete:function () { $.messager.alert("提示信息","数据导入成功!","info"); $("#grid").datagrid("reload"); }, onSelect:function () { // 如果文件名字不符合要求,就阻止提交, // 1 关闭默认的自动提交 this.autoSubmit = false; // 2 获取文件名 var filename = this.filename(); // 3 正则表达式校验 // . 1个换行符意外的任意字符 // * 0-n个任意字符 // \. 标识. // (a|b) 只能出现a或者b var regex = /^.*\.(xls|xlsx)$/; // 校验 if (regex.test(filename)) { // 手动提交 this.submit(); }else{ // 不符合规则,不提交,给出提醒 $.messager.alert("提示","请选择xls或者xlsx结尾的文件") } } }) }); </script> </head> <body class="easyui-layout"> <div region="center"> <table id="grid"></table> </div> </body> </html> 1.4 用法(后台) --->自定义模板下载 /** * 模板下载 * @param filename 文件名 * @return * @throws Exception */ @GetMapping("/downLoad") public ResponseEntity<String> downLoadExcel(String filename) throws Exception { System.out.println(filename+"-------------------------------------------------------"); /** * 查找数据之后,下面只需要将内容写进xls中,然后下载 */ //1 创建工作簿 Workbook wb = new XSSFWorkbook(); //2 创建工作表 Sheet sheet = wb.createSheet(); /** * 定义公共变量 */ int rowNo=0,cellNo=0;//行号 和 列号 Row nRow = null;// 行对象通用变量 Cell nCell = null;// 单元格对象通用变量 /****************大标题打印****************/ //3 创建行 nRow = sheet.createRow(rowNo); // 设置行高 nRow.setHeightInPoints(36); //4 创建单元格 nCell = nRow.createCell(cellNo); //5 设置内容 nCell.setCellValue("运单数据"); //6 设置内容格式 // 合并单元格 //参数1:起始行 参数2:终止行 参数3:起始列 参数4:终止列 sheet.addMergedRegion(new CellRangeAddress(0, 0, (short) 0, (short) 9)); // 样式 CellStyle bigTitleCellStyle = bigTitleStyle(wb); nCell.setCellStyle(bigTitleCellStyle); rowNo++; nRow = sheet.createRow(rowNo); //小标题 String[] titles={"编号","产品","快递产品类型","发件人姓名","发件人电话","发件人地址","收件人姓名","收件人电话","收件人公司","收件人地址"}; for (int i = 0;i<titles.length;i++){ String title = titles[i]; //4 创建单元格 nCell = nRow.createCell(cellNo++);// 先创建单元格,然后在新增 //5 设置内容 nCell.setCellValue(title); //6 设置内容格式 nCell.setCellStyle(titleStyle(wb)); //设置列宽 -->自动 sheet.autoSizeColumn(i); sheet.setColumnWidth(i,sheet.getColumnWidth(i)*17/10); } //下载 DownloadUtil downloadUtil = new DownloadUtil(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); wb.write(byteArrayOutputStream); downloadUtil.download(byteArrayOutputStream,response,filename); return new ResponseEntity<>(HttpStatus.OK); } 1.5 上传导入 /** * 导入 * @return */ @RequestMapping("/excelUp") public ResponseEntity<Void> batchImport(@RequestParam("myFile") MultipartFile file){ try { // 1.1 获取文件名 String originalFilename = file.getOriginalFilename();// 文件名 String name = file.getName();//此名字对应<input> 文本框的name属性的值 // 1.2 设置保存的path String path = "d:\\"+ UUID.randomUUID().toString()+originalFilename; // 1.3 创建File--path File myFile = new File(path); // 1.4 复制 file.transferTo(myFile); // 解析xls,将数据存入数据库 // 2 创建Workbook // 2.1 创建输入流 FileInputStream is = new FileInputStream(myFile); // InputStream is = file.getInputStream(); // 2.2 创建Workbook Workbook wb = new XSSFWorkbook(is); // 3 获取Sheet Sheet sheet = wb.getSheetAt(0); // 定义List集合存放数据,最后一次性保存 List<WayBill> list = new ArrayList<>(); // 4 获取row for(Row row:sheet){ // 5 获取单元格数据 // 跳过第一行 if(row.getRowNum()==0 || row.getRowNum()==1){ continue; } // 如果第一列为空,整条数据都不读取 if(row.getCell(0)==null || (int) row.getCell(0).getNumericCellValue()==0){ continue; } WayBill wayBill = new WayBill(); //编号 int value0 = (int) row.getCell(0).getNumericCellValue(); wayBill.setId(value0); //产品 wayBill.setGoodsType(row.getCell(1).getStringCellValue()); //快递产品类型 wayBill.setSendProNum(row.getCell(2).getStringCellValue()); //发件人姓名 wayBill.setSendName(row.getCell(3).getStringCellValue()); //发件人电话 String value4 =""+ (int) row.getCell(4).getNumericCellValue(); wayBill.setSendMobile(value4); //发件人地址 wayBill.setSendAddress(row.getCell(5).getStringCellValue()); //收件人姓名 wayBill.setRecName(row.getCell(6).getStringCellValue()); //收件人电话 wayBill.setRecMobile(""+ (int) row.getCell(7).getNumericCellValue()); //收件人公司 wayBill.setRecCompany(row.getCell(8).getStringCellValue()); //收件人地址 wayBill.setRecAddress(row.getCell(9).getStringCellValue()); list.add(wayBill); } // 6 保存至数据库 wayBillService.saveWayBillAll(list); }catch (Exception e){ e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(HttpStatus.OK); } public CellStyle bigTitleStyle(Workbook wb){ // 创建格式 CellStyle cellStyle = wb.createCellStyle(); // 水平对齐方式 cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 垂直居中 cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 设置字体 Font font = wb.createFont(); // 是数值的1/20 大小 font.setFontHeight((short) 480); font.setBold(true); font.setColor(Font.COLOR_RED); cellStyle.setFont(font); return cellStyle; } public CellStyle titleStyle(Workbook wb){ CellStyle cellStyle = wb.createCellStyle(); cellStyle.setBorderTop(CellStyle.BORDER_THIN); cellStyle.setBorderRight(CellStyle.BORDER_THIN); cellStyle.setBorderBottom(CellStyle.BORDER_THIN); cellStyle.setBorderLeft(CellStyle.BORDER_THIN); Font font = wb.createFont(); font.setFontHeight((short)300); cellStyle.setFont(font); return cellStyle; }
1.2 整合shiro1.2.1 maven坐标步骤1:在common-parent项目中,添加maven坐标 <!--shiro start--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency> <!--shiro end--> 1.2.2 配置过滤器使用Shiro时,需要配置的相关权限过滤器如下(共10个): anon: 匿名过滤器,未登陆也可以访问 authc: 认证过滤器, 登陆后访问 perms : 需要xx权限,才能访问 roles: 需要xx角色,才能访问 user: 需要xx用户,才能访问 port:指定端口才能访问 ssl:必须使用https协议才能访问 logout :登出功能 rest :根据指定HTTP请求访问才能访问 ,get方式提交 或者 post方式提交才能访问 可 1.2.3 配置config类shiro的配置步骤 1 配置安全管理器SecurityManager2 realm域配置:由于SecurityManger需要使用realm域,涉及到用户信息、权限信息,处理用户信息的时候需要加密 3 密码比较器:用户输入的铭文进行加密,并且与数据库中的密文进行比较 4 配置生成过滤器的工厂类 /** * 在ShiroConfig中做什么事情呢? * 1 配置shiro安全管理器,向安全管理器中注入Realm域 * 2 配置Realm域:注入密码比较器 * 3 配置密码比较器 * 4 配置拦截路径和放行路径 */ @Configuration public class ShiroConfig { /** * 配置安全管理器,并且注入Realm域 * @param realm * @return */ @Bean public SecurityManager securityManager(Realm realm){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(realm); return securityManager; } /** * Credentials:凭证/证书 --- * * 配置Realm域,注入密码比较器 * @param credentialsMatcher * @return */ @Bean public BosRealm realm(CredentialsMatcher credentialsMatcher){ BosRealm bosRealm = new BosRealm(); bosRealm.setCredentialsMatcher(credentialsMatcher); return bosRealm; } /** * 密码比较器 * * @return */ @Bean public CredentialsMatcher credentialsMatcher(){ // return new HashedCredentialsMatcher("MD5"); return new BosCredentialsMatcher(); } /** * 配置拦截路径和放行路径 * @param securityManager * @return */ @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager){ System.out.println("ShiroConfiguration.shirFilter()"); // shiro过滤器工厂类 ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // 必须设置 SecurityManager shiroFilterFactoryBean.setSecurityManager(securityManager); //拦截器----Map集合 Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>(); //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 filterChainDefinitionMap.put("/login*", "anon"); filterChainDefinitionMap.put("/user/login*", "anon"); filterChainDefinitionMap.put("/validatecode.jsp*", "anon"); filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/js/**", "anon"); filterChainDefinitionMap.put("/images/**", "anon"); filterChainDefinitionMap.put("/data/**", "anon"); // /** 匹配所有的路径 // 通过Map集合组成了一个拦截器链 ,自顶向下过滤,一旦匹配,则不再执行下面的过滤 // 如果下面的定义与上面冲突,那按照了谁先定义谁说了算 // /** 一定要配置在最后 filterChainDefinitionMap.put("/**", "authc"); // 将拦截器链设置到shiro中 shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 shiroFilterFactoryBean.setLoginUrl("/login.html"); // 登录成功后要跳转的链接 shiroFilterFactoryBean.setSuccessUrl("/index.html"); //未授权界面; shiroFilterFactoryBean.setUnauthorizedUrl("/403"); return shiroFilterFactoryBean; } /** * 开启shiro aop注解支持 * 使用代理方式;所以需要开启代码支持 * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } /** * 开启cglib代理 * @return */ @Bean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); creator.setProxyTargetClass(true); return creator; } } 根据配置文件报错显示,需要创建如下文件: 1 BosRealm域2 BosCredentialsMatcher密码比较器 //自定义Realm ,实现安全数据 连接 public class BosRealm extends AuthorizingRealm { // 认证... @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) { System.out.println("shiro 认证管理... "); return null; } @Override // 授权... protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) { System.out.println("shiro 授权管理..."); return null; } } 1.2.5 编写密码比较器 public class BosCredentialsMatcher extends SimpleCredentialsMatcher { @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { System.out.println("密码比较器"); return false; } } 授权 //拦截器. Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>(); //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 filterChainDefinitionMap.put("/login*", "anon"); filterChainDefinitionMap.put("/validatecode.jsp*", "anon"); filterChainDefinitionMap.put("/user/login*", "anon"); filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/js/**", "anon"); filterChainDefinitionMap.put("/images/**", "anon"); filterChainDefinitionMap.put("/services/**", "anon"); filterChainDefinitionMap.put("/pages/base/courier**", "perms[courier:list]"); filterChainDefinitionMap.put("/pages/base/area**", "roles[base]"); //<!-- 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了; //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问--> filterChainDefinitionMap.put("/**", "authc"); // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 shiroFilterFactoryBean.setLoginUrl("/login.html"); // 登录成功后要跳转的链接 shiroFilterFactoryBean.setSuccessUrl("/index.html"); //未授权界面; shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized.html");```
首先:引入工具类: 可以自行添加/修改 public class Constants { public static final String TEST = "http://127.0.0.1:8080"; public static final String PRODUCT_MANAGEMENT_HOST = "http://127.0.0.1:8090"; } 引入HttpClient支持: @Autowired private RestTemplate restTemplate; 1.查询数据 :getForEntity(url,Object.class) 参数一: 需要调用服务的地址(可以携带数据) 参数二:String.class表示我希望返回的body类型是String 返回值类型: ResponseEntity*<*T*>* 或 ResponseEntity*<*T*>* @GetMapping("/findProductByPage") public ResponseEntity<String> findProductByPage(Integer page, Integer rows,Product product){ HttpStatus statusCode = null; try { String url = Constants.PRODUCT_MANAGEMENT_HOST+ "/product/findProductByPage?page="+page+"&rows="+rows+"&product="+product; ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);//跨服务器访问 statusCode = entity.getStatusCode();//获取状态码 String body = entity.getBody(); //获取返回数据 return new ResponseEntity<>(body,statusCode); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(statusCode); } } 2.保存数据: postForEntity(url,pojo,Object.class) 参数一:同上 参数二:传递的数据 参数三:同上*注意:该方法传递给跨服务器是 方法参数上需要加上@RequestBody 否则无法接受到数据 @PostMapping("/saveProduct") public ResponseEntity<String> saveProduct(Product product){ HttpStatus statusCode =null; try { JSONObject proJson = JSONObject.fromObject(product); String prodct = proJson.toString(); String url = Constants.PRODUCT_MANAGEMENT_HOST+"/product/saveProduct"; ResponseEntity<String> entity = restTemplate.postForEntity(url, prodct, String.class); String body = entity.getBody(); statusCode = entity.getStatusCode(); return new ResponseEntity<>(HttpStatus.CREATED); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(statusCode); } } //全部类:我使用的--->勿喷 @RestController @RequestMapping("/product") public class ProductController { @Autowired private RestTemplate restTemplate; @GetMapping("/findProductByPage") public ResponseEntity<String> findProductByPage(Integer page, Integer rows,Product product){ HttpStatus statusCode = null; try { String url = Constants.PRODUCT_MANAGEMENT_HOST+ "/product/findProductByPage?page="+page+"&rows="+rows+"&product="+product; ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class); statusCode = entity.getStatusCode();//获取状态码 String body = entity.getBody(); //获取返回数据 return new ResponseEntity<>(body,statusCode); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(statusCode); } } @PostMapping("/saveProduct") public ResponseEntity<String> saveProduct(Product product){ HttpStatus statusCode =null; try { JSONObject proJson = JSONObject.fromObject(product); String prodct = proJson.toString(); String url = Constants.PRODUCT_MANAGEMENT_HOST+"/product/saveProduct"; ResponseEntity<String> entity = restTemplate.postForEntity(url, prodct, String.class); String body = entity.getBody(); statusCode = entity.getStatusCode(); return new ResponseEntity<>(HttpStatus.CREATED); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(statusCode); } } }
1、导入maven坐标 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> 2、在bos_management中创建HttpClientConfig类 #The config for HttpClient http.maxTotal=300 http.defaultMaxPerRoute=50 http.connectTimeout=1000 http.connectionRequestTimeout=500 http.socketTimeout=5000 http.staleConnectionCheckEnabled=true 3、在类中编写代码 /** * HttpClient的配置类 * */ @Configuration @ConfigurationProperties(prefix = "http", ignoreUnknownFields = true) public class HttpClientConfig { private Integer maxTotal;// 最大连接 private Integer defaultMaxPerRoute;// 每个host的最大连接 private Integer connectTimeout;// 连接超时时间 private Integer connectionRequestTimeout;// 请求超时时间 private Integer socketTimeout;// 响应超时时间 /** * HttpClient连接池 * @return */ @Bean public HttpClientConnectionManager httpClientConnectionManager() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(maxTotal); connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); return connectionManager; } /** * 注册RequestConfig * @return */ @Bean public RequestConfig requestConfig() { return RequestConfig.custom().setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout) .build(); } /** * 注册HttpClient * @param manager * @param config * @return */ @Bean public HttpClient httpClient(HttpClientConnectionManager manager, RequestConfig config) { return HttpClientBuilder.create().setConnectionManager(manager).setDefaultRequestConfig(config) .build(); } @Bean public ClientHttpRequestFactory requestFactory(HttpClient httpClient) { return new HttpComponentsClientHttpRequestFactory(httpClient); } /** * 使用HttpClient来初始化一个RestTemplate * @param requestFactory * @return */ @Bean public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) { RestTemplate template = new RestTemplate(requestFactory); List<HttpMessageConverter<?>> list = template.getMessageConverters(); for (HttpMessageConverter<?> mc : list) { if (mc instanceof StringHttpMessageConverter) { ((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8")); } } return template; } public Integer getMaxTotal() { return maxTotal; } public void setMaxTotal(Integer maxTotal) { this.maxTotal = maxTotal; } public Integer getDefaultMaxPerRoute() { return defaultMaxPerRoute; } public void setDefaultMaxPerRoute(Integer defaultMaxPerRoute) { this.defaultMaxPerRoute = defaultMaxPerRoute; } public Integer getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } public Integer getConnectionRequestTimeout() { return connectionRequestTimeout; } public void setConnectionRequestTimeout(Integer connectionRequestTimeout) { this.connectionRequestTimeout = connectionRequestTimeout; } public Integer getSocketTimeout() { return socketTimeout; } public void setSocketTimeout(Integer socketTimeout) { this.socketTimeout = socketTimeout; } }