SpringBoot-ssm

SpringBoot-ssm

1、创建项目
lombok、devtool、spring web、mybatis、oracle driver

2、在src/main下创建文件

  • webapp
  • webapp/WEB-INF
  • webapp/WEB-INF/content

3、application.properties

# 配置连接池,使用默认推荐的HikariCP
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:ORCL
spring.datasource.username=yanjun
spring.datasource.password=123456
# web应用相关配置
spring.mvc.view.prefix=/WEB-INF/content/
spring.mvc.view.suffix=.jsp

spring.mvc.format.date=yyyy-MM-dd

4、修改pom.xml引入针对jsp的支持,springBoot不再建议使用jsp,而是建议使用模板引擎创建视图Thymeleaf

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

5、环境测试

  • 创建一个控制器
@Controller
public class CommonController {
    @RequestMapping({"","/"})
    public String index(){
        return "index";
    }
}
  • 在/WEB-INF/content/目录下创建index.jsp
this is index.jsp
  • 通过直接执行main方法或者通过maven启动应用

  • 浏览器http://localhost:8080/,如果能够看到页面则表示环境运行正常

6、创建对应的数据表

create table tb_users(
    id number(18) primary key,
    username varchar2(20) not null unique,
    password varchar2(20) not null,
    birth date default sysdate,
    sex number(1) default 1,
    pict varchar2(50) default 'images/nopic.jpg'
);

7、引入mybatis的反向工程插件执行反向映射,以生成实体类、映射元文件以及接口

<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.4.0</version>
    <configuration>
        <!-- 执行命令mybatis-generator:generate -->
        <!-- 在控制台打印执行日志 -->
        <verbose>true</verbose>
        <!-- 重复生成时会覆盖之前的文件-->
        <overwrite>true</overwrite>
        <!--反向工程所需要的配置文件-->
        <configurationFile>src/test/resources/generatorConfig.xml</configurationFile>
    </configuration>
</plugin>

新增反向映射配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <classPathEntry location="c:\ojdbc8-12.2.0.1.jar"/>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="false"/>
            <property name="suppressAllComments" value="false"/>
        </commentGenerator>
        <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
                        connectionURL="jdbc:oracle:thin:@localhost:1521:ORCL"
                        userId="yanjun" password="123456"></jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <javaModelGenerator targetPackage="com.yan.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="com.yan.mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.yan.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <table tableName="tb_users" domainObjectName="User"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

执行反向映射。反向映射生成代码后,进行代码的检查和修改。

实体类

@Data
public class User implements Serializable {
    private Long id;
    private String username;
    private String password;
    private Date birth;
    private Boolean sex;
    private String pict;
}

映射接口

public interface UserMapper {    int deleteByPrimaryKey(Long id);    int insertSelective(User record);    User selectByPrimaryKey(Long id);    int updateByPrimaryKeySelective(User record);    List<User> selectByExample(User record);}

映射元文件

<?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="com.yan.dao.UserMapper">    <resultMap id="BaseResultMap" type="com.yan.entity.User">        <id column="ID" jdbcType="NUMERIC" property="id"/>        <result column="USERNAME" jdbcType="VARCHAR" property="username"/>        <result column="PASSWORD" jdbcType="VARCHAR" property="password"/>        <result column="BIRTH" jdbcType="DATE" property="birth"/>        <result column="SEX" jdbcType="BOOLEAN" property="sex"/>        <result column="PICT" jdbcType="VARCHAR" property="pict"/>    </resultMap>    <sql id="Base_Column_List">        ID, USERNAME, PASSWORD, BIRTH, SEX, PICT    </sql>    <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from TB_USERS        where ID = #{id,jdbcType=NUMERIC}    </select>    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">        delete        from TB_USERS        where ID = #{id,jdbcType=NUMERIC}    </delete>    <insert id="insertSelective" parameterType="com.yan.entity.User">        <selectKey order="BEFORE" keyProperty="id" resultType="long">            select seq_users.nextval from dual        </selectKey>        insert into TB_USERS        <trim prefix="(" suffix=")" suffixOverrides=",">            <if test="id != null">                ID,            </if>            <if test="username != null">                USERNAME,            </if>            <if test="password != null">                PASSWORD,            </if>            <if test="birth != null">                BIRTH,            </if>            <if test="sex != null">                SEX,            </if>            <if test="pict != null">                PICT,            </if>        </trim>        <trim prefix="values (" suffix=")" suffixOverrides=",">            <if test="id != null">                #{id,jdbcType=NUMERIC},            </if>            <if test="username != null">                #{username,jdbcType=VARCHAR},            </if>            <if test="password != null">                #{password,jdbcType=VARCHAR},            </if>            <if test="birth != null">                #{birth,jdbcType=DATE},            </if>            <if test="sex != null">                #{sex,jdbcType=BOOLEAN},            </if>            <if test="pict != null">                #{pict,jdbcType=VARCHAR},            </if>        </trim>    </insert>    <update id="updateByPrimaryKeySelective" parameterType="com.yan.entity.User">        update TB_USERS        <set>            <if test="username != null">                USERNAME = #{username,jdbcType=VARCHAR},            </if>            <if test="password != null">                PASSWORD = #{password,jdbcType=VARCHAR},            </if>            <if test="birth != null">                BIRTH = #{birth,jdbcType=DATE},            </if>            <if test="sex != null">                SEX = #{sex,jdbcType=BOOLEAN},            </if>            <if test="pict != null">                PICT = #{pict,jdbcType=VARCHAR},            </if>        </set>        where ID = #{id,jdbcType=NUMERIC}    </update>    <select id="selectByExample" parameterType="com.yan.entity.User" resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from tb_users        <where>            <if test="username != null">                USERNAME like #{username,jdbcType=VARCHAR}            </if>            <if test="password != null">                and PASSWORD = #{password,jdbcType=VARCHAR}            </if>            <if test="birth != null">                and BIRTH = #{birth,jdbcType=DATE}            </if>            <if test="sex != null">                and SEX = #{sex,jdbcType=BOOLEAN}            </if>            <if test="pict != null">                and PICT = #{pict,jdbcType=VARCHAR}            </if>            <if test="id!=null">                ID = #{id,jdbcType=NUMERIC}            </if>        </where>    </select></mapper>

修改application.properties注册映射元文件

mybatis.mapper-locations=classpath:com/yan/mapper/*.xml

在主类上添加注解

@MapperScan("com.yan.dao")  //com.yan.dao包中用于存放Mapper接口

针对Mybatis进行单元测试

@SpringBootTestclass Springboot02ApplicationTests {    @Autowired    private UserMapper userMapper;    @Test    void contextLoads() {        userMapper.selectByExample(null).forEach(System.out::println);    }}

8、定义业务处理

spring要求面向接口编程

public interface IUserServ {    public boolean login(User user);}

针对接口提供实现类

@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)@Servicepublic class UserServImpl implements IUserServ{    @Autowired    private UserMapper userMapper;    @Override    public boolean login(User user) {        Assert.notNull(user,"参数不能为空!");        Assert.hasText(user.getUsername(),"用户名称不能为空!");        Assert.hasText(user.getPassword(),"用户口令不能为空!");        List<User> userList=userMapper.selectByExample(user);        if(userList!=null && userList.size()>0){            User tmp=userList.get(0);            BeanUtils.copyProperties(tmp,user);            return true;        }        return false;    }}

定义业务上所需要的声明式事务管理

修改主类,使用注解打开声明式事务支持

@EnableTransactionManagement@MapperScan("com.yan.dao")@SpringBootApplicationpublic class Springboot02Application {    public static void main(String[] args) {        SpringApplication.run(Springboot02Application.class, args);    }}

添加注解后,则可以在业务类上直接使用注解声明事务特性

9、修改控制器调用业务处理逻辑

@RequestMapping(value="login",method = RequestMethod.POST)    public String login(@ModelAttribute("user") User user, Errors errors, Model model)throws Exception{        boolean bb=userService.login(user);        if(bb){            model.addAttribute("userInfo",user);            return "redirect:/admin/show";        }else{            model.addAttribute("msg","登录失败!请重新尝试");            return "user/login";        }    }

如何查看日志输出信息

在application.properties中添加日志输出配置即可,甚至可以不用log4j.properties之类的配置文件

logging.level.com.yan=debug

10、添加服务器端数据校验

引入依赖

 <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-validation</artifactId> </dependency>

不需要进行任何配置

在控制器方法中添加注解打开数据校验

@Validated(UserGroup.LoginGroup.class) User user, Errors errors

方法的参数User和Errors之间的顺序不能进行任何调整,服务器端的报错信息会自动存储在errors中

在页面上显示报错信息<form:errors path="输入域的名称"/>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值