SpringBoot学习笔记整理-开发应用

本文测试代码下载:下载代码

1.springboot启动器(44个):

 	Spring-boot-starter-web---支持全栈式开发包括了 Tomcat和SpringMVC
	Spring-boot-starer-jdbc----以jdbc方式操作数据库
	Spring-boot-starter-redis ---支持redis键值操作数据库集合。等等

2.启动Spring-boot

 	普通类带main方法;
	@SpringBoootApplication;
	SpringApplication.run(类名.class,args);

3.编写启动器时注意点

 位置:启动器放在上级目录;原因Spring扫描带注解包默认为为自己及其子包

4.整合Servlet

方式一:servlet类加注解@WebServlet(name="XXXServlet", urlPatterns="/hello")
  	      在启动类加@ServletComponentScan//自动扫描@WebServlet并实例化
方式二:启动类加一个方法 

@Bean
public ServletRegistrationBean getServletRegistrationBean(){
	ServletRegistrationBean  bean = new ServletRegistrationBean (new XXXServlet());
	bean.addUrlMaping("/hello");
	return bean;
}

5.整合filter

方式一:filter类加注解@WebFilter(name=“XXXFilter”, urlPatterns={"*.do", ...})
        		  在启动类加@ServletComponentScan//自动扫描@WebServlet并实例化
方式二:启动类加一个方法 

	@Bean
	public FiltterRegistrationBean getFiltterRegistrationBean (){
		FiltterRegistrationBean bean = new FiltterRegistrationBean (new XXXFitler());
		bean.addUrlMaping(new String[]{"*.do", "*.jsp"});
		return bean;
	}

6.整合listener

方式一:filter类加注解@WebListener
        		  在启动类加@ServletComponentScan//自动扫描@WebServlet并实例化
方式二:启动类加一个方法 

@Bean
public SevletListenerRegistrationBean getSevletListenerRegistrationBean  (){
	SevletListenerRegistrationBean<T> bean = new SevletListenerRegistrationBean<T> (new T());
	bean.addUrlMaping(new String[]{"*.do", "*.jsp"});
	return bean;
}

7.访问静态目录

方式一:在src/main/resources目录下,添加文件夹static(存放静态资源包括图片、HTML等)
方式二:在src/main/webapp 

8.文件上传(和SpringMVC一样)
设置上传文件参数src/main/resorces/application.properties(.yml)

spring.http.multipart.maxFileSize = 200MB(文件最大值,默认10MB)
spring.http.multipart.maxRequestSize = 200MB(一次上传的总容量)

9.视图层技术(整合jsp)
添加坐标

		<!-- jstl 标签 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
		<!-- jasper jsp的处理引擎 -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>
	application.properties配置信息 
	spring.mvc.view.prefix=/WEB-INF/jsp 前缀
	spring.mvc.view.suffix=.jsp 后缀

10.视图层技术(整合freemarker)
添加坐标

		<!-- freemarker启动器的坐标 -->
		 <dependency>
    	   	 <groupId>org.springframework.boot</groupId>
      	  	<artifactId>spring-boot-starter-freemarker</artifactId>
    	</dependency>
    	
模板文件位置src/main/resources/templates下写ftl文件
templates:该目录是安全的,外界不能直接访问(存放需要渲染的文件)

11.视图层技术(整合Thymeleaf,spring官方推荐的)
添加坐标

 	<!-- thymeleaf启动器的坐标 -->
	 <dependency>
  	      <groupId>org.springframework.boot</groupId>
  	      <artifactId>spring-boot-starter-thymeleaf</artifactId>
   	 </dependency>
模板文件位置src/main/resources/templates下
Thymeleaf特点:通过他特定语法对HTML的标记渲染
可以修改Thymeleaf版本换高版本,因为低版本对标签有强约束(标签有开就必须有闭),导致一些错误;
  <properties>
   	   	<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    	<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
  </properties>
Thymeleaf的常用语法
	java:
       	  model.addAttribute("msg", "world");
    	  model.addAttribute("key", new Date());
	变量输出:
	th:text ---页面输出某个值
	th:vealue---可以将一个值放入input中
	字符串操作:
		原理:调用的实际上是Thymeleaf内置对象
		注意:调用内置对象一定要加#; 大部分内置对象都是s结尾(strings/numbers/dates)
			<span th:text="${#strings.isEmpty(msg)}"></span>
			<span th:text="${#strings.contains(msg,'9')}"></span>
			<span th:text="${#strings.startsWith(msg,'a')}"></span>
			<span th:text="${#strings.endsWith(msg,'a')}"></span>
			<span th:text="${#strings.length(msg)}"></span>
			<span th:text="${#strings.indexOf(msg,'h')}"></span>
			<span th:text="${#strings.substring(msg,13)}"></span>
			<span th:text="${#strings.substring(msg,13,14)}"></span>
			<span th:text="${#strings.toUpperCase(msg)}"></span>
			<span th:text="${#strings.toLowerCase(msg)}"></span>
	日期操作:
			<span th:text="${#dates.format(key)}"></span>
			<span th:text="${#dates.format(key,'yyy/MM/dd')}"></span>
			<span th:text="${#dates.year(key)}"></span>
			<span th:text="${#dates.month(key)}"></span>
			<span th:text="${#dates.day(key)}"></span>
	 条件判断:
			<span th:if="${msg}=='world'">世界</span>
			<div th:switch="${msg}">
				<span th:case="world">我的世界</span>
			</div>
 	集合遍历:
	java:
         	    model.addAttribute("msg", "world");
    	       	model.addAttribute("key", new Date());
    	      	List<User> users = new ArrayList<>();
   	     	    users.add(new User(1, "张三", 19));
   	     	    users.add(new User(2, "李四", 20));
   	      	    model.addAttribute("users", users);
				Map<Integer, User> maps = new HashMap<>();
    	     	maps.put(1, new User(2, "张三", 19));
				maps.put(2, new User(2, "李四", 20));
				model.addAttribute("maps", maps);
	thmeleaf:
				<tr th:each="u,var : ${list}">
					<td th:text="${u.userid}"></td>
					<td th:text="${u.username}"></td>
					<td th:text="${u.userage}"></td>
					<td th:text="${var.index}"></td>
					<td th:text="${var.count}"></td>
					<td th:text="${var.size}"></td>
					<td th:text="${var.even}"></td>
					<td th:text="${var.odd}"></td>
					<td th:text="${var.first}"></td>
					<td th:text="${var.last}"></td>
				</tr>
				<tr th:each="map : ${maps}">
                   	<td th:each="entity : ${map}" th:text="${entity.key}"></td>
                    <td th:each="entity : ${map}" th:text="${entity.value.name}"></td>
            	 </tr>
 	 获取作用域对象:
	Java:
     	    request.setAttribute("req", "req-value");
            request.getSession().setAttribute("ses", "ses-val");
            request.getSession().getServletContext().setAttribute("app", "app-value");
	thymeleaf:
    	    <span th:text="${#httpServletRequest.getAttribute('req')}"></span><br>
            <span th:text="${session.ses}"></span><br>
            <span th:text="${application.app}"></span><br>
             <!--<span th:text="${request.req}"></span><br>不能这样取值-->
  	 URL表达式:
			<a th:href="@{http://www.baidu.com}">绝对路径1</a> 等价于<a href="http://www.baidu.com">绝对路径2</a>
			<a th:href="@{/hello}">相对路径(相对于项目上下文的根)</a>
			<a th:href="@{~/project/hello}">相对路径(相对于服务器的根)</a>
			<a th:href="@{/hello(id=1,...)}">相对路径传递参数</a>

12.整合MyBatis
添加坐标

<!-- Mybatis启动器 -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.1.1</version>
</dependency>
<!-- mysql数据库驱动 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid数据库连接池 (阿里巴巴的)-->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.0.9</version>
</dependency>
    添加application.properties配置
	spring.datasource.driverClassName=com.mysql.jdbc.Driver
	spring.datasource.url=jdbc:mysql://localhost:3318/mydatabase
	spring.datasource.username=root
	spring.datasource.password=1111
	spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
	mybatis.type-aliases-package=com.ren.domain
 启动类再多加个@MapperScan("com.ren.mapper")//@MapperScan 用户扫描MyBatis的Mapper接口
 其他和Mybatis使用一样

13.异常处理方式
springboot提供了5种处理方式:

自定义错误页面;
	     springboot默认的处理异常的机制:springboot默认的已经提供了一套处理异常的机制,如果代码中出现异常;springboot会向/error的URL发请求,在springboot这种提供了一个叫BasicExceptionContoller来处理/error请求,然后跳转到error.html错误页面;
	     如果我们需要将所有异常调到自定义的页面;需要在src/main/resources/templates目录下,创建error.html页面,名字必须叫error
	     缺点:所有的异常都是这一个页面
@ExceptionHandler注解处理异常;
	       针对异常不同,跳转不同错误页面时,在Controller里加一个异常处理方法
 	       / **
	       * 该方法需要返回一个ModelAndView:目的是可以让我们封装异常信息以及视图的指定
	       * 参数Exception e:会将产生异常对象注入到方法中
	       */
	       @ExceptionHandler(value={XXXException.class,...})
	        public ModelAndView xxxExceptionHandler(Exception e){
		     	  ModelAndView mv = new ModelAndView ();
		     	  mv.addObject("error",  e.toString());
		      	  mv.setViewName("error1");
		          return mv;
	        }
	        缺点:只能处理当前Controller的异常
@ControllerAdvice和@ExceptionHandler注解处理异常;
	        解决所有Controller的异常处理,写一个异常处理类,并加上注解@ControllerAdriver;将上面的@ExceptionHandler异常处理方法放入类里
配置SimpleMappingExceptionResolver处理异常;
	  		 写一个配置类(被@Configuration注解的类),配置一个Bean(被@Bean注解的方法),该方法必须要有返回值。返回值类型必须是:SimpleMappingExceptionResolver
		    @Bean
		    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
					SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
					Properties mappings = new Properties();
					/**
					 * 参数一:异常的类型,注意必须是异常类型的全名
					 * 参数二:视图名称
					 */
					mappings.put("java.lang.ArithmeticException", "error1");
					mappings.put("java.lang.NullPointerException","error2");
					//设置异常与视图映射信息的
					resolver.setExceptionMappings(mappings);
					return resolver;
	          }
	          与上面的第三种区别,无法传递异常信息(exception对象)
自定义HandlerExceptionResolver 
           写一个配置类,实现HandlerExceptionResolver接口,重写接口方法;和上面第三种类似;

14.服务端数据校验
springboot中使用了Hibernate-validate校验框架

     校验步骤:
		在实体类属性加注解;如@NotBlank//非空;
		在controller方法参数加@Valid,同时注入BindingResult对象(封装了校验结果),如下
			@RequestMapping("/save")
			public String saveUser(@Valid Users users,BindingResult result){
				if(result.hasErrors()){
					return "add";
				}
				return "ok";
			}
		在页面中获取提示信息th:errors="${users.name}“”这里的users不是Users的对象,而是Spring给错误信息以验证对象名命名的错误信息对象;
		th:errors在页面跳转时,如果没有users对象,就会报错,需要在跳转页面也注入Users对象
	    其他校验规则
			@NotBlank: 判断字符串是否为null,或者空串(去掉首尾空格);
			@NotEmpty: 判断字符串是否为null,或者空串;
			@Length:判断字符的长度;
			@Min: 判断数值最小值;
			@Max: 判断数值最大值;
			@Email:判断邮箱是否合法;等

15.整合Junit单元测试
添加坐标

<!-- 添加junit环境的jar包 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
   		<artifactId>spring-boot-starter-test</artifactId>
</dependency>
 创建测试类添加注解@RunWith(SpringJUnit4ClassRunner.class) //启动器,让junit与spring整合;@SpringBootTest(classes={springboot应用启动类.class})

16.springboot热部署

使用SpringLoader进行项目的热部署
以Manven插件方式使用SpringLoader
<!-- springloader插件 -->
<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<dependencies>
				<dependency>
					<groupId>org.springframework</groupId>
					<artifactId>springloaded</artifactId>
					<version>1.2.5.RELEASE</version>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</build>
使用Maven命令启动:spring-boot:run
springLoader缺陷:就是Java代码作部署处理,但对页面无能为力;springloader热部署程序是系统在后台以进程形式来运行的。
使用DevTools部署
	SpringLoader与DevTools的区别:SpringLoader在部署项目时使用热部署的方式;DevTools在部署时使用的是重新部署;
	添加坐标
	<!-- DevTools的坐标 -->
    	<dependency>
    	    	<groupId>org.springframework.boot</groupId>
     	   	<artifactId>spring-boot-devtools</artifactId>
      	  	<optional>true</optional>
   	 </dependency>

17.springboot缓存技术

    springboot整合Ehcache
	添加坐标
			<!-- Spring Boot缓存支持启动器 -->
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-cache</artifactId>
			</dependency>
			<!-- Ehcache坐标 -->
			<dependency>
				<groupId>net.sf.ehcache</groupId>
				<artifactId>ehcache</artifactId>
			</dependency>	
	创建ehcache的配置文件
		文件名及位置:src/main/resources/ehcache.xml
		修改application.properties
				spring.cache.encache.config=ehcache.xml
		启动类上加注解@EnableCaching //启动缓存
		在ServiceImpl方法上添加@Cacheable //对当前查询对象做缓存处理,该缓存对象需要实现序列化接口;
		注解解释:			
				@Cacheable作用:把方法的返回值添加到Ehcache中做缓存;value属性指定Ehcache的缓存策略;key属性给存储的值起个名称,在查询时,如果有名称相同,那么则从缓存中将数据返回
				@CacheEvict作用:清除缓存;属性allEntries=true 
				

18.springboot定时任务

	整合Scheduled:Spring3.0后添加的定时器
	添加坐标
		<!-- 添加Scheduled坐标 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
	定时任务方法添加@Scheduled注解,属性cron定时任务触发的时间字符串表达式
		在启动类添加注解@EnableScheduling //开启定时
		cron表达式:
			cron 表达式是一个字符串分为6或7个域,每一个域代表一个含义
			cron 两种语法形式
				秒 分 时 日 月 周 年
				秒 分 时 日 月 周
	整合Quartz:
	添加坐标
		<!-- Quartz坐标 -->
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.2.1</version>
			<exclusions>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- 添加Scheduled坐标 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<!-- Sprng tx 坐标 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
		</dependency>
创建Quart的配置类
			/**
			 * 1.创建Job对象
			 */
			@Bean
			public JobDetailFactoryBean jobDetailFactoryBean(){
				JobDetailFactoryBean factory = new JobDetailFactoryBean();
				//关联我们自己的Job类
				factory.setJobClass(Quart的配置类.class);
				return factory;
			}
			/**
			 * 2.创建Trigger对象
			 */
			@Bean
			public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
				CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
				factory.setJobDetail(jobDetailFactoryBean.getObject());
				//设置触发时间
				factory.setCronExpression("0/2 * * * * ?");
				return factory;
			}
			
			/**
			 * 3.创建Scheduler对象
			 */
			@Bean
			public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean cronTriggerFactoryBean, MyAdaptableJobFactory myAdaptableJobFactory){
				SchedulerFactoryBean factory = new SchedulerFactoryBean();
				//关联trigger
				factory.setTriggers(cronTriggerFactoryBean.getObject());
				factory.setJobFactory(myAdaptableJobFactory);
				return factory;
			}
	自定义对象注入
		@Component("myAdaptableJobFactory")
		public class MyAdaptableJobFactory extends AdaptableJobFactory {

			//AutowireCapableBeanFactory 可以将一个对象添加到SpringIOC容器中,并且完成该对象注入
			@Autowired
			private AutowireCapableBeanFactory autowireCapableBeanFactory;
			
			/**
			 * 该方法需要将实例化的任务对象手动的添加到springIOC容器中并且完成对象的注入
			 */
			@Override
			protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
				Object obj = super.createJobInstance(bundle);
				//将obj对象添加Spring IOC容器中,并完成注入
				this.autowireCapableBeanFactory.autowireBean(obj);
				return obj;
			}

		}
	创建Job类实现Job接口,重写定时任务执行内容
	在启动类添加注解@EnableScheduling //开启定时
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值