Spring Boot中web开发常用技术说明
下文笔者讲述SpringBoot中web开发中常用技术说明,如下所示
SpringBoot中web开发中常用功能
json输出 filters property log等
json 接口开发
json开发涉及思路:
1.引入jackjson相关jar包
2.配置springController注解
json涉及方法,则使用@ResponseBody注解
(如果没有使用此注解,则会出现406错误)
json实现思路:
在类上加入@RestController,则方法可采用json格式返回
@RestController
public class HelloWorldController {
@RequestMapping("/getUser")
public User getUser() {
User user=new User();
user.setUserName("java265.com");
user.setPassWord("xxxx");
return user;
}
}
自定义Filter
在日常开发的项目中
我们经常使用filters收集日志、排除有XSS威胁的字符、执行权限验证等
实现思路:
实现Filter接口,实现Filter方法
添加@Configuration注解,将自定义Filter加入过滤链
例:Springboot添加filter的示例
@Configuration
public class WebConfiguration {
@Bean
public RemoteIpFilter remoteIpFilter() {
return new RemoteIpFilter();
}
@Bean
public FilterRegistrationBean testFilterRegistration() {
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 filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) srequest;
System.out.println("this is MyFilter,url :"+request.getRequestURI());
filterChain.doFilter(srequest, sresponse);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
}
自定义Property
日常开发中, 我们需自定义配置文件例
//1.定义一个application.properties:
com.java265.title=java爱好者
com.java265.description=这是一个java爱好者的网站
//2.自定义配置类:
public class TestProperties {
@Value("${com.java265.title}")
private String title;
@Value("${com.java265.description}")
private String description;
//省略getter settet方法
}
log配置
//配置log //输出的地址 //输出级别 logging.path=/user/local/log logging.level.com.favorites=DEBUG logging.level.org.springframework.web=INFO logging.level.org.hibernate=ERROR //path:本机log地址 //logging.level 后面可以根据包路径配置不同资源的log级别
数据库操作
添加相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=123456 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。
show-sql:是否打印出自动生产的SQL,方便调试的时候查看。
添加实体类和Dao
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String userName;
@Column(nullable = false)
private String passWord;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = true, unique = true)
private String nickName;
@Column(nullable = false)
private String regTime;
//省略getter settet方法、构造方法
}
//dao只需继承JpaRepository类
//即可根据方法名来自动的生产SQL
//如:
// findByUserName:
// 会自动生产一个以 userName 为参数的查询方法
// findAlll:
// 自动会查询表里面的所有数据,如自动分页等。
Entity中不映射成列的字段得加@transient 注解,不加注解也会映射成列
public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(String userName);
User findByUserNameOrEmail(String username, String email);
数据库操作测试
@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("java265.com-1", "java265@126.com", "tt1", "9898888",formattedDate));
userRepository.save(new User("java265.com-2", "java265@126.com", "tt2", "9898888",formattedDate));
userRepository.save(new User("java265.com-3", "java265@126.com", "tt3", "9898888",formattedDate));
Assert.assertEquals(9, userRepository.findAll().size());
Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("tt2", "java265@126.com").getNickName());
userRepository.delete(userRepository.findByUserName("java265.com-1"));
}
}
thymeleaf模板
Thymeleaf介绍
Thymeleaf 是一款用于渲染XML/XHTML/HTML5内容的模板引擎 类似JSP,Velocity,FreeMaker等 它可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎 Thymeleaf最大的特点: 直接在浏览器中打开并正确显示模板页面 而无需启动整个Web应用
Thymeleaf示例
<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>
3,条件求值
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
4,for循环
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
Gradle 构建工具
spring 项目:
笔者使用Gradle进行构建项目
相比maven来说Gradle更简洁
如:Spring源码都基于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
}
WebJars
WebJars简介
WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件 对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。
WebJars使用方法
实现思路:
1.引入jar包
<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>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


