Java云原生---Spring、SpringMVC、Mybatis

一、核心

Spring的核心容器部分由spring-core, spring-beansspring-contextspring-context-support,和spring-expression 模块组成

二、IOC与AOP

(一)IOC(Inversion of Control)容器

Spring 容器是 Spring 框架的核心。容器里面存放的都是由Spring管理的对象,与在程序中自己new出来的对象不一样的是,容器中对象的生命周期,都是由容器来管理,而new出来的对象是不受容器管理的。

IOC 容器是具有依赖注入功能的容器,它可以创建对象,IOC 容器负责实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。通常new一个实例,控制权由程序员控制,而"控制反转"是指new实例工作不由程序员来做而是交给Spring容器来做。在Spring中BeanFactory是IOC容器的实际代表者。

(二)AOP

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。面向切面可以简单理解为在类的方法前后都可以进行拦截,比如我们需要知道A方法被调用了多少次,又不能侵入这个方法(也就是不能改动这个方法),那么我们就可以在方法前做一个切面,在切面中我们加一个计数的逻辑,在进入方法A之前会先执行我们切面里的内容,这样就能完成方法调用次数的统计而又不侵入业务代码了。

三、实现

1.新建Maven项目

2.完善项目目录

3.新建Controller

4.配置web.xml中servlet

5.配置servlet.xml

 <bean name="/form" class="net.csdn.ssm.controller.FormController"></bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

6. 创建service和serviceimpl

7.controller引入service并创建set方法

private FormService formService;

8.配置servlet.xml

    <bean id="formService" class="net.csdn.ssm.service.impl.FormServiceImpl"></bean>
    <bean name="/form" class="net.csdn.ssm.controller.FormController">
        <property name="formService" ref="formService"></property>
    </bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

9,dao与daoImpl

package net.csdn.ssm.dao;

import net.csdn.ssm.vo.param.FormDataParam;

/**
 * @Author:张金贺
 * @Date:2022/7/31 13:34
 * @Version 1.0
 */
public interface FormDao {
    void insertForm(FormDataParam formDataParam);
}
package net.csdn.ssm.dao.impl;

import net.csdn.ssm.dao.FormDao;
import net.csdn.ssm.vo.param.FormDataParam;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author:张金贺
 * @Date:2022/7/31 13:34
 * @Version 1.0
 */
public class FormDaoImpl implements FormDao {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void insertForm(FormDataParam formDataParam) {
        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/form", "root", "root");
            PreparedStatement preparedStatement = connection.prepareStatement("insert into form_user_basic(name,sex,cell_Phone,birthday) values(?,?,?,?)");
            preparedStatement.setString(1,formDataParam.getName());
            preparedStatement.setInt(2,formDataParam.getSex());
            preparedStatement.setString(3,formDataParam.getCellPhone());
            preparedStatement.setLong(4,formDataParam.getBirthday());
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

10.serviceimpl引入dao层,创建set方法,并在方法中调用。

private FormDao formDao;

11.配置servlet.xml

 <bean id="formDao" class="net.csdn.ssm.dao.impl.FormDaoImpl"></bean>
    <bean id="formService" class="net.csdn.ssm.service.impl.FormServiceImpl">
        <property name="formDao" ref="formDao"></property>
    </bean>

12.controller

 FormDataParam formDataParam = new FormDataParam();
        String name = httpServletRequest.getParameter("name");
        Integer sex = Integer.parseInt(httpServletRequest.getParameter("sex"));
        String cellPhone = httpServletRequest.getParameter("cellPhone");
        String birthday = httpServletRequest.getParameter("birthday");
        formDataParam.setName(name);
        formDataParam.setSex(sex);
        formDataParam.setCellPhone(cellPhone);

        CharSequence text;
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
        LocalDate localDate = LocalDate.parse(birthday,formatter);
        java.util.Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        formDataParam.setBirthday(date.getTime());
        formService.insertForm(formDataParam);
       ModelAndView modelAndView = new ModelAndView();
       modelAndView.setViewName("form");

四、注解开发

daoimpl:@Repository//标识为数据访问类

serviceimpl:@Service//标识为业务类

@Autowired//标识为自动注入

@PostMapping

web.xml:<context:component-scan base-package="net.csdn.ssm"/>

五、解决乱码

web.xml

<filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <!-- 使用utf-8编码 -->
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <!-- 任何情况下强制使用此编码 -->
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>*</url-pattern>
    </filter-mapping>

六、集成Mybatis(mybatis.org)

1.引入Mybatis依赖,在pom.xml中增加依赖

<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.4.5</version>
        </dependency>

2.servlet.xml中配置Mybatis和连接池相关信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="net.csdn.form"/>
    <!--    配置连接池信息-->
    <bean name="dataSource" class="com.zaxxer.hikari.HikariDataSource">
        <!--    配置连接信息    -->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl"
                  value="jdbc:mysql://localhost:3306/form?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--    配置连接工厂信息-->
    <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!--扫描接口包路径,生成包下所有接口的代理对象,并且放入spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="net.csdn.form.mapper"/>
    </bean>

    <!--    视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3.创建包entity,然后再创建一个实体类用来和数据库字段一一对应

4.创建一个包mapper,在包中创建一个Mapper类Mapper(@Mapper)

@Mapper
public interface FormUserBasicMapper {
    void insert(FormUserBasic  formDataParam);
}

5. 写SQL语句

resources目录下新建一个文件夹叫mapper,然后在mapper文件夹中新建一个formUserBasicMapper.xml配置文件,在mapper文件中增加一个插入方法

#{}:这是Mybatis取参数属性的一种方式,这种方式取值会走预编译模式,也就是PreparedStatement占位符的方式

${}:这种方式也是Mybatis取参数属性的一种方式,但是这种方式会直接拼接SQL,所以可能会有SQL注入的问题,一般用的比较少

<?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="net.csdn.form.mapper.FormUserBasicMapper">
    <insert id="insert" parameterType="net.csdn.form.entity.FormUserBasic">
        insert into form_user_basic(name,sex,cell_phone,birthday) values(#{name},#{sex},#{cellPhone},#{birthday});
    </insert>
</mapper>

 6.daoImpl

创建FormUserBasic对象后直接调用。

七、注意的问题

1.避免XSS注入

2.监听在线人数

3.Cookie表单数据管理

4.图片验证码

(1)依赖:

    <dependency>
      <groupId>com.github.whvcse</groupId>
      <artifactId>easy-captcha</artifactId>
      <version>1.6.2</version>
    </dependency>

(2)前端html

   <div class="cart cart-box code">
                        <!-- <div class="cart-title">验证码</div> -->
                        <div class="form-group">
                            <!-- label表示文字提示标签,可以通过表单的组建的id提示-->
                            <label class="col-md-2 control-label" for="captcha">验证码</label>
                            <div class="col-md-6">
                                <input class="form-control" id="captcha" placeholder="验证码" name="code"
                                       type="text"></input>
                            </div>
                            <div class="col-md-2">
                                <img src="${pageContext.request.contextPath}/captcha" alt="加载失败" srcset=""
                                     class="captcha" onclick="refreshImg()" id="code-img">
                            </div>
                        </div>
                    </div>

前端JS

 function refreshImg(){
        document.getElementById("code-img").src="${pageContext.request.contextPath}/captcha?"+Math.random();
    }

(3)后端处理

FormController中对图片验证码进行判断

package net.csdn.form.controller;

import com.wf.captcha.utils.CaptchaUtil;
import net.csdn.form.error.constants.BizErrorConstants;
import net.csdn.form.exception.BizException;
import net.csdn.form.service.FormService;
import net.csdn.form.vo.param.FormDataParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;



@Controller
@RequestMapping("/form")
public class FormController {
    @Autowired
    private FormService formService;

    @PostMapping
    public ModelAndView postForm(HttpServletRequest req, @Validated FormDataParam formDataParam) throws BizException {
        String code = formDataParam.getCode();
        if (!CaptchaUtil.ver(code, req)) {
            // 清除session中的验证码
            CaptchaUtil.clear(req);
            throw new BizException(BizErrorConstants.CAPTCHA_ERROR_CODE);
        }
        formService.insertForm(formDataParam);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("form");
        return modelAndView;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java张金贺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值