Spring boot和Mybatis整合+Mysql+jsp页面跳转问题(借助FreeMarker)

来源:互联网 发布:淘宝怎么注册天猫 编辑:程序博客网 时间:2024/06/06 08:47

本篇文章,介绍springboot+mybatis+mysql+freemarker+jsp应用的一个小demo,主要是整合mybatis部分。

笔者刚研究springboot,刚刚跑通的例子,出来分享一下,直接上代码:

第一,建一个Maven项目。(不会Maven的自学)

结构图如下:


下面看pom.xml配置:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.zhang.demo</groupId>  <artifactId>springbootSample</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.2.3.RELEASE</version>  </parent>    <dependencies>     <!-- freemarker jar包导入 -->     <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-freemarker</artifactId>    </dependency>     <!-- 我这里用到gson,也可用jakson 等json转换工具jar-->    <dependency>        <groupId>com.google.code.gson</groupId>        <artifactId>gson</artifactId>        <version>2.8.0</version>    </dependency>    <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-web</artifactId>      </dependency>        <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.21</version>     </dependency>     <dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency>     <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter</artifactId></dependency>     </dependencies>    <!-- Package as an executable JAR -->  <build>      <plugins>          <plugin>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-maven-plugin</artifactId>          </plugin>         <plugin>     <groupId>org.apache.maven.plugins</groupId>    <artifactId>maven-surefire-plugin</artifactId> <configuration>    <skip>true</skip> </configuration></plugin>            </plugins>  </build>   <!-- Allow access to Spring milestones and snapshots -->  <!-- (you don't need this if you are using anything after 0.5.0.RELEASE) -->  <repositories>      <repository>          <id>spring-snapshots</id>          <url>http://repo.spring.io/snapshot</url>          <snapshots><enabled>true</enabled></snapshots>      </repository>      <repository>          <id>spring-milestones</id>          <url>http://repo.spring.io/milestone</url>          <snapshots><enabled>true</enabled></snapshots>      </repository>  </repositories>  <pluginRepositories>      <pluginRepository>          <id>spring-snapshots</id>          <url>http://repo.spring.io/snapshot</url>      </pluginRepository>      <pluginRepository>          <id>spring-milestones</id>          <url>http://repo.spring.io/milestone</url>      </pluginRepository>  </pluginRepositories></project>

第二、我们以City表为例,做一个查询操作。

1、下面是City实体类部分代码,对应数据库中的表自己创建。

/** * @author zcloudfly(qq:920869693) */public class City implements Serializable {private Long id;private String name;private String state;private String country;//下面get/set/tostring方法自己实现}

2、下面是Dao层接口CityMapper的书写,注意:CityMapper和CityMapper.xml名字要一致,springboot会自动识别。

package sample.mybatis.mapper;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;import sample.mybatis.domain.City;@Mapperpublic interface CityMapper {City findByState(@Param("state") String state);//根据state字段查询City}
CityMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="sample.mybatis.mapper.CityMapper">    <select id="findByState" resultType="City">        select * from city where state = #{state}    </select></mapper>
mybatis-config.xml:为domain包下的实体类起别名,之后注册mapper

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <typeAliases>        <package name="sample.mybatis.domain"/>    </typeAliases>   <mappers>        <mapper resource="sample/mybatis/mapper/CityMapper.xml"/>        <mapper resource="sample/mybatis/mapper/UserMapper.xml"/>    </mappers>      </configuration>
3、下面进行application.properties文件配置,里面会把数据源和mybatis-config.xml配置好:

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=spring.datasource.driver-class-name=com.mysql.jdbc.Drivermybatis.config-location=classpath:mybatis-config.xml
4、CityController类编写:

package sample.mybatis.controller;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpSession;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.ModelAndView;import sample.mybatis.domain.City;import sample.mybatis.mapper.CityMapper;import com.google.gson.Gson;@RestController  //相当于Responsebody和Controller@RequestMapping("/controller")public class CityController {@Autowiredprivate CityMapper cityMapper;@RequestMapping("/city")public String view(){City city = cityMapper.findByState("CC");System.out.println(city+"=====控制台测试======");Gson gson=new Gson();String cityJson = gson.toJson(city);//把city转成json格式字符串return cityJson;}
5.Application.java启动类编写,这个类的位置要放到其他类的上一层包中,它启动时会自外而内的加载其他类。

package sample.mybatis;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration  @ComponentScan@EnableAutoConfiguration//@SpringBootApplication(相当于以上三个注解的集合,我这里没有导入相关依赖,所以没用)public class Application {public static void main(String[] args) {SpringApplication.run(Application.class,args);}}
我的这个程序中省略了Service层,实际开发中加上就好。

好了,下面我们启动Application.java类的main方法,进行测试吧。启动后控制台出现:

  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (v1.2.3.RELEASE)
在浏览器输入:http://localhost:8080/controller/city会把查出来的city对象的json窜返回到浏览器,如下:

{"id":2,"name":"beijing","state":"CC","country":"china"}

理解:Springboot内嵌的Tomcat默认端口8080



下面说说结合Freemaker的页面跳转:

pom.xml中已经引入相关jar,springboot会自动识别,

@RestController默认就会在每个方法上加上@Responsebody,方法返回值会直接被httpmessageconverter转化,

如果想直接返回视图,需要直接指定modelAndView。

我们在CityControler中在写个方法如下:

@RequestMapping("/view")public ModelAndView view2(){ModelAndView mv=new ModelAndView("index");return mv;}
新建FreeMarker模板index.ftl(在resources里新建templates文件夹放模板,系统自动找到):

<!DOCTYPE html><html> <head>  <meta charset="utf-8">  <title>标题</title> </head> <body>    我是跳转页面; </body></html>
之后启动程序,访问http://localhost:8080/controller/view  就会看到结果。

下面说说jsp页面直接跳转的配置。
注意:springboot实际不建议整合jsp,官方不不推荐使用。但实际我们也可以做,首先在pom.xml中注释掉freeMarker依赖jar。
1、在项目中建立src/main/webapp/WEB-INF/pages/index.jsp的结构(在jsp中随便写点东西)
在application.properties中加上前后缀(分新旧版本):

springboot老版本:

spring.view.prefix:/WEB-INF/pages/        

spring.view.suffix:.jsp

springboot新版本:

spring.mvc.view.prefix:/WEB-INF/pages/        

spring.mvc.view.suffix:.jsp



2、然后在controller里加个方法直接返回视图,

   @RequestMapping("/test")    public ModelAndView test() {        return new ModelAndView("index");    }}
之后启动程序,在浏览器输入http://localhost:8080/controller/test。页面会显示错误,或者读到的是未解析的jsp代码。

原因:

此处引用http://blog.csdn.net/yingxiake/article/details/51288727博客中的话
注意:jsp只能是打成war包在非嵌套的tomcat容器才能看到效果,直接在嵌套的tomcat容器是看不到效果的,
因为不支持,例如在IDE直接右键run main函数或者打成可执行的jar包都不行。
例外,如果出现freemarker模版引擎和jsp技术同时存在的话,springmvc会根据解析器的优先级来返回具
体的视图,默认,FreeMarkerViewResolver的优先级大于InternalResourceViewResolver的优先级,所以
同时存在的话,会返回freemarker视图。



原创粉丝点击