1 web开发
Spring boot web 开发非常简单,其中包括常用的 json输出、filters、property、log等
1.1 json接口开发
在以前的Spring 开发我么提供json 的做法:
- 添加jackjson 等相关jar包
- 配置Spring controller扫描
- 对接的方法添加@ResponseBody
而在Spring boot中,只需要添加 @RestController 即可。默认类中的方法都会以json格式返回
@RestController public class HelloWorldController {
@RequestMapping("/getUser")
public User getUser() {
User user=new User();
user.setUserName("小明");
user.setPassWord("xxxx");
return user;
}
}
在使用页面开发使用 @Controller 即可
1.2 自定义Filter
我们常常在项目中会使用filters用于调用日志、排除有xss威胁的字符、执行权限验证等等。Spring Boot自动添加了 OrderedCharacterEncodingFilter 和 HiddenHttpMethodFilter ,并且我们可以自定义Filter。
两个步骤:
- 实现Filter 接口,实现Filter方法;
- 添加 @Configurationz 注解,讲自定义Filter加入过滤链
@Configuration
public class WebConfiguration {
@Bean
public RemoteIpFilter remoteIpFilter() {
return new RemoteIpFilter();
}
public FilterRegistrationBean testFilterRegistrationBean() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("MyFilter");
registration.setOrder(1);
return registration;
}
public class MyFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain fc)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest)sRequest;
System.out.println("this is " + request.getRequestURI());
fc.doFilter(sRequest, sResponse);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
}
1.3 log配置
配置输出的地址和输出级别
logging.path=/user/local/log
logging.level.com.favorites=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR
1.4 数据库操作
重点讲mysql、Spring data jpa:jpa是利用Hibernate生成各种自动化的 sql,如果只是简单的增删改查,基本上不用手写,Spring 内部已经封装实现了。
- 添加相应jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 添加配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
hibernate.hbm2ddl.auto 参数的作用是:自动创建|更新|验证数据库表结构,有四个值:
- create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
- create-drop: 每次加载hibernate 时根据model 类生成表,但是sessionFactory 一关闭,表就删除。
- update:最常用的属性,第一次加载hibernate 时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时会根据model类自动更新表结构,即使表结构该表了但表中的行仍然存在不会删除以前的行。 要注意的是当第一次部署到服务器后,表结构不会立马被建立起来,要等到应用第一次运行起来后才会。
- validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但会插入新值。
dialect 主要是指定生成表名的存储引擎为InneoDB。
1.5 添加实体类和Dao
这里后续插入常用实体类的注解
dao只要继承jpaRepository 类就可以,几乎可以不用写方法
1.6 测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class UserRepositoryTests {
@Autowired
private UserRepository userRepository;
@Test
public void test() throws Exception {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
String formattedDate = dateFormat.format(date);
userRepository.save(new User("aa1", "[email protected]", "aa", "aa123456",formattedDate));
userRepository.save(new User("bb2", "[email protected]", "bb", "bb123456",formattedDate));
userRepository.save(new User("cc3", "[email protected]", "cc", "cc123456",formattedDate));
Assert.assertEquals(9, userRepository.findAll().size());
Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "[email protected]").getNickName());
userRepository.delete(userRepository.findByUserName("aa1"));
}
}
1.7 thymeleaf介绍
thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。 它使用了自然的模板技术。这意味着Thymeleaf的模板语言不会破坏文档结构,模板依旧是有效的XML文档。 在运行期替换掉静态值。
velocity,FreMaker,beetle也是模板引擎。
下面的代码示例分别使用Velocity、FreeMarker、Thymeleaf打印一条消息:
Velocity: <p>$message</p>
FreeMarker: <p>${message}</p>
Thymeleaf: <p th:text="${message}">Hello World!</p>
注意:由于Thymeleaf使用了XML DOM解析器,因此它并不适合处理大规模的XML文件。
这里是Thymeleaf使用教程:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
- 页面即原型(Thymeleaf的好处)
在传统java web开发过程中,前端工程师和后端工程师一样,需要一套完整的开发环境,然后各类java IDE中修改模板、静态资源。
但实际上前端工程师的职责更多关注页面本身而非后端。使用jsp,Velocity等传统的java模板引擎很难做到这一点,而Thymeleaf通过属性进行模板渲染不会引起新的浏览器不能识别的标签,可以直接作为HTML文件在浏览器中打开。
1.8 WebJars
WebJars是一个很神奇的东西,可以让大家以jar包的形式来使用前端的各种框架、组件。
什么是WebJars
什么是WebJars?WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。
为什么使用
我们在开发Java web项目的时候会使用像Maven,Gradle等构建工具以实现对jar包版本依赖管理,以及项目的自动化管理,但是对于JavaScript,Css等前端资源包,我们只能采用拷贝到webapp下的方式,这样做就无法对这些资源进行依赖管理。那么WebJars就提供给我们这些前端资源的jar包形势,我们就可以进行依赖管理。
如何使用
1、 WebJars主官网 查找对于的组件,比如Vuejs
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>vue</artifactId>
<version>1.0.21</version>
</dependency>
2、页面引入
<link th:href="@{/webjars/bootstrap/3.3.6/dist/css/bootstrap.css}" rel="stylesheet"></link>
这样就可以正常使用了。
1.9 Gradle 构建工具
类似maven,Spring项目建议使用Gradle进行构建项目,相比maven来讲 Gradle更简洁,而且Gradle更适合大型项目的构建。
buildscript {
repositories {
maven { url "http://repo.spring.io/libs-snapshot" }
mavenLocal()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
}
}
apply plugin: 'java' //添加 Java 插件, 表明这是一个 Java 项目
apply plugin: 'spring-boot' //添加 Spring-boot支持
apply plugin: 'war' //添加 War 插件, 可以导出 War 包
apply plugin: 'eclipse' //添加 Eclipse 插件, 添加 Eclipse IDE 支持, Intellij Idea 为 "idea"
war {
baseName = 'favorites'
version = '0.1.0'
}
sourceCompatibility = 1.7 //最低兼容版本 JDK1.7
targetCompatibility = 1.7 //目标兼容版本 JDK1.7
repositories { // Maven 仓库
mavenLocal() //使用本地仓库
mavenCentral() //使用中央仓库
maven { url "http://repo.spring.io/libs-snapshot" } //使用远程仓库
}
dependencies { // 各种 依赖的jar包
compile("org.springframework.boot:spring-boot-starter-web:1.3.6.RELEASE")
compile("org.springframework.boot:spring-boot-starter-thymeleaf:1.3.6.RELEASE")
compile("org.springframework.boot:spring-boot-starter-data-jpa:1.3.6.RELEASE")
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4'
compile("org.springframework.boot:spring-boot-devtools:1.3.6.RELEASE")
compile("org.springframework.boot:spring-boot-starter-test:1.3.6.RELEASE")
compile 'org.webjars.bower:bootstrap:3.3.6'
compile 'org.webjars.bower:jquery:2.2.4'
compile("org.webjars:vue:1.0.24")
compile 'org.webjars.bower:vue-resource:0.7.0'
}
bootRun {
addResources = true
}