1、json接口开发
在Controller接口增加注解@RestController即可自动返回json数据
2、自定义Filter
在web开发中经常会使用到filters用于日志记录、排除xss威胁、执行权限验证等,SpringBoot中自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,也可自定义Filter
1、实现Filter接口,实现Filter方法
2、添加Configuration注解,将自定义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 {
// TODO Auto-generated method stub
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 {
// TODO Auto-generated method stub
}
}
}
3、自定义property
配置在application.properties中,格式为name=value
使用配置项
@Value("${com.neo.title}")
private String title;
4、log配置
在application.properties中配置输出的地址和输出级别
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级别
5、数据库操作
使用springBoot对mysql进行增加删查改操作
1、添加相关依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2、application.properties增加数据库相关配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8011
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8
3、Controller类测试数据库连接并查询
@Autowired
private JdbcTemplate jdbcTemplate;//数据库链接
@RequestMapping("/queryAllProduct")
public List<Map<String, Object>> queryAllProduct(){
String sql="select * from product ";
List<Map<String, Object>> list=jdbcTemplate.queryForList(sql);
return list;
}
//通过查询参数查询
@RequestMapping("/queryProduct/{id}")
public Map<String,Object> queryProductByID(@PathVariable String id){
String sql="select * from product where id=?";
return jdbcTemplate.queryForMap(sql, new Object[]{id});
}