SpringBoot学习笔记.docx_第1页
SpringBoot学习笔记.docx_第2页
SpringBoot学习笔记.docx_第3页
SpringBoot学习笔记.docx_第4页
SpringBoot学习笔记.docx_第5页
已阅读5页,还剩8页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

SpringBoot学习笔记此文包含:如何新建一个Springboot项目、如何返回视图(字符串/JSON)、怎么支持velocity/JSP页面、怎么链接数据库,实现基本的增删改查、前端如何往后端传递数据,后端如何往前段传递数据,配置日志Logger框架,安全控制Security,以及几种常用的定时任务的使用,如何部署项目。1、新建项目:新建一个maven项目即可,然后修改pom文件,添加以下依赖,是做web必须的 org.springframework.boot spring-boot-starter-web 2、返回字符串 新建一个ControllerEnableAutoConfiguration /自动配置ControllerRequestMapping(value = /hi)public class Application private static final Logger logger = LoggerFactory.getLogger(Application.class);/日志 RequestMapping(value = /hello) ResponseBody /返回字符,JSON等 public String hi() System.out.print(=); return 我是一个字符串; public static void main(String args) SpringApplication.run(Application.class, args); 此时运行localhost:8080/hi/hello即可看到 “我是一个字符串”,表示boot项目配置成功3、添加视图支持,可以返回数据在页面,此处使用是velocity,首先添加依赖:org.springframework.bootspring-boot-starter-velocityController中添加一个方法:此时会在resources/templates/文件夹下面找login.vm返回RequestMapping(value = /login, method = RequestMethod.GET)public String loginGet(String username, String password) return login;4、在视图中显示数据RequestMapping(value = /login, method = RequestMethod.GET)public String login(String username, String password, Map map) map.put(username, username); Date d = new Date(); map.put(time, d.toLocaleString(); (准备转发进去);/打印日志在日志文件里 return hi;5、前台显示后台传递的数据 hello:$username,现在时间:$time/也可以不带6、使用日志Logger 添加依赖: 在这个里面添加下面的2个2.5 1.1.5 org.apache.logging.log4j log4j-api $log4j.version org.apache.logging.log4j log4j-core $log4j.version ch.qos.logback logback-classic $perties里面配置logging.file=SpringBoot/src/log/app.log /我写的是项目名目录下.springframework.web=DEBUG具体Controller这样写import org.slf4j.Logger; /是这2个包,不是阿帕奇的import org.slf4j.LoggerFactory;private static final Logger logger = LoggerFactory.getLogger(MyApplication.class);RequestMapping(value = /login, method = RequestMethod.GET)public String login(String username, String password, Map map) map.put(username, username); Date d = new Date(); map.put(time, d.toLocaleString(); (准备转发进去);/打印日志在日志文件里 return hi;7、使用JPA(Hibernate)操作数据库 1.添加依赖,和Mysql依赖perties这样配置#数据库信息 spring.datasource.url = jdbc:mysql:/localhost:3306/testspring.datasource.username = rootspring.datasource.password = rootspring.datasource.driverClassName = com.mysql.jdbc.Driver#数据库类型spring.jpa.database = MYSQL#格式化sql语句spring.jpa.show-sql = true#每次启动是更新表还是创建表 (create, create-drop, update)2个都可以用,个人感觉第二个好用spring.jpa.hibernate.ddl-auto = perties.hibernate.hbm2ddl.auto=update spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy#数据库方言perties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect3.直接写一个接口,UserDao继承 JpaRepository,不需要实现类,不需要service层,此类即可操作数据库,自带很多方法,也能够支持解析方法名称进行查询。在需要使用的时间直接Autowired即可Transactionalpublic interface UserDao extends JpaRepository User findByName(String name); /解析方法名称查询 .注意JPA命名规范Query(from User u where =:name) /支持自定义查询User findUser(Param(name) String name);4.具体Controller中这样用Autowiredprivate UserDao userServiceImpl; List users = new ArrayList(); users = userServiceImpl.findAll();5.这个JpaRepository提供了很多方法,如截图:8、security安全机制 1.pom文件添加依赖org.springframework.bootspring-boot-starter-security 2.perties配置用户名密码(打开网站的时候需要输入)#安全控制=adminsecurity.user.password=admin9、拦截器配置 1.自定义一个拦截器 写一个类继承HandlerInterceptorAdapter类,重写preHandle(请求发生前执行)和postHandle(请求完成后执行)public class inteceptor extends HandlerInterceptorAdapter private static Set path = new HashSet();static / 不拦截的路径path.add(/login.vm);path.add(/home); /* * 拦截请求前,此处可设置session,characterEncoding */Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception long start = System.currentTimeMillis();request.setAttribute(start, start);if (path.contains(request.getRequestURI() System.out.println(URL: + request.getRequestURI();return true;System.out.println(-redirect);response.sendRedirect(login.vm);return false;/* * 拦截请求完成后执行的操作 */Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception long start = (long) request.getAttribute(start);long now = System.currentTimeMillis();System.out.println(-: + (now - start);request.setAttribute(time, new Date().toLocaleString();2.注册拦截器 写一个类继承WebMvcConfigurerAdapter ,重写addInterceptors方法,把自定义的拦截器add进去即可Configurationpublic class WebConfig extends WebMvcConfigurerAdapter /* * 注册拦截器,方法是不能改名字的,因为是重写的 */Overridepublic void addInterceptors(InterceptorRegistry registry) registry.addInterceptor(new inteceptor();/inteceptor类是我自定义的拦截器类System.out.println(拦截器注册完成.);10、定时任务(springboot自带)还有是java内的。只需要写一个定时任务的类,然后在方法里面启动需要执行的任务即可,一个类可以定多个定时任务Configuration EnableScheduling / 标注启动定时任务public class SchudelTime /* * cron内容分别是:秒,分,时,天,月,星期,年(可以省略年) */Scheduled(cron = 0/20 * * * * ?) / 每隔20秒执行一次public void doTask() System.out.println(-每隔20秒执行一次 at: + new Date().toLocaleString();Scheduled(fixedRate = 1000 * 30) / 每隔30秒执行一次public void reportCurrentTime() System.out.println(每隔30秒执行一次: The time is now + new Date().toLocaleString();Scheduled(fixedRate = 1000 * 60, initialDelay = 1000) / 每隔1分钟执行一次,延迟1秒执行public void updatePayRecords() System.out.println(每隔1分钟执行一次,延迟1秒执行: The time is now + new Date().toLocaleString();11、定时任务,使用 ScheduledExecutorService 思路:新建一个类,在这个类的方法里创建定时任务调度器,然后使用调度器自带的方法执行具体的任务(是类,不是方法),这个类需要实现Runable接口 /* * 链接服务端接口的定时任务 * Created by server on 2016/9/2. */public class LinkServerScheduled public static void scheduleWithFixedDelay() ScheduledExecutorService schedule = Executors.newScheduledThreadPool(5); /延迟10秒,以后每隔30秒执行一次 . schedule.scheduleWithFixedDelay(new UpdateTask(), 10, 30, TimeUnit.SECONDS); / schedule不止scheduleWithFixedDelay一个方法,很多种下面是UpdateTask类public class UpdateTask implements Runnable private static final Logger logger = LoggerFactory.getLogger(UpdateTask.class); Override public void run() System.out.println(=begin do something:- + new Date().toLocaleString();12、定时任务 使用Timer 可以指定时间点执行,比如10点10分 写一个普通类,里面有具体执行定时任务的方法,在这个方法中new定时任务管理器,启动定时任务,设置时间。public class TimerDemo public void dosomething() Calendar calendar = Calendar.getInstance();calendar.set(Calendar.HOUR_OF_DAY, 16); / 时calendar.set(Calendar.MINUTE, 17);/ 分calendar.set(Calendar.SECOND, 00); / 秒Date date = calendar.getTime(); / 第一次执行定时任务的时间/ 如果第一次执行定时任务的时间 小于当前的时间/ 此时要在 第一次执行定时任务的时间加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。if (date.before(new Date() calendar.add(Calendar.DAY_OF_MONTH, 1);date = this.addDay(date, 1);System.out.println(exe Time: + date.toLocaleString();Timer timer = new Timer();TimerTask task = new TimerTask();/ 具体的任务类timer.schedule(task, date, 10000);/ 任务类,第一次执行时间点,延迟时间/ 增加或减少天数public static Date addDay(Date date, int num) Calendar startDT = Calendar.getInstance();startDT.setTime(date);startDT.add(Calendar.DAY_OF_MONTH, num);return startDT.getTime();具体执行的类,继承TimerTask类,在其run方法里进行操作,写具体的定时

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论