(04) springboot 下的springMVC和jsp和mybatis
1. springboot 和springmvc下的注解完全一样(新增了一些有用的)
常用的注解如下:
@Controller
@RestController= @Controller + @ResponseBody
四大请求方法注注解
getMapping, postMapping, deleteMapping, DeleteMapping
(getMapping= RequestMapping + method=RequestMethod.GET)表示该方法支持get请求
事务注解 @Transaction
2. springboot 使用jsp
1. 在springboot使用jsp, 需要在pom文件中引入支持jsp的解析包如下:
<!--引入Spring Boot内嵌的Tomcat对JSP的解析包--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!-- servlet依赖的jar包start --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <!-- servlet依赖的jar包start --> <!-- jsp依赖jar包start --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <!-- jsp依赖jar包end --> <!--jstl标签依赖的jar包start --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!--jstl标签依赖的jar包end -->
2. 在application里面配置前后缀
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
3. 如果是idea用户, 需要在pom里面配置一下build, 防止出现404 not found
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> <resource> <directory>src/main/webapp</directory> <targetPath>META-INF/resources</targetPath> <includes> <include>**/*.*</include> </includes> </resource> </resources>
3. springboot 集成mybatis
1. 首先在pom里面添加相关依赖
<!-- 加载mybatis整合springboot --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <!-- MySQL的jdbc驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
2、在Springboot的核心配置文件 application.properties 中配置MyBatis的Mapper.xml文件所在位置:
mybatis.mapper-locations=classpath:com/bjpowernode/springboot/mapper/*.xml
3、在Springboot的核心配置文件application.properties中配置数据源:
spring.datasource.username=root spring.datasource.password=root21322 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://ip:3036/db1?useUnicode=true&characterEncoding=utf8&useSSL=false
4、在MyBatis的Mapper接口中添加@Mapper注解 或者 在运行的主类上添加 @MapperScan("com.bjpowernode.springboot.mapper") 注解包扫描
4. springboot 事务支持非常简单
1、在入口类(application类)中使用注解 @EnableTransactionManagement 开启事务支持;
2、在访问数据库的Service方法上添加注解 @Transactional 即可;