springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件
6、写了一个统一的接口层;日志门面(日志的一个抽象层);logging-abstract.jar; 给项目中导入具体的日志实现就行了;我们之前的日志框架都是实现的抽象层;
JUL、JCL、Jboss-logging、logback、log4j、log4j2、slf4j....
左边选一个门面(抽象层)、右边来选一个实现;我蒙着眼随便选两个,日志门面选: SLF4J,日志实现选:Logback(竟然和SpringBoot的设计者选的一样,英雄所见略同呀);
SpringBoot(slf4j+logback): Spring(commons-logging)、Hibernate(jboss-logging)、MyBatis、xxxx
日志输出格式:
%d表示日期时间,
%thread表示线程名,
%‐5level:级别从左显示5个字符宽度
%logger{50} 表示logger名字最长50个字符,否则按照句点分割。
%msg:日志消息,
%n是换行符
‐‐>
%d{yyyy‐MM‐dd HH:mm:ss.SSS} [%thread] %‐5level %logger{50} ‐ %msg%n
SpringBoot修改日志的默认配置
logging.level.cn.starfish=trace
#logging.path=
# 不指定路径在当前项目下生成springboot.log日志
# 可以指定完整的路径;
#logging.file=G:/springboot.log
# 在当前磁盘的根路径下创建spring文件夹和里面的log文件夹;使用 spring.log 作为默认文件
logging.path=/spring/log
# 在控制台输出的日志的格式
logging.pattern.console=%d{yyyy‐MM‐dd} [%thread] %‐5level %logger{50} ‐ %msg%n
# 指定文件中日志输出的格式
logging.pattern.file=%d{yyyy‐MM‐dd} === [%thread] === %‐5level === %logger{50} ==== %msg%n
logging.file |
logging.path |
Example |
Description |
(none) |
(none) |
|
只在控制台输出 |
指定文件名 |
(none) |
my.log |
输出日志到my.log文件 |
(none) |
指定目录 |
/var/log |
输出到指定目录的 spring.log 文件中 |
4.2、指定配置
给类路径下放上每个日志框架自己的配置文件即可;SpringBoot就不使用他默认配置的了
Logging System |
Customization |
Logback |
logback-spring.xml , logback-spring.groovy , logback.xml or logback.groovy |
Log4j2 |
log4j2-spring.xml or log4j2.xml |
JDK (Java Util Logging) |
logging.properties |
logback.xml:直接就被日志框架识别了;
logback-spring.xml:日志框架就不直接加载日志的配置项,由SpringBoot解析日志配置,可以使用SpringBoot
的高级Profile功能
可以指定某段配置只在某个环境下生效
如:
%d{yyyy‐MM‐dd HH:mm:ss.SSS} ‐‐‐‐> [%thread] ‐‐‐> %‐5level
%logger{50} ‐ %msg%n
%d{yyyy‐MM‐dd HH:mm:ss.SSS} ==== [%thread] ==== %‐5level
%logger{50} ‐ %msg%n
如果使用logback.xml作为日志配置文件,还要使用profile功能,会有以下错误
no applicable action for [springProfile]
5、切换日志框架
可以按照slf4j的日志适配图,进行相关的切换;
slf4j+log4j的方式;
org.springframework.boot
spring‐boot‐starter‐web
logback‐classic
ch.qos.logback
log4j‐over‐slf4j
org.slf4j
org.slf4j
slf4j‐log4j12
切换为log4j2
org.springframework.boot
spring‐boot‐starter‐web
spring‐boot‐starter‐logging
org.springframework.boot
org.springframework.boot
spring‐boot‐starter‐log4j2
四、Web开发
1、使用SpringBoot
1)、创建SpringBoot应用,选中我们需要的模块;
2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3)、自己编写业务代码;
2、SpringBoot对静态资源的映射规则;
一层一层的剥开SpringBoot到ResourceProperties,可以看到加载resource的路径顺序,以及属性的一些操作链(SpringBoot1.xx的版本是继承了ResourceLoaderAware,2.xx和1.xx的变化还挺大饿)。

在访问的时候只需要写webjars下面资源的名称即可
org.webjars
jquery
3.3.1
"classpath:/META‐INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" "/":当前项目的根路径
localhost:8080/abc === 去静态资源文件夹里面找abc
- 欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射;
localhost:8080/ 找index页面
- 所有的 **/favicon.ico 都是在静态资源文件下找;
## **3**、模板引擎
常见的模板引擎:JSP、Velocity、Freemarker、Thymeleaf

SpringBoot推荐的Thymeleaf; 语法更简单,功能更强大;
### 3.1、引入thymeleaf;
```xml
org.springframework.boot
spring‐boot‐starter‐thymeleaf
3.0.9.RELEASE
2.2.2
3.2、Thymeleaf使用
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF‐8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
-
导入thymeleaf的名称空间
-
使用thymeleaf语法;
Title
成功!
这是显示欢迎信息
3.3、语法规则
1)、th:text;改变当前元素里面的文本内容;
th:任意html属性;来替换原生属性的值
2)、表达式
Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.
${session.foo}
3)、内置的一些工具对象:
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the
same way as they would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a
result of an iteration).
Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
补充:配合 th:object="${session.user}:
Name: Sebastian.
Surname: Pepper.
Nationality: Saturn.
Message Expressions: #{...}:获取国际化内容
Link URL Expressions: @{...}:定义URL;
@{/order/process(execId=${execId},execType='FAST')}
Fragment Expressions: ~{...}:片段引用表达式
...
Literals(字面量)
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
Binary operators: + , ‐ , * , / , %
4、SpringMVC自动配置
4.1、Spring MVC auto-configuration
Spring Boot 自动配置好了SpringMVC
以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration)
- Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
- 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何 渲染(转发?重定向?))
- ContentNegotiatingViewResolver:组合所有的视图解析器的;
- 如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;
- Support for serving static resources, including support for WebJars (see below).静态资源文件夹路 径,webjars
- Static index.html support. 静态首页访问
- Custom Favicon support (see below). favicon.ico
- 自动注册了 of Converter , GenericConverter , Formatter beans. Converter:转换器; public String hello(User user):类型转换使用Converter Formatter 格式化器; 2017.12.17===Date;
@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date‐format")//在文件中配置日期格
式化的规则
public Formatter dateFormatter() {
return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化组件
}
自己添加的格式化器转换器,我们只需要放在容器中即可
- Support for HttpMessageConverters (see below).
- HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User---Json
- HttpMessageConverters 是从容器中确定;获取所有的HttpMessageConverter; 自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中 (@Bean,@Component)
- Automatic registration of MessageCodesResolver (see below).定义错误代码生成规则
- Automatic use of a ConfigurableWebBindingInitializer bean (see below). 我们可以配置一个ConfigurableWebBindingInitializer来替换默认的;(添加到容器)
4.2、扩展SpringMVC
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;
既保留了所有的自动配置,也能用我们扩展的配置;
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").setViewName("success");
}
}
原理:
1)、WebMvcAutoConfiguration是SpringMVC的自动配置类
2)、在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)
@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
//从容器中获取所有的WebMvcConfigurer
@Autowired(required = false)
public void setConfigurers(List configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
//一个参考实现;将所有的WebMvcConfigurer相关配置都来一起调用;
@Override
// public void addViewControllers(ViewControllerRegistry registry) {
// for (WebMvcConfigurer delegate : this.delegates) {
// delegate.addViewControllers(registry);
// }
}
}
}
3)、容器中所有的WebMvcConfigurer都会一起起作用;
4)、我们的配置类也会被调用;
效果:SpringMVC的自动配置和我们的扩展配置都会起作用;
4.3、全面接管SpringMVC;
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了 我们需要在配置类中添加@EnableWebMvc即可;
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").setViewName("success");
}
}
原理:
为什么@EnableWebMvc自动配置就失效了;
1)@EnableWebMvc的核心
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
2)、
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
3)、
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
4)、@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;
5)、导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;
5、如何修改SpringBoot的默认配置
模式:
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如 果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默 认的组合起来;
2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
6、RestfulCRUD
1)、默认访问首页
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
//@EnableWebMvc 不要接管SpringMVC
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").setViewName("success");
}
//所有的WebMvcConfigurerAdapter组件都会一起起作用
@Bean //将组件注册在容器
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
};
return adapter;
}
}
2)、国际化
- 编写国际化配置文件;
- 使用ResourceBundleMessageSource管理国际化资源文件
- 在页面使用fmt:message取出国际化内容
步骤:
a、编写国际化配置文件,抽取页面需要显示的国际化消息
b、SpringBoot自动配置好了管理国际化资源文件的组件;
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
/**
* Comma‐separated list of basenames (essentially a fully‐qualified classpath
* location), each following the ResourceBundle convention with relaxed support for
* slash based locations. If it doesn't contain a package qualifier (such as
* "org.mypackage"), it will be resolved from the classpath root.
*/
private String basename = "messages";
//我们的配置文件可以直接放在类路径下叫messages.properties;
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) {
//设置国际化资源文件的基础名(去掉语言国家代码的)
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(this.basename)));
}
if (this.encoding != null) {
messageSource.setDefaultEncoding(this.encoding.name());
}
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
messageSource.setCacheSeconds(this.cacheSeconds);
messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
return messageSource;
}
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration { 3
private String basename = "messages";
//我们的配置文件可以直接放在类路径下叫messages.properties; 12
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) {
//设置国际化资源文件的基础名(去掉语言国家代码的) messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(this.basename))); 20 }
if (this.encoding != null) {
messageSource.setDefaultEncoding(this.encoding.name()); 23 }
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
messageSource.setCacheSeconds(this.cacheSeconds);
messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
return messageSource; 28 }
c、去页面获取国际化的值;
Signin Template for Bootstrap
效果:根据浏览器语言设置的信息切换了国际化;
原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);默认的就是根据请求头带来的区域信息获取Locale进行国际化
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
if (this.mvcProperties
.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
d、点击链接切换国际化
/**
* 可以在连接上携带区域信息
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] split = l.split("_");
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale
locale) {
}
}
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
3)、登陆
开发期间模板引擎页面修改以后,要实时生效
a、禁用模板引擎的缓存
# 禁用缓存
spring.thymeleaf.cache=false
b、页面修改完成以后ctrl+f9:重新编译; 登陆错误消息的显示
4)、拦截器进行登陆检查
拦截器
/**
* 登陆检查,
*/
public class LoginHandlerInterceptor implements HandlerInterceptor {
//目标方法执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if(user == null){
//未登陆,返回登陆页面
request.setAttribute("msg","没有权限请先登陆");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
//已登陆,放行请求
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
}
注册拦截器
//所有的WebMvcConfigurerAdapter组件都会一起起作用
@Bean //将组件注册在容器
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//super.addInterceptors(registry);
//静态资源; *.css , *.js
//SpringBoot已经做好了静态资源映射
registry.addInterceptor(new
LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login");
}
};
return adapter;
}
5)、CRUD-员工列表
实验要求:
a、RestfulCRUD:CRUD满足Rest风格;
URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作
|
普通CRUD(uri来区分操作) |
RestfulCRUD |
查询 |
getEmp |
emp---GET |
添加 |
addEmp?xxx |
emp---POST |
修改 |
updateEmp?id=xxx&xxx=xx |
emp/{id}---PUT |
删除 |
deleteEmp?id=1 |
emp/{id}---DELETE |
b、实验的请求架构;
实验功能 |
请求URI |
请求方式 |
查询所有员工 |
emps |
GET |
查询某个员工(来到修改页面) |
emp/1 |
GET |
来到添加页面 |
emp |
GET |
添加员工 |
emp |
POST |
来到修改页面(查出员工进行信息回显) |
emp/1 |
GET |
修改员工 |
emp |
PUT |
删除员工 |
emp/1 |
DELETE |
c、员工列表:
thymeleaf公共页面元素抽取
1、抽取公共片段
© 2011 The Good Thymes Virtual Grocery
2、引入公共片段
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名
3、默认效果:
insert的公共片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{}:
行内写法可以加上:[[~{}]];[(~{})];
三种引入公共片段的th属性:
th:insert:将公共片段整个插入到声明引入的元素中
th:replace:将声明引入的元素替换为公共片段
th:include:将被引入的片段的内容包含进这个标签中
引入方式
引入片段的时候传入参数:
6)、CRUD-员工添加
添加页面
效果
© 2011 The Good Thymes Virtual Grocery
7、错误处理机制
1)、SpringBoot默认的错误处理机制
默认效果:
a、浏览器,返回一个默认的错误页面

b、如果是其他客户端,默认响应一个json数据
原理:
可以参照ErrorMvcAutoConfiguration;错误处理的自动配置; 给容器中添加了以下组件
- DefaultErrorAttributes:帮我们在页面共享信息;
@Override
public Map getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace) {
Map errorAttributes = new LinkedHashMap();
errorAttributes.put("timestamp", new Date());
addStatus(errorAttributes, requestAttributes);
addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
addPath(errorAttributes, requestAttributes);
return errorAttributes;
}
- BasicErrorController:处理默认/error请求
-
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
@RequestMapping(produces = "text/html")//产生html类型的数据;浏览器发送的请求来到这个方法处理
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map model = Collections.unmodifiableMap(getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
//去哪个页面作为错误页面;包含页面地址和页面内容
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
}
@RequestMapping
@ResponseBody //产生json数据,其他客户端来到这个方法处理;
public ResponseEntity
- ErrorPageCustomizer:
@Value("${error.path:/error}")
//系统出现错误以后来到error请求进行处理;(web.xml注册的错误页面规则)
private String path = "/error";
- DefaultErrorViewResolver:
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,
Map model) {
ModelAndView modelAndView = resolve(String.valueOf(status), model);
if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
}
return modelAndView;
}
private ModelAndView resolve(String viewName, Map model) {
//默认SpringBoot可以去找到一个页面? error/404
String errorViewName = "error/" + viewName;
//模板引擎可以解析这个页面地址就用模板引擎解析
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders
.getProvider(errorViewName, this.applicationContext);
if (provider != null) {
//模板引擎可用的情况下返回到errorViewName指定的视图地址
return new ModelAndView(errorViewName, model);
}
//模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
return resolveResource(errorViewName, model);
}
步骤:
一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error 请求;就会被BasicErrorController处理;
- 响应页面;去哪个页面是由DefaultErrorViewResolver解析得到的;
protected ModelAndView resolveErrorView(HttpServletRequest request,
HttpServletResponse response, HttpStatus status, Map model) {
//所有的ErrorViewResolver得到ModelAndView
for (ErrorViewResolver resolver : this.errorViewResolvers) {
ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
if (modelAndView != null) {
return modelAndView;
}
}
return null;
}
2)、如何定制错误响应:
a. 如何定制错误的页面;
有模板引擎的情况下;error/状态码; 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面error 文件夹下】,发生此状态码的错误就会来到对应的页面;
我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态 码.html);
页面能获取的信息:timestamp:
- 时间戳
- status:状态码
- error:错误提示exception:异常对象
- message:异常消息
- errors:JSR303数据校验的错误都在这里没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;
- 以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;
b. 如何定制错误的json数据;
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map handleException(Exception e){
Map map = new HashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return map;
}
}
//没有自适应效果...
@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request){
Map map = new HashMap<>();
//传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message",e.getMessage());
//转发到/error
return "forward:/error";
}
3)、将我们的定制数据携带出去;
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由
getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
- 完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
- 页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到; 容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;
自定义ErrorAttributes
//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
@Override
public Map getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace) {
Map map = super.getErrorAttributes(requestAttributes,
includeStackTrace);
map.put("company","atguigu");
return map;
}
最终的效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容,
8、配置嵌入式Servlet容器
SpringBoot默认使用Tomcat作为嵌入式的Servlet容器;
1)、如何定制和修改Servlet容器的相关配置;
- 修改和server有关的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】);
server.port=8081
server.context‐path=/crud
server.tomcat.uri‐encoding=UTF‐8
//通用的Servlet容器设置
server.xxx
//Tomcat的设置
server.tomcat.xxx
- 编写一个EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;来修改Servlet容器的配置
@Bean //一定要将这个定制器加入到容器中
public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
return new EmbeddedServletContainerCustomizer() {
//定制嵌入式的Servlet容器相关的规则
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(8083);
}
};
}
2)、注册Servlet三大组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文 件。
注册三大组件用以下方式
ServletRegistrationBean
//注册三大组件
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new
MyServlet(),"/myServlet");
return registrationBean;
}
FilterRegistrationBean
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}
ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean registrationBean = new
ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
SpringBoot帮我们自动配置SpringMVC的时候,自动的注册SpringMVC的前端控制器;DIspatcherServlet;
DispatcherServletAutoConfiguration中:
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name =
DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public ServletRegistrationBean dispatcherServletRegistration(
DispatcherServlet dispatcherServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet, this.serverProperties.getServletMapping());
//默认拦截: / 所有请求;包静态资源,但是不拦截jsp请求; /*会拦截jsp
//可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径
registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
registration.setLoadOnStartup(
this.webMvcProperties.getServlet().getLoadOnStartup());
if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig);
}
return registration;
}
3)、替换为其他嵌入式Servlet容器
默认支持:
Tomcat(默认使用)
org.springframework.boot
spring‐boot‐starter‐web
引入web模块默认就是使用嵌入式的Tomcat作为Servlet容器;
Jetty
org.springframework.boot
spring‐boot‐starter‐web
spring‐boot‐starter‐tomcat
org.springframework.boot
spring‐boot‐starter‐jetty
org.springframework.boot
Undertow
org.springframework.boot
spring‐boot‐starter‐web
spring‐boot‐starter‐tomcat
org.springframework.boot
spring‐boot‐starter‐undertow
org.springframework.boot
4)、嵌入式Servlet容器自动配置原理;
EmbeddedServletContainerAutoConfiguration:嵌入式的Servlet容器自动配置?
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@Import(BeanPostProcessorsRegistrar.class)
//导入BeanPostProcessorsRegistrar:Spring注解版;给容器中导入一些组件
//导入了EmbeddedServletContainerCustomizerBeanPostProcessor:
//后置处理器:bean初始化前后(创建完对象,还没赋值赋值)执行初始化工作
public class EmbeddedServletContainerAutoConfiguration {
@Configuration
@ConditionalOnClass({ Servlet.class, Tomcat.class })//判断当前是否引入了Tomcat依赖;
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search =
SearchStrategy.CURRENT)//判断当前容器没有用户自己定义EmbeddedServletContainerFactory:嵌入式的
Servlet容器工厂;作用:创建嵌入式的Servlet容器
public static class EmbeddedTomcat {
@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory()
{
return new TomcatEmbeddedServletContainerFactory();
}
}
/**
* Nested configuration if Jetty is being used.
*/
@Configuration
@ConditionalOnClass({ Servlet.class, Server.class, Loader.class,
WebAppContext.class })
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search =
SearchStrategy.CURRENT)
public static class EmbeddedJetty {
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
return new JettyEmbeddedServletContainerFactory();
}
}
/**
* Nested configuration if Undertow is being used.
*/
@Configuration
@ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search =
SearchStrategy.CURRENT)
public static class EmbeddedUndertow {
@Bean
public UndertowEmbeddedServletContainerFactory
undertowEmbeddedServletContainerFactory() {
return new UndertowEmbeddedServletContainerFactory();
}
}
- EmbeddedServletContainerFactory(嵌入式Servlet容器工厂)
public interface EmbeddedServletContainerFactory {
//获取嵌入式的Servlet容器
EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers);
}
- EmbeddedServletContainer:(嵌入式的Servlet容器)
- 以TomcatEmbeddedServletContainerFactory为例
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers) {
//创建一个Tomcat
Tomcat tomcat = new Tomcat();
//配置Tomcat的基本环节
File baseDir = (this.baseDirectory != null ? this.baseDirectory
: createTempDir("tomcat"));
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
//将配置好的Tomcat传入进去,返回一个EmbeddedServletContainer;并且启动Tomcat服务器
return getTomcatEmbeddedServletContainer(tomcat);
我们对嵌入式容器的配置修改是怎么生效?
ServerProperties、EmbeddedServletContainerCustomizer
EmbeddedServletContainerCustomizer:定制器帮我们修改了Servlet容器的配置? 怎么修改的原理?
容器中导入了EmbeddedServletContainerCustomizerBeanPostProcessor
//初始化之前
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
//如果当前初始化的是一个ConfigurableEmbeddedServletContainer类型的组件
if (bean instanceof ConfigurableEmbeddedServletContainer) {
//
postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer) bean);
}
return bean;
}
private void postProcessBeforeInitialization(
ConfigurableEmbeddedServletContainer bean) {
//获取所有的定制器,调用每一个定制器的customize方法来给Servlet容器进行属性赋值;
for (EmbeddedServletContainerCustomizer customizer : getCustomizers()) {
customizer.customize(bean);
}
}
private Collection getCustomizers() {
if (this.customizers == null) {
// Look up does not include the parent context
this.customizers = new ArrayList(
this.beanFactory
//从容器中获取所有这葛类型的组件:EmbeddedServletContainerCustomizer
//定制Servlet容器,给容器中可以添加一个EmbeddedServletContainerCustomizer类型的组件
.getBeansOfType(EmbeddedServletContainerCustomizer.class,
false, false)
.values());
Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE);
this.customizers = Collections.unmodifiableList(this.customizers);
}
return this.customizers;
}
ServerProperties也是定制器
步骤:
a、SpringBoot根据导入的依赖情况,给容器中添加相应的
EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】
b、容器中某个组件要创建对象就会惊动后置处理器; EmbeddedServletContainerCustomizerBeanPostProcessor;
只要是嵌入式的Servlet容器工厂,后置处理器就工作;
c、后置处理器,从容器中获取所有的EmbeddedServletContainerCustomizer,调用定制器的定制方法
5)、嵌入式Servlet容器启动原理;
什么时候创建嵌入式的Servlet容器工厂?
什么时候获取嵌入式的Servlet容器并启动Tomcat; 获取嵌入式的Servlet容器工厂:
- SpringBoot应用启动运行run方法
- refreshContext(context);SpringBoot刷新IOC容器【创建IOC容器对象,并初始化容器,创建容器中的每一个 组 件 】 ; 如 果 是 web 应 用 创 建 AnnotationConfigEmbeddedWebApplicationContext, 否 则 : AnnotationConfigApplicationContext
- refresh(context);刷新刚才创建好的ioc容器;
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post‐processing of the bean factory in context subclasses.
- onRefresh(); web的ioc容器重写了onRefresh方法
- webioc容器会创建嵌入式的Servlet容器;createEmbeddedServletContainer();
- 获取嵌入式的Servlet容器工厂:
EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
从ioc容器中获取EmbeddedServletContainerFactory 组件;TomcatEmbeddedServletContainerFactory创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制Servlet容器的相关配置;
- 使用容器工厂获取嵌入式的Servlet容器:
this.embeddedServletContainer = containerFactory
.getEmbeddedServletContainer(getSelfInitializer());
- 嵌入式的Servlet容器创建对象并启动Servlet容器;
- 先启动嵌入式的Servlet容器,再将ioc容器中剩下没有创建出的对象获取出来;
IOC容器启动创建嵌入式的Servlet容器
9、使用外置的Servlet容器
9.1. 嵌入式Servlet容器:
应用打成可执行的jar
优点:简单、便携;
缺点:默认不支持JSP、优化定制比较复杂(使用定制器【ServerProperties、自定义
EmbeddedServletContainerCustomizer】,自己编写嵌入式Servlet容器的创建工厂
【EmbeddedServletContainerFactory】);
9.2. 外置的Servlet容器
外面安装Tomcat---应用war包的方式打包;
步骤
- 必须创建一个war项目;(利用idea创建好目录结构)
- 将嵌入式的Tomcat指定为provided;
org.springframework.boot
spring‐boot‐starter‐tomcat
provided
- 必须编写一个SpringBootServletInitializer的子类,并调用configure方法
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//传入SpringBoot应用的主程序
return application.sources(SpringBoot04WebJspApplication.class);
}
}
- 启动服务器就可以使用;
9.3. 原理
- jar包:执行SpringBoot主类的main方法——>启动ioc容器——>创建嵌入式的Servlet容器;
- war包:启动服务器——>服务器启动SpringBoot应用【SpringBootServletInitializer】——>启动ioc容器;
servlet3.0(Spring注解版):
Shared libraries / runtimes pluggability: 规则:
- 服务器启动(web应用启动)会创建当前web应用里面每一个jar包里面ServletContainerInitializer实例:
- ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer的实现类的全类名
- 还可以使用@HandlesTypes,在应用启动的时候加载我们感兴趣的类;
流程:
- 启动Tomcat
- org\springframework\spring-web\4.3.14.RELEASE\spring-web-4.3.14.RELEASE.jar!\META- INF\services\javax.servlet.ServletContainerInitializer:
- Spring的web模块里面有这个文件:org.springframework.web.SpringServletContainerInitializer
- SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class)标注的所有这个类型的类都传入到onStartup方法的Set>;为这些WebApplicationInitializer类型的类创建实例;
- 每一个WebApplicationInitializer都调用自己的onStartup;
- 相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStartup方法
- SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext;创建容器
protected WebApplicationContext createRootApplicationContext(
ServletContext servletContext) {
//1、创建SpringApplicationBuilder
SpringApplicationBuilder builder = createSpringApplicationBuilder();
StandardServletEnvironment environment = new StandardServletEnvironment();
environment.initPropertySources(servletContext, null);
builder.environment(environment);
builder.main(getClass());
ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
if (parent != null) {
this.logger.info("Root context already created (using as parent).");
servletContext.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
builder.initializers(new ParentContextApplicationContextInitializer(parent));
}
builder.initializers(
new ServletContextApplicationContextInitializer(servletContext));
builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
//调用configure方法,子类重写了这个方法,将SpringBoot的主程序类传入了进来
builder = configure(builder);
//使用builder创建一个Spring应用
SpringApplication application = builder.build();
if (application.getSources().isEmpty() && AnnotationUtils
.findAnnotation(getClass(), Configuration.class) != null) {
application.getSources().add(getClass());
}
Assert.state(!application.getSources().isEmpty(),
"No SpringApplication sources have been defined. Either override the "
+ "configure method or add an @Configuration annotation");
// Ensure error pages are registered
if (this.registerErrorPageFilter) {
application.getSources().add(ErrorPageFilterConfiguration.class);
}
//启动Spring应用
return run(application);
}
- Spring的应用就启动并且创建IOC容器
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//刷新IOC容器
refreshContext(context);
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
复制代码
启动Servlet容器,再启动SpringBoot应用
五、SpringBoot与数据访问
1、JDBC
org.springframework.boot
spring‐boot‐starter‐jdbc
mysql
mysql‐connector‐java
runtime
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.15.22:3306/jdbc
driver‐class‐name: com.mysql.jdbc.Driver
默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源;
数据源的相关配置都在DataSourceProperties里面;
自动配置原理:
org.springframework.boot.autoconfigure.jdbc:
- 参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用spring.datasource.type指定自定义的数据源类型;
- SpringBoot默认可以支持;
org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource、
- 自定义数据源类型
/**
* Generic DataSource configuration.
*/
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {
@Bean
public DataSource dataSource(DataSourceProperties properties) {
//使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
return properties.initializeDataSourceBuilder().build();
}
}
- DataSourceInitializer:ApplicationListener;
作用:
- runSchemaScripts();运行建表语句;
- runDataScripts();运行插入数据的sql语句;
默认只需要将文件命名为:
schema‐*.sql、data‐*.sql
默认规则:schema.sql,schema‐all.sql;
可以使用
schema:
‐ classpath:department.sql
指定位置
- 操作数据库:自动配置了JdbcTemplate操作数据库
2、整合Druid数据源
com.alibaba
druid-spring-boot-starter
1.1.10
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),
"/druid/*");
Map initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
3、整合MyBatis
org.mybatis.spring.boot
mybatis‐spring‐boot‐starter
1.3.1
步骤:
- 配置数据源相关属性
- 给数据库建表
- 创建JavaBean
- 注解版
//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set departmentName=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
问题:
自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}
- 配置文件版
mybatis:
config‐location: classpath:mybatis/mybatis‐config.xml 指定全局配置文件的位置
mapper‐locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置
4、整合SpringData JPA
- 编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;
public class User {
@Id //这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
private Integer id;
@Column(name = "last_name",length = 50) //这是和数据表对应的一个列
private String lastName;
@Column //省略默认列名就是属性名
private String email;
- 编写一个Dao接口来操作实体类对应的数据表(Repository)
//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository {
}
- 基本的配置JpaProperties
spring:
jpa:
hibernate:
# 更新或者创建数据表结构
ddl‐auto: update
# 控制台显示SQL
show‐sql: true
六、启动配置原理
几个重要的事件回调机制
配置在META-INF/spring.factories
ApplicationContextInitializer
SpringApplicationRunListener
只需要放在ioc容器中ApplicationRunner CommandLineRunner
启动流程:
1、创建SpringApplication对象
initialize(sources);
private void initialize(Object[] sources) {
//保存主配置类
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
//判断当前是否一个web应用
this.webEnvironment = deduceWebEnvironment();
//从类路径下找到META‐INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起
来
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
//从类路径下找到ETA‐INF/spring.factories配置的所有ApplicationListener
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//从多个配置类中找到有main方法的主配置类
this.mainApplicationClass = deduceMainApplicationClass();
}
2、运行run方法
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
//获取SpringApplicationRunListeners;从类路径下META‐INF/spring.factories
SpringApplicationRunListeners listeners = getRunListeners(args);
//回调所有的获取SpringApplicationRunListener.starting()方法
listeners.starting();
try {
//封装命令行参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//准备环境
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
//创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准
备完成
Banner printedBanner = printBanner(environment);
//创建ApplicationContext;决定创建web的ioc还是普通的ioc
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
//准备上下文环境;将environment保存到ioc中;而且applyInitializers();
//applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法
//回调所有的SpringApplicationRunListener的contextPrepared();
//
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded();
//s刷新容器;ioc容器初始化(如果是web应用还会创建嵌入式的Tomcat);Spring注解版
//扫描,创建,加载所有组件的地方;(配置类,组件,自动配置)
refreshContext(context);
//从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调
//ApplicationRunner先回调,CommandLineRunner再回调
afterRefresh(context, applicationArguments);
//所有的SpringApplicationRunListener回调finished方法
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
//整个SpringBoot应用启动完成以后返回启动的ioc容器;
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
3、事件监听机制
配置在META-INF/spring.factories ApplicationContextInitializer
public class HelloApplicationContextInitializer implements
ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("ApplicationContextInitializer...initialize..."+applicationContext);
}
}
SpringApplicationRunListener
配置(META-INF/spring.factories)
org.springframework.context.ApplicationContextInitializer=\
com.atguigu.springboot.listener.HelloApplicationContextInitializer
org.springframework.boot.SpringApplicationRunListener=\
com.atguigu.springboot.listener.HelloSpringApplicationRunListener
只需要放在ioc容器中
ApplicationRunner
@Component
public class HelloApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner...run....");
}
}
CommandLineRunner
@Component
public class HelloCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner...run..."+ Arrays.asList(args));
}
}
你可能感兴趣的:(SpringBoot,SpringBoot)
- 当进行npm install指令,安装依赖的情况下,存在如下报错
舒克日记
javanpm前端node.js
当进行npminstall指令,安装依赖的情况下,存在如下报错D:\ssmprogramcode\springboot8i5qd7np\src\main\resources\front\front>npminstallnpmERR!codeENOTFOUNDnpmERR!errnoENOTFOUNDnpmERR!networkrequesttohttps://registry.nlark.com/
- Spring Cloud Alibaba与Spring Boot、Spring Cloud版本对应关系
web13093320398
面试学习路线阿里巴巴springbootspringcloudjava
一、前言在搭建SpringCloud项目环境架构的时候,需要选择SpringBoot和SpringCloud进行兼容的版本号,因此对于选择SpringBoot版本与SpringCloud版本的对应关系很重要,如果版本关系不对应,常见的会遇见项目启动不起来,怪异的则会是你的项目出现一些诡异的问题,查资料也不好查。下面就收集一下SpringBoot与SpringCloud版本之间的对应关系,在搭建项目
- Spring Boot项目@Cacheable注解的使用
m0_54851477
面试学习路线阿里巴巴springbootspringjava
@Cacheable是Spring框架中用于缓存的注解之一,它可以帮助你轻松地将方法的结果缓存起来,从而提高应用的性能。下面详细介绍如何使用@Cacheable注解以及相关的配置和注意事项。1.基本用法1.1添加依赖首先,确保你的项目中包含了SpringCache的依赖。如果你使用的是SpringBoot,可以在pom.xml或build.gradle中添加以下依赖:Maven:org.sprin
- Spring Boot 整合 RabbitMQ 详解
码农爱java
【RabbitMQ】java-rabbitmqspringbootrabbitmq消息中间件MQ实战
前言:在消息中间件领域中RabbitMQ也是一种非常常见的消息中间件了,本篇简单分享一下SpringBoot项目集成RabbitMQ的过程。RabbitMQ系列文章传送门RabbitMQ的介绍及核心概念讲解@RabbitListener注解详解SpringBoot集成RabbitMQ可以分为三大步,如下:在proerties或者yml文件中添加RabbitMQ配置。项目pom.xml文件中引入sp
- SpringBoot 整合mongoDB并自定义连接池
飘零未归人
javamongodbmongodb数据库java
整合mongoDB的目的就是想用它给我们提供的mongoTemplate,它可以很容易的操作mongoDB数整合mongoDB的目的就是想用它给我们提供的mongoTemplate,它可以很容易的操作mongoDB数据库。通过我们自定义的连接池和mongoTemplate,我们可以轻松的配置多个数据源,并在多个数据源之间切换为了自定义连接池,我们在配置类中主要与MongoClientOptions
- SpringBoot 整合mongoDB并自定义连接池,实现多数据源配置
飘零未归人
#javadatabasejavaspringbootmongodb后端
要想在同一个springboot项目中使用多个数据源,最主要是每个数据源都有自己的mongoTemplate和MongoDbFactory。mongoTemplate和MongoDbFactory是负责对数据源进行交互的并管理链接的。spring提供了一个注解@EnableMongoRepositories用来注释在某些路径下的MongoRepositor实现类使用哪个MongoTemplate实
- Maven+SSM+SpringBoot+Mybatis-Plus
五月茶
mavenspringbootmybatis
SSM技术栈:spring6、springmvc、mybatis、springboot3、mybatis-plus、druid;前端:node、npm、vue快速掌握:全新SSM+SpringBoot+MyBatis-Plus实战精讲
- SpringBoot-引入jackson-dataformat-xml之后,本返回json的接口返回xml
LIUYEYEA
xmljavajavaxmljson
一、问题当我们项目中需要引入"jackson-dataformat-xml"后,我们会发现我们原本返回json数据的接口也开始返回xml数据格式了二、原因publicabstractclassAbstractMessageConverterMethodProcessorextendsAbstractMessageConverterMethodArgumentResolverimplementsHa
- Springboot 自动化装配的原理
Code额
SpringBootspringbootjava
Springboot自动化装配的原理SpringBoot主要作用为:起步依赖、自动装配。而为了实现这种功能,SpringBoot底层主要使用了@SpringBootApplication注解。首先,@SpringBootApplication是一个复合注解,它结合了@Configuration、@EnableAutoConfiguration和@ComponentScan三个注解的功能。这个注解通
- springboot-利用反射调用service层方法从Excel读取数据写入数据库报错:java.lang.NullPointerException,小坑一个
正在努力中。。。
springbootjava数据库springboot
最近在做一个小项目,需要从读取Excel数据写入到数据库。利用的是easyExcel的read方法,通过实现了ReadListener接口的监听器去调用service层方法实现数据持久化操作。但业务表那么多,本身在读取过程中不需要做任何操作,只要数据从Excel读出来直接写到mysql就可以,因此不想给每个表都写一个监听器,通过泛型加反射的方式实现类的匹配和方法调用。我的方案是:1.前台选择Exc
- java接口返回值实现数据脱敏
不平衡的叉叉树
javajava开发语言
基于jackson,通过自定义注解的方式实现数据脱敏,在需要脱敏的字段上使用该注解即可。由于项目是springboot服务,而jackson相关依赖包已由spring-web、spring-boot-starter-web集成,所以无需单独添加jackson相关依赖包。自定义脱敏注解@Retention(RetentionPolicy.RUNTIME)@JacksonAnnotationsInsi
- Spring Boot 整合WebSocket
weixin_44021967
javawebsocket
文章目录1.WebSocket介绍2.SpringBoot结合WebSocket11-03在线私聊1.WebSocket介绍SpringBoot结合WebSocket实现在线聊天:https://mp.weixin.qq.com/s/Rrj7oco3K8kJBsTxEEdz9gWebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服
- Spring Boot整合WebSocket实现实时通信
Mac-AcAclA
springbootwebsocket后端
SpringBoot整合WebSocket实现实时通信引言在现代Web应用中,实时通信功能变得越来越重要。WebSocket提供了一种在客户端和服务器之间进行全双工通信的方式,使得服务器能够主动向客户端推送消息。SpringBoot作为一个轻量级的Java应用框架,提供了对WebSocket的原生支持,使得开发者可以轻松地在SpringBoot应用中集成WebSocket。本文将详细介绍如何在Sp
- 微服务实战:Spring Boot与Spring Cloud指南
萧书泓
微服务实战:SpringBoot与SpringCloud指南Microservices-with-Spring-Boot-and-Spring-Cloud-Third-EditionMicroserviceswithSpringBootandSpringCloud,ThirdEdition项目地址:https://gitcode.com/gh_mirrors/mi/Microservices-wi
- 保姆级!springboot访问Ollama API并调用DeepSeek模型 Api
不会吉他的肌肉男不是好的挨踢男
springbootDeepSeekOllamaai大模型
要在springboot中访问OllamaAPI并调用DeepSeek模型,你需要遵循以下步骤。首先,确保你有一个有效的Ollama服务器实例运行中,并且DeepSeek模型已经被加载。可以参考我的这篇博客保姆级!使用Ollama本地部署DeepSeek-R1大模型并java通过api调用使用SpringBoot+SpringAI在使用Ollama把deepseek-r1跑起来之后,我们就可以开始
- Spring Boot 排除自动配置
m0_74824954
面试学习路线阿里巴巴springbootjavamybatis
SpringBoot排除自动配置SpringBoot自动配置非常强大,有时需要排除/禁用SpringBoot某些类的自动化配置。***************************APPLICATIONFAILEDTOSTART***************************Description:FailedtoconfigureaDataSource:'url'attributeisn
- SpringBoot 与 Maven 快速上手指南
蓝天资源分享
springbootmaven后端
SpringBoot与Maven快速上手指南在Java开发领域,SpringBoot和Maven是两个极其重要的工具,它们极大地简化了企业级应用的开发和构建过程。SpringBoot通过自动配置和起步依赖等特性,让开发者能够快速搭建起一个Spring应用;而Maven则是一个强大的项目管理和构建工具,能够帮助我们管理项目的依赖、构建生命周期以及自动化测试等。本文将详细介绍如何快速上手SpringB
- Spring Boot与MyBatis
geinvse_seg
面试学习路线阿里巴巴springbootmybatis后端
SpringBoot与MyBatis的配置一、简介SpringBoot是一个用于创建独立的、基于Spring的生产级应用程序的框架,它简化了Spring应用的初始搭建以及开发过程。MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。将SpringBoot和MyBatis结合使用,可以高效地开发数据驱动的应用程序。二、环境准备(一)创建SpringBoot项目可以使用Sp
- SpringBoot备份神通数据库
松岛的枫叶
springboot数据库后端
SpringBoot备份神通数据库····直接上代码···publicStringbackupOsrdb(){//构建命令Listcommand=newArrayList<>();command.add("osrexp");command.add("-u");command.add("SYSDBA"+"/"+"szoscar55");//用户名/密码command.add("-d");comman
- 【面试实战】Spring基础、IoC、AOP、MVC、Mybatis、Spring Boot
Sivan_Xin
技术实战专栏(已上云)面试mvcspring
version:1.0文章目录SpringSpring基础/IoC♂️面试官:举例Spring的模块?♂️面试官:Spring、SpringMVC、SpringBoot关系?♂️面试官:说说对SpringIoC的了解?♂️面试官:什么是SpringBean?♂️面试官:Bean的作用域?♂️面试官:Bean的生命周期?♂️面试官:单例Bean的线程安全问题了解吗?♂️面试官:@Co
- spring boot、spring cloud、spring cloud alibaba 之间的版本对应关系
薄荷街的兔比先生
springbootspringcloudjava
大家在引用pom的时候还是要以官方推荐版本为主,不然容易出现未知的问题。1.springboot和springcloud的版本关系官方提供的版本对照表https://start.spring.io/actuator/info{"git":{"branch":"93e528fc7e79e41a513e493d057499401a15eb67","commit":{"id":"93e528f","ti
- SpringBoot + vue 管理系统
m0_74825565
面试学习路线阿里巴巴springbootvue.js后端
SpringBoot+vue管理系统文章目录SpringBoot+vue管理系统1、成品效果展示2、项目准备3、项目开发3.1、部门管理3.1.1、前端核心代码3.1.2、后端代码实现3.2、员工管理3.2.1、前端核心代码3.2.2、后端代码实现3.3、班级管理3.3.1、前端核心代码3.3.2、后端代码实现3.4、学生管理3.4.1、前端核心代码3.4.2、后端代码实现3.5、数据统计3.5.
- Spring Boot的项目结构
m0_74823983
面试学习路线阿里巴巴springboot后端java
SpringBoot的项目结构技术背景SpringBoot项目结构遵循Maven或Gradle的标准目录结构,同时融入了SpringBoot的特定约定。良好的项目结构不仅有助于代码组织,还能提高开发效率和项目可维护性。了解SpringBoot的项目结构对于开发高质量的应用至关重要。1.基础项目结构1.1标准目录结构基本的SpringBoot项目结构如下:myproject/├──src/│├──m
- Spring Boot@Component注解下的类无法@Autowired的问题
Micrle_007
springbootSpring
这个问题心累(确实)在把我的一个非Web程序迁移从Spring迁移到SpringBoot时,出现了在@Component注解下@Autowired的类为null的情况,也就是没注入成功,或者说是此类在bean加载之前就被调用了。试了各种办法,修改扫描包,修改@Component注解等等,皆未成功,后来看到了一个方法,探究了一下。@ComponentpublicclassComponentClass
- spring cloud alibaba版本对应表(2024/6/26)
翻身仗
springcloudspringboot中间件
毕业版本依赖关系(推荐使用)由于SpringBoot3.0,SpringBoot2.7~2.4和2.4以下版本之间变化较大,目前企业级客户老项目相关SpringBoot版本仍停留在SpringBoot2.4以下,为了同时满足存量用户和新用户不同需求,社区以SpringBoot3.0和2.4分别为分界线,同时维护2022.x、2021.x、2.2.x三个分支迭代。如果不想跨分支升级,如需使用新特性,
- 一个基于 React + SpringBoot 的在线多功能问卷系统(附源码)
程序员-李旭亮
Java项目源码react.jsspringboot前端
简介:一个基于React+SpringBoot的在线多功能问卷系统前端技术栈:React、React-Router、Webpack、Antd、Zustand、Echarts、DnDKit后端技术栈:SpringBoot、MySQL、MyBatisPlus、Redis项目源码下载链接:https://pan.quark.cn/s/2e32786e0c61部分页面静态预览:主要前端业务需求与技术突破:
- Spring Boot 集成 Kafka
m0_74823471
面试学习路线阿里巴巴springbootkafkalinq
在现代软件开发中,分布式系统和微服务架构越来越受到关注。为了实现系统之间的异步通信和解耦,消息队列成为了一种重要的技术手段。Kafka作为一种高性能、分布式的消息队列系统,被广泛应用于各种场景。而SpringBoot作为一种流行的Java开发框架,提供了便捷的方式来构建应用程序。本文将介绍如何在SpringBoot项目中集成Kafka,包括Kafka的基本概念、SpringBoot集成Kafka的
- server.servlet.session.timeout: 12h(HTTP 会话的超时时间为 12 小时)
小丁学Java
产品资质管理系统servlethttpfirefox
从你提供的配置文件(应该是SpringBoot的application.yml或application.properties文件)来看,以下部分与会话超时时间相关:server:servlet:session:timeout:12h#timeout:30cookie:name:VENDER_SID会话超时时间的设置server.servlet.session.timeout:12h:这行配置明确指
- 《Spring Boot + MySQL高性能应用实战:性能优化技巧与最佳实践》
扣丁梦想家
Springspringbootmysql后端
目录应用性能优化概述环境搭建与技术栈选择数据库设计优化SpringBoot与MySQL集成优化4.1使用JPA/Hibernate的性能优化4.2连接池的配置与优化4.3分页与查询优化MySQL性能优化5.1索引优化5.2查询缓存与慢查询分析应用性能监控与日志总结与最佳实践应用性能优化概述在高性能应用的构建过程中,我们不仅需要关注数据库性能,还要从以下几个方面进行优化:数据库设计优化:合理设计表结
- 告诉你如何用springboot调用python脚本
luckilyil
项目springbootpython后端
目录springboot调用python脚本准备工作方法一:使用ProcessBuilder1.编写测试方法2.解释代码方法二:使用ApacheCommonsExec1.编写测试方法2.解释代码Python脚本的数据通过接口让SpringBoot接收。Python脚本作为服务1.使用Flask创建PythonHTTP服务2.在SpringBoot中调用PythonHTTP服务使用RestTempl
- Java实现的基于模板的网页结构化信息精准抽取组件:HtmlExtractor
yangshangchuan
信息抽取HtmlExtractor精准抽取信息采集
HtmlExtractor是一个Java实现的基于模板的网页结构化信息精准抽取组件,本身并不包含爬虫功能,但可被爬虫或其他程序调用以便更精准地对网页结构化信息进行抽取。
HtmlExtractor是为大规模分布式环境设计的,采用主从架构,主节点负责维护抽取规则,从节点向主节点请求抽取规则,当抽取规则发生变化,主节点主动通知从节点,从而能实现抽取规则变化之后的实时动态生效。
如
- java编程思想 -- 多态
百合不是茶
java多态详解
一: 向上转型和向下转型
面向对象中的转型只会发生在有继承关系的子类和父类中(接口的实现也包括在这里)。父类:人 子类:男人向上转型: Person p = new Man() ; //向上转型不需要强制类型转化向下转型: Man man =
- [自动数据处理]稳扎稳打,逐步形成自有ADP系统体系
comsci
dp
对于国内的IT行业来讲,虽然我们已经有了"两弹一星",在局部领域形成了自己独有的技术特征,并初步摆脱了国外的控制...但是前面的路还很长....
首先是我们的自动数据处理系统还无法处理很多高级工程...中等规模的拓扑分析系统也没有完成,更加复杂的
- storm 自定义 日志文件
商人shang
stormclusterlogback
Storm中的日志级级别默认为INFO,并且,日志文件是根据worker号来进行区分的,这样,同一个log文件中的信息不一定是一个业务的,这样就会有以下两个需求出现:
1. 想要进行一些调试信息的输出
2. 调试信息或者业务日志信息想要输出到一些固定的文件中
不要怕,不要烦恼,其实Storm已经提供了这样的支持,可以通过自定义logback 下的 cluster.xml 来输
- Extjs3 SpringMVC使用 @RequestBody 标签问题记录
21jhf
springMVC使用 @RequestBody(required = false) UserVO userInfo
传递json对象数据,往往会出现http 415,400,500等错误,总结一下需要使用ajax提交json数据才行,ajax提交使用proxy,参数为jsonData,不能为params;另外,需要设置Content-type属性为json,代码如下:
(由于使用了父类aaa
- 一些排错方法
文强chu
方法
1、java.lang.IllegalStateException: Class invariant violation
at org.apache.log4j.LogManager.getLoggerRepository(LogManager.java:199)at org.apache.log4j.LogManager.getLogger(LogManager.java:228)
at o
- Swing中文件恢复我觉得很难
小桔子
swing
我那个草了!老大怎么回事,怎么做项目评估的?只会说相信你可以做的,试一下,有的是时间!
用java开发一个图文处理工具,类似word,任意位置插入、拖动、删除图片以及文本等。文本框、流程图等,数据保存数据库,其余可保存pdf格式。ok,姐姐千辛万苦,
- php 文件操作
aichenglong
PHP读取文件写入文件
1 写入文件
@$fp=fopen("$DOCUMENT_ROOT/order.txt", "ab");
if(!$fp){
echo "open file error" ;
exit;
}
$outputstring="date:"." \t tire:".$tire."
- MySQL的btree索引和hash索引的区别
AILIKES
数据结构mysql算法
Hash 索引结构的特殊性,其 检索效率非常高,索引的检索可以一次定位,不像B-Tree 索引需要从根节点到枝节点,最后才能访问到页节点这样多次的IO访问,所以 Hash 索引的查询效率要远高于 B-Tree 索引。
可能很多人又有疑问了,既然 Hash 索引的效率要比 B-Tree 高很多,为什么大家不都用 Hash 索引而还要使用 B-Tree 索引呢
- JAVA的抽象--- 接口 --实现
百合不是茶
抽象 接口 实现接口
//抽象 类 ,方法
//定义一个公共抽象的类 ,并在类中定义一个抽象的方法体
抽象的定义使用abstract
abstract class A 定义一个抽象类 例如:
//定义一个基类
public abstract class A{
//抽象类不能用来实例化,只能用来继承
//
- JS变量作用域实例
bijian1013
作用域
<script>
var scope='hello';
function a(){
console.log(scope); //undefined
var scope='world';
console.log(scope); //world
console.log(b);
- TDD实践(二)
bijian1013
javaTDD
实践题目:分解质因数
Step1:
单元测试:
package com.bijian.study.factor.test;
import java.util.Arrays;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import com.bijian.
- [MongoDB学习笔记一]MongoDB主从复制
bit1129
mongodb
MongoDB称为分布式数据库,主要原因是1.基于副本集的数据备份, 2.基于切片的数据扩容。副本集解决数据的读写性能问题,切片解决了MongoDB的数据扩容问题。
事实上,MongoDB提供了主从复制和副本复制两种备份方式,在MongoDB的主从复制和副本复制集群环境中,只有一台作为主服务器,另外一台或者多台服务器作为从服务器。 本文介绍MongoDB的主从复制模式,需要指明
- 【HBase五】Java API操作HBase
bit1129
hbase
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.ha
- python调用zabbix api接口实时展示数据
ronin47
zabbix api接口来进行展示。经过思考之后,计划获取如下内容: 1、 获得认证密钥 2、 获取zabbix所有的主机组 3、 获取单个组下的所有主机 4、 获取某个主机下的所有监控项
- jsp取得绝对路径
byalias
绝对路径
在JavaWeb开发中,常使用绝对路径的方式来引入JavaScript和CSS文件,这样可以避免因为目录变动导致引入文件找不到的情况,常用的做法如下:
一、使用${pageContext.request.contextPath}
代码” ${pageContext.request.contextPath}”的作用是取出部署的应用程序名,这样不管如何部署,所用路径都是正确的。
- Java定时任务调度:用ExecutorService取代Timer
bylijinnan
java
《Java并发编程实战》一书提到的用ExecutorService取代Java Timer有几个理由,我认为其中最重要的理由是:
如果TimerTask抛出未检查的异常,Timer将会产生无法预料的行为。Timer线程并不捕获异常,所以 TimerTask抛出的未检查的异常会终止timer线程。这种情况下,Timer也不会再重新恢复线程的执行了;它错误的认为整个Timer都被取消了。此时,已经被
- SQL 优化原则
chicony
sql
一、问题的提出
在应用系统开发初期,由于开发数据库数据比较少,对于查询SQL语句,复杂视图的的编写等体会不出SQL语句各种写法的性能优劣,但是如果将应用系统提交实际应用后,随着数据库中数据的增加,系统的响应速度就成为目前系统需要解决的最主要的问题之一。系统优化中一个很重要的方面就是SQL语句的优化。对于海量数据,劣质SQL语句和优质SQL语句之间的速度差别可以达到上百倍,可见对于一个系统
- java 线程弹球小游戏
CrazyMizzz
java游戏
最近java学到线程,于是做了一个线程弹球的小游戏,不过还没完善
这里是提纲
1.线程弹球游戏实现
1.实现界面需要使用哪些API类
JFrame
JPanel
JButton
FlowLayout
Graphics2D
Thread
Color
ActionListener
ActionEvent
MouseListener
Mouse
- hadoop jps出现process information unavailable提示解决办法
daizj
hadoopjps
hadoop jps出现process information unavailable提示解决办法
jps时出现如下信息:
3019 -- process information unavailable3053 -- process information unavailable2985 -- process information unavailable2917 --
- PHP图片水印缩放类实现
dcj3sjt126com
PHP
<?php
class Image{
private $path;
function __construct($path='./'){
$this->path=rtrim($path,'/').'/';
}
//水印函数,参数:背景图,水印图,位置,前缀,TMD透明度
public function water($b,$l,$pos
- IOS控件学习:UILabel常用属性与用法
dcj3sjt126com
iosUILabel
参考网站:
http://shijue.me/show_text/521c396a8ddf876566000007
http://www.tuicool.com/articles/zquENb
http://blog.csdn.net/a451493485/article/details/9454695
http://wiki.eoe.cn/page/iOS_pptl_artile_281
- 完全手动建立maven骨架
eksliang
javaeclipseWeb
建一个 JAVA 项目 :
mvn archetype:create
-DgroupId=com.demo
-DartifactId=App
[-Dversion=0.0.1-SNAPSHOT]
[-Dpackaging=jar]
建一个 web 项目 :
mvn archetype:create
-DgroupId=com.demo
-DartifactId=web-a
- 配置清单
gengzg
配置
1、修改grub启动的内核版本
vi /boot/grub/grub.conf
将default 0改为1
拷贝mt7601Usta.ko到/lib文件夹
拷贝RT2870STA.dat到 /etc/Wireless/RT2870STA/文件夹
拷贝wifiscan到bin文件夹,chmod 775 /bin/wifiscan
拷贝wifiget.sh到bin文件夹,chm
- Windows端口被占用处理方法
huqiji
windows
以下文章主要以80端口号为例,如果想知道其他的端口号也可以使用该方法..........................1、在windows下如何查看80端口占用情况?是被哪个进程占用?如何终止等. 这里主要是用到windows下的DOS工具,点击"开始"--"运行",输入&
- 开源ckplayer 网页播放器, 跨平台(html5, mobile),flv, f4v, mp4, rtmp协议. webm, ogg, m3u8 !
天梯梦
mobile
CKplayer,其全称为超酷flv播放器,它是一款用于网页上播放视频的软件,支持的格式有:http协议上的flv,f4v,mp4格式,同时支持rtmp视频流格 式播放,此播放器的特点在于用户可以自己定义播放器的风格,诸如播放/暂停按钮,静音按钮,全屏按钮都是以外部图片接口形式调用,用户根据自己的需要制作 出播放器风格所需要使用的各个按钮图片然后替换掉原始风格里相应的图片就可以制作出自己的风格了,
- 简单工厂设计模式
hm4123660
java工厂设计模式简单工厂模式
简单工厂模式(Simple Factory Pattern)属于类的创新型模式,又叫静态工厂方法模式。是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。
- maven笔记
zhb8015
maven
跳过测试阶段:
mvn package -DskipTests
临时性跳过测试代码的编译:
mvn package -Dmaven.test.skip=true
maven.test.skip同时控制maven-compiler-plugin和maven-surefire-plugin两个插件的行为,即跳过编译,又跳过测试。
指定测试类
mvn test
- 非mapreduce生成Hfile,然后导入hbase当中
Stark_Summer
maphbasereduceHfilepath实例
最近一个群友的boss让研究hbase,让hbase的入库速度达到5w+/s,这可愁死了,4台个人电脑组成的集群,多线程入库调了好久,速度也才1w左右,都没有达到理想的那种速度,然后就想到了这种方式,但是网上多是用mapreduce来实现入库,而现在的需求是实时入库,不生成文件了,所以就只能自己用代码实现了,但是网上查了很多资料都没有查到,最后在一个网友的指引下,看了源码,最后找到了生成Hfile
- jsp web tomcat 编码问题
王新春
tomcatjsppageEncode
今天配置jsp项目在tomcat上,windows上正常,而linux上显示乱码,最后定位原因为tomcat 的server.xml 文件的配置,添加 URIEncoding 属性:
<Connector port="8080" protocol="HTTP/1.1"
connectionTi