Springboot:IntelliJ运行配置Spring Boot项目
(37条消息) 从零开始搭建springboot框架_程序员杨叔的博客-CSDN博客_从0开始搭建springboot
1、用IDEA新建一个SpringBoot项目
File→New→Project→Spring Initializr→项目名为springbootmybatisxml
注意JDK与Java版本的匹配
2、添加依赖
添加Spring Web和MyBatis Framework两个依赖
3、在工程项目下,构造如下目录结构
对各文件的说明
文件 |
说明 |
User | 一个JavaBean,数据库字段映射的对象 |
WebMvcConfig | WebMvc配置类,用于覆写addViewControllers配置映射关系,实现页面路由 |
SwaggerConfig | Swagger配置类,配置只有在方法上使用@ApiOperation注解才会暴露给swagger |
UserController | Controller层,定义前端请求与后端接口的映射关系 |
UserDao |
数据持久层,定义数据库相关接口方法,是个接口,只定义无实现。 |
UserServices | 接口层,定义后端接口,定义各个的业务逻辑方法的功能 |
UserServicesImpl | 接口实现类,后端接口的具体方法实现。 |
SpringbootmybatisxmlApplication | 工程启动类,main方法所在类 |
resources |
资源文件夹 |
UserMapper.xml | Mybatis mapper配置文件,管理数据相关方法的具体实现 |
static | 前端页面的相关静态js/css文件、字体、图片等 |
templates | 前端页面HTML文件 |
application.properties | 配置文件,配置数据库,Redis等相关配置 |
4、具体代码
4.1*、pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.yy</groupId> <artifactId>springbootmybatisxml</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springbootmybatisxml</name> <description>Demo project for Spring Boot</description> <packaging>jar</packaging> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>com.intellij</groupId> <artifactId>annotations</artifactId> <version>6.0.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency> <!--swagger依赖--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
4.1、bean→User.java
public class User { //映射数据库字段 private Long id; private String name; private Integer age; private String pwd; //定义一个msg,发送消息 private String msg; //判断是否成功 private boolean success; //getter与setter方法 }
4.2、common→WebMvcConfig.java
WebMvc配置类,用于覆写addViewControllers方法配置映射关系,实现URL与具体HTML文件跳转关系:
/** * 过去使用SpringMVC时,如果要访问一个页面,必须要写相应的Controller类 * 而 SpringBoot 要实现这个需求,只需要在MVC配置类中覆写addViewControllers方法配置映射关系即可, * 不用再写相应的Controller类 */ @Configuration public class WebMvcConfig implements WebMvcConfigurer { public void addViewController(ViewControllerRegistry registry){ registry.addViewController("/login").setViewName("login"); registry.addViewController("/register").setViewName("register"); registry.addViewController("/loginNew").setViewName("loginNew"); registry.addViewController("/registerNew").setViewName("registerNew"); registry.addViewController("/sessionResult").setViewName("sessionResult"); } }
4.3、config→SwaggerConfig
Swagger配置类,配置只有在方法上使用@ApiOperation注解才会暴露给swagger
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .select() //只有在类上使用@Api注解,且在方法上用@ApiOpertaion注解才会暴露 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation)) .build(); } }
4.4、dao→UserDao
数据持久化,定义数据库相关接口方法:
@Repository @Mapper public interface UserDao { //查询用户是否存在 User findUserByName(String name); //新增用户 void register(String name, Integer age,String pwd); //用户登录 Long login(String name,String pwd); //根据ID查询用户信息 User findUserById(Long id); }
4.5、services→UserServices
接口层,定义后端接口——注册和登录接口。
只是定义接口,具体的实现在它的实现类中。
public interface UserServices { User register(String name , Integer age,String pwd); User login(String name,String pwd); }
4.6、Services→impl→UserServicesImpl
接口UserService的实现类,4.4中所说的方法的具体实现:
public class UserServicesImpl implements UserServices { @Autowired private UserDao userDao; @Override public User register(String name,Integer age,String pwd){ ... } @Override public User login(String name,String pwd){ ... } }
register
public User register(String name, Integer age, String pwd) { User existUser = userDao.findUserByName(name); User result = new User(); try { if (existUser != null) { result.setMsg("用户名已存在!"); result.setSuccess(false); result.setId(existUser.getId()); result.setAge(existUser.getAge()); result.setName(existUser.getName()); result.setPwd(existUser.getPwd()); } else { userDao.register(name, age, pwd); result.setMsg("注册成功!"); result.setSuccess(true); //注册后再使用该名字查询用户信息 User currentRegUser = userDao.findUserByName(name); result.setId(existUser.getId()); result.setAge(existUser.getAge()); result.setName(existUser.getName()); result.setPwd(existUser.getPwd()); } } catch (Exception e) { e.printStackTrace(); result.setMsg(e.getMessage()); } return result; }
login
@Override public User login(String name, String pwd) { User result = new User(); result.setSuccess(false); Long userId = userDao.login(name, pwd); try { if (userId != null) { result.setMsg("登录成功!"); result.setSuccess(true); //根据userId查询出当前登录用户 User currentLoginUser = userDao.findUserById(userId); result.setId(userId); result.setPwd(currentLoginUser.getPwd()); result.setName(currentLoginUser.getName()); } else { result.setMsg("用户名或密码不正确!"); result.setSuccess(false); } } catch (Exception e) { e.printStackTrace(); result.setMsg(e.getMessage()); } return result; }
4.7、controller→UserController
Controller层,定义前端请求与后端接口的映射关系,主要是两个接口——注册与登录:
import com.example.springbootmybatisxml.bean.User;
import com.example.springbootmybatisxml.services.UserServices;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//import springfox.documentation.schema.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Api(description = "用户注册登录") @Slf4j @Controller @RequestMapping(value = "/api/user") public class UserController { @Autowired private UserServices userServices; //具体的login与register方法 }
register
@ApiOperation(value = "用户注册", notes = "注册会员") @RequestMapping(value = "/register", method = RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "用户名", dataType = "String", required = true), @ApiImplicitParam(name = "age", value = "年龄", dataType = "Int", required = true), @ApiImplicitParam(name = "pwd", value = "密码", dataType = "String", required = true) }) public String register(String name, Integer age, String pwd, Model model, HttpServletRequest request, HttpServletResponse response ) throws Exception { try { //打印日志 log.info(name + "," + age + "," + pwd); //获取注册结果 User result = userServices.register(name, age, pwd); if (result.isSuccess()) { //将结果保存在Model中,用于前端View展示 model.addAttribute("result", result); //跳转到注册结果页面 return "/registerResult"; } else { response.setContentType("application/json; charset=utf-8"); response.getWriter().print("{\"code\":\"0002\",\"msg\":\"用户名已存在,注册失败!\"}"); } } catch (Exception e) { e.printStackTrace(); } return null; }
login
//login @ApiOperation(value="用户登录",notes="用户名密码登录") @RequestMapping(value="/login",method=RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name="name",value="用户名",dataType="String",required = true), @ApiImplicitParam(name="pwd",value="密码",dataType="String",required = true), }) public String login(String name,String pwd,Model model, HttpServletRequest request, HttpServletResponse response )throws Exception{ try{ //打印日志 log.info(name+","+pwd); User result = userServices.login(name,pwd); if(result.isSuccess()){ //将结果存到model中,用于前端view层显示 model.addAttribute("result",result); HttpSession session = request.getSession(); session.setAttribute("name",result.getName()); session.setAttribute("password",result.getPwd()); System.out.println("登录后的sessionId:"+session.getId()); //跳转到登录结果页面 return"/loginResult"; }else{ response.setContentType("application/json; charset=utf-8"); response.getWriter().print("{\"code\":\"0001\",\"msg\":\"用户名或密码错误!\"}"); } }catch(Exception e){ e.printStackTrace(); } return null; }
4.8、SpringbootmybatisxmlApplication
Springboot的启动类,main方法所在(写法基本不会变):
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringbootmybatisxmlApplication { public static void main(String[] args) { SpringApplication.run(SpringbootmybatisxmlApplication.class, args); } }
4.9、resources→mapper→UserMapper
Mybatis mapper配置文件,管理UserDao中具体方法实现:
<?xml version="1.0" encoding="UTF-8" ?> <mapper namespace="com.example.springbootmybatisxml.dao.UserDao"> <!--JavaBean属性与数据库列之间的映射--> <resultMap id="BaseResultMap" type="com.example.springbootmybatisxml.bean.User"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="name" property="name" jdbcType="VARCHAR"/> <result column="pwd" property="pwd" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="INTEGER"/> </resultMap> <sql id="Base_Column_List"> id,name,age,pwd </sql> <!--具体的Dao方法的数据库实现--> <select id="findUserByName" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from t_user where name=#{name} </select> <select id="login" resultType="java.lang.Long"> select u.id from t_user u where u.name=#{param1} and u.pwd=#{param2} </select> <select id="findUserById" resultMap="BaseResultMap"> select * from t_user u where u.id=#{id} </select> <inser id="register"> insert into t_user (name,age,pwd) values(#{param1},#{param2},#{param3}) </inser> </mapper>