SpringBoot整合常用功能demo
前面写的东西都是用最简单的代码介绍分布式框架的几个基本功能,比如远程过程调用,服务注册与发现,负载均衡等,代码较不规范,感觉不怎么好,所以打算后面写代码都基于spring boot,今天呢,就用demo介绍一些springboot的常用功能(后续会有分布式事务方面的),一举两得
今天的内容有:Spring Boot入口、访问静态资源、自定义参数配置、全局异常、Spring Boot支持JSP、Spring Boot支持Freemarker、Spring Boot整合JdbcTemplate、Spring Boot整合jpa、Spring Boot整合Mybaits
每个都经过本人测试,请放心~
1. Spring Boot入口
添加注解 @SpringBootApplication 时的App必须放在controller的上级目录
若想放在同级的app包下,可在添加注解 @SpringBootApplication 的同时,可用注解@ComponentScan(“com.vttsor”)对@SpringBootApplication 默认扫描的目录进行覆盖
@ComponentScan("com.vttsor")
@SpringBootApplication
public class InnerApp {
public static void main(String[] args) {
SpringApplication.run(InnerApp.class,args);
}
}
在app包下,和controller包平级
application.properties:
server.port=6060 #服务端口号(默认为8080)
server.context-path=/mypath #项目根路径
2. 访问静态资源
应该将静态资源放到static目录下,这样可直接进行访问:
图片加载成功:
3. 自定义参数配置
使用注解@Value("${myBackCode}"),参数key值可以和变量名不一样,代码如下:
//@Controller和@ResponseBody组合
@RestController
public class TestController {
@Value("${myBackCode}")
private String backCode;
@RequestMapping("/testCustomParam")
public String testCustomParam(){
return backCode;
}
}
运行结果:
4. 全局异常
全局异常拦截类:
//全局异常拦截器标识
@ControllerAdvice
public class MyExceptionHandler {
//要拦截的异常类型
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Map<String, Object> exceptionBack() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("backCode", "500");
map.put("errorMsg", "服务器异常!");
return map;
}
}
Controller中加入测试方法:
@RequestMapping("/testExceptionHandler")
public String testExceptionHandler(){
int n = 1/0;
return "SUCCESS";
}
执行结果:
5. Spring Boot支持JSP
Maven依赖:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
application.properties中加入配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
Java代码:
@Controller
public class JspController {
@RequestMapping("/testJsp")
public String testJsp(Model model){
model.addAttribute("pageType","JSP");
return "jsp_test";
}
}
JSP代码:
<title>jsp page</title>
</head>
<body>
I am a ${pageType} page.
</body>
执行结果:
6. Spring Boot支持Freemarker
Freemarker maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
application.properties中加入framework配置
#freemarker文件后缀
spring.freemarker.suffix=.ftl
#freemarker文件路径
spring.freemarker.template-loader-path=classpath:/templates/
#编码
spring.freemarker.charset=UTF-8
#模板格式
spring.freemarker.content-type=text/html
#是否使用缓存
spring.freemarker.cache=true
#指定HttpServletRequest的属性是否可以覆盖controller的model的同名项
spring.freemarker.allow-request-override=false
#是否检查模板路径是否存在
spring.freemarker.check-template-location=true
Java代码:
@Controller
public class FtlController {
@RequestMapping("testFtl")
public String testFtl(Model model){
model.addAttribute("pageType","Freemarker");
model.addAttribute("gender","2");
//userlist
List<String> userList = new ArrayList<String>();
userList.add("张三");
userList.add("李四");
userList.add("王麻子");
model.addAttribute("userList",userList);
return "testFreemarker";
}
}
freemarker代码:
I am a ${pageType} page.<br>
-------------<br>
the person is
<#if gender=="1">
man
<#elseif gender=="0">
woman
<#else>
renyao
</#if><br>
-------------<br>
<#list userList as user>
${user}
</#list>
执行结果:
7. Spring Boot整合JdbcTemplate
Java代码:
controller :
@RequestMapping("testJdbcTemplate")
public String testJdbcTemplate(Model model){
model.addAttribute("userList",userService.queryAllUser());
return "testJdbcTemplate";
}
service :
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<User> queryAllUser(){
return jdbcTemplate.query("select * from user", new RowMapper<User>() {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User us = new User();
us.setUserCode(resultSet.getString("user_code"));
us.setUserPwd(resultSet.getString("user_pwd"));
us.setAge(resultSet.getInt("age"));
return us;
}
});
}
}
前台模板
<#list userList as user>
${user}
</#list>
数据库信息
执行结果:
8. Spring Boot整合jpa
Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Java后台代码
启动类:
@EnableJpaRepositories(basePackages = "com.vttsor.dao")
@EntityScan(basePackages = "com.vttsor.pojo")
@ComponentScan("com.vttsor")
@SpringBootApplication
public class InnerApp {
public static void main(String[] args) {
SpringApplication.run(InnerApp.class,args);
}
}
Pojo 代码:
@Entity(name = "user")
public class JpaUser {
@Id
private String userCode;
@Column
private String userPwd;
@Column
private int age;
...
}
Dao 代码:
import com.vttsor.pojo.JpaUser;
import org.springframework.data.jpa.repository.JpaRepository;
public interface JpaUserDao extends JpaRepository<JpaUser,String> {
}
Controller 代码:
@RequestMapping("testJdbcJpa")
public String testJdbcJpa(Model model){
userDao.findAll();
model.addAttribute("userList",userDao.findAll());
return "testJdbcJpa";
}
前台模板testJdbcJpa.ftl
<#list userList as user>
${user}
</#list>
数据库信息
执行结果:
9. Spring Boot整合Mybaits
Maven依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
Java后台代码
启动类加入注解:
@MapperScan(basePackages = "com.vttsor.mapper")
Pojo 代码:
private String userCode;
private String userPwd;
private int age;
...
mapper代码:
public interface UserMapper {
@Results(
{
@Result(property = "userCode", column = "user_code"),
@Result(property = "userPwd", column = "user_pwd")
}
)
@Select("SELECT * FROM USER WHERE user_code = #{userCode}")
User findByName(@Param("userCode") String userCode);
@Insert("INSERT INTO USER(user_code,user_pwd,age) VALUES(#{userCode},#{userPwd},#{age})")
int insert(@Param("userCode") String userCode,@Param("userPwd") String userPwd,
@Param("age") Integer age);
}
Controller 代码:
@RequestMapping("testMybatis")
public String testMybatis(Model model){
model.addAttribute("user",userMapper.findByName("vttsor"));
userMapper.insert("gebilaowang","1212",18);
return "testMybatis";
}
前台模板testMybatis.ftl
${user}
数据库信息
插入前:
插入后:
访问页面:
- 总体工程结构: