SSM详细速成

ssm速成

此文对狂神说ssm整合 进行解读

mybatis 学习+测试

pojo.Books

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Books {
    private int bookId;
    private String bookName;
    private int bookCounts;
    private String detail;
}

mybatis.xml核心文件

  • 设置连接用户名密码
  • 要访问的数据库名字
  • 关联映射文件

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>

    <mappers>
        <mapper resource="com/oxt/dao/BookMapper.xml"/>
    mappers>
configuration>

编写dao.BookMapper接口

public interface BookMapper {
    public void addBook(Books books);
    public void deleteBookById(int id);
    public void updateBook(Books books);
    public List<Books> getAllBooks();
}

实现接口,编写映射文件BookMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.oxt.dao.BookMapper">
    
    <select id="allBooks" resultType="com.oxt.pojo.Books">
        select * from books
    select>    
    

    <update id="updateBook" parameterType="com.oxt.pojo.Books">
        update ssmbuild.books
        set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where BOOKID=#{bookId}
    update>


    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books
        where BoOkID=#{s}
    delete>


    <insert id="addBook" parameterType="com.oxt.pojo.Books">
        insert into ssmbuild.books(bookName,bookCounts,detail)
        values(#{bookName},#{bookCounts},#{detail})
    insert>
    
mapper>

工具类

public class MybatisUtils {

   private static SqlSessionFactory sqlSessionFactory;

   static {
       try {

           String resource = "mybatis-config.xml";
           InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

      } catch (IOException e) {
           e.printStackTrace();
      }
  }

   //获取SqlSession连接
   public static SqlSession getSession(){
       return sqlSessionFactory.openSession();
  }

}

编写测试类

public class MyTest {
   @Test
   public void selectUser() {
       SqlSession session = MybatisUtils.getSession();
       //方法一:
//       List books = session.selectList("com.oxt.dao.BookMapper.allBooks");
       //方法二:
       BookMapper mapper = session.getMapper(BookMapper.class);
       List<Books> books = mapper.getAllBooks();


       for (Books book: books){
           System.out.println(book);
      }

//       mapper.addBook(new Books(5,"老人与海",5,"good"));
       mapper.deleteBookById(13);
//       mapper.updateBook(new Books(13,"老人与海",2222,"better"));

       session.commit();
       session.close();
  }
}
  1. 创建sqlsessionfactory
  2. 打开session会话,获取sqlSession连接
  3. session获取mapper

小结:

  • 所有的增删改操作都需要提交事务!
  • 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
  • 有时候根据业务的需求,可以考虑使用map传递参数!
  • 为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!

spring-mybatis 整合

导入依赖

  1. spring
  2. spring-jdbc操作数据库
  3. aop植入器
  4. mybatis-spring整合包

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.1.10.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.1.10.RELEASEversion>
        dependency>


        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.4version>
        dependency>

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.2version>
        dependency>

beans.xml

  1. 数据源,可以是spring自带,c3p0等
  2. 注入SQLsessionfactory,无需new;并关联mybatis(SQLsessionfactory需要数据源作为参数)
  3. 注入SQLSessionTemplate,即sqlSession
  4. 注入bookMapper的实现,该实现类中直接使用sqlSession

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    bean>


    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">

        <constructor-arg index="0" ref="sqlSessionFactory"/>
    bean>


    <bean id="bookMapper" class="com.oxt.dao.BookDaoImp">
        <property name="sqlSession" ref="sqlSession"/>
    bean>

beans>

mybatis-config.xml

    <typeAliases>
        <package name="com.oxt.pojo"/>
    typeAliases>
    <mappers>

        <package name="com.oxt.dao"/>
    mappers>

BookDaoImp

package com.oxt.dao;

import com.oxt.pojo.Books;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class BookDaoImp implements BookMapper  {
   //sqlSession不用我们自己创建了,Spring来管理
   private SqlSessionTemplate sqlSession;
   public void setSqlSession(SqlSessionTemplate sqlSession) {
       this.sqlSession = sqlSession;
  }
    @Override
    public void addBook(Books books) {
        BookMapper mapper=sqlSession.getMapper(BookMapper.class);
        mapper.addBook(books);
        sqlSession.commit();
    }
    @Override
    public void deleteBookById(int id) {
        BookMapper mapper=sqlSession.getMapper(BookMapper.class);
        mapper.deleteBookById(id);
        sqlSession.commit();
    }
    @Override
    public void updateBook(Books books) {
        BookMapper mapper=sqlSession.getMapper(BookMapper.class);
        mapper.updateBook(books);
        sqlSession.commit();
    }
    @Override
    public List<Books> getAllBooks() {

        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        return mapper.getAllBooks();
    }
}

测试

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    BookMapper mapper = (BookMapper) context.getBean("bookMapper");
    List<Books> book = mapper.getAllBooks();
    System.out.println(book);
}

SpringMVC

网页请求与处理过程:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3veKxk6Y-1675944572804)(F:\桌面\delete.jpg)]

  1. http请求—>Tomcat从磁盘加载servlet

  2. Tomcat将http请求转化为request请求对象

  3. 相应的servlet处理该request请求:转发,重定向,转发即反馈数据,重定向即切换页面

  4. tomcat将response转化为http相应

MVC

SSM详细速成_第1张图片

  • Model模型:dao,service 数据模型.
  • view 视图jsp
  • controller 控制器Servlet,负责接收用户请求和返回响应

典型mvc:javaBean+jsp+servlet

MVC框架要做哪些事情

  1. 将url映射到java类或 java类的方法.
  2. 封装用户提交的数据.
  3. 处理请求–调用相关的业务处理–封装响应数据.
  4. 将响应的数据进行渲染. jsp/html等表示层数据

Servlet

准备依赖

  1. servlet
  2. jsp
<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>servlet-apiartifactId>
    <version>2.5version>
dependency>
<dependency>
    <groupId>javax.servlet.jspgroupId>
    <artifactId>jsp-apiartifactId>
    <version>2.2version>
dependency>

配置web.xml,处理http请求

  1. 配置处理请求的servlet
  2. 配置路径处理的mapping
<servlet>
    <servlet-name>com.oxt.servlet.HelloServletservlet-name>
    <servlet-class>com.oxt.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>com.oxt.servlet.HelloServletservlet-name>
    <url-pattern>/userurl-pattern>
servlet-mapping>

编写servlet,处理request请求

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String method = req.getParameter("method");//获取参数
    if(method.equals("add")){
        req.getSession().setAttribute("msg","执行了add方法");
    }else{
        req.getSession().setAttribute("msg","没执行add");
    }
    req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);//视图跳转
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
}

第一个SpringMVC

配置开发

web.xml

  1. 同上web.xml,但是servlet变成了DispatcherServlet

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

        
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc-servlet.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>

    
    
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

关联的springmvc-servlet.xml

  1. 处理器
  2. 处理器适配器
  3. 视图解析器
  4. 请求处理类映射

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>



    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>

    
    <bean id="/hello" class="com.oxt.controller.HelloController"/>

beans>
  • hello请求从xx-servlet.xml转到相应的处理器
public class HelloController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //ModelAndView 模型和视图
        ModelAndView mv = new ModelAndView();

        //封装对象,放在ModelAndView中。Model
        mv.addObject("msg","HelloSpringMVC!");

        //封装要跳转的视图,放在ModelAndView中
        mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
        return mv;
    }
}
  • 实现接口,导入接口的包org.springframework.web.servlet.mvc.Controller;
注解开发

web.xml

  1. 注册DispatcherServlet
<servlet>
    <servlet-name>SpringMVChereservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
    	<param-name>contextConfigLocationparam-name>
    	<param-value>classpath:springmvc-servlet.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
servlet>
  1. 设置springmvc拦截请求
<servlet-mapping>
	<servlet-name>SpringMVChereservlet-name>
	<url-pattern>/url-pattern>
servlet-mapping>

12成双

resources下建立springmvc-servlet.xml


<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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  1. 自动扫描包:该包下的注解生效,由IOC容器管理
<context:component-scan base-package="com.oxt.controller"/>
  1. 不让SpringMVC处理静态资源

在 WEB 容器启动的时候会在上下文中定义一个 DefaultServletHttpRequestHandler,它会对DispatcherServlet的请求进行处理,如果该请求已经作了映射,那么会接着交给后台对应的处理程序,如果没有作映射,就交给 WEB 应用服务器默认的 Servlet 处理,从而找到对应的静态资源,只有再找不到资源时才会报错。点击查看原文

如果想要解决访问静态资源问题,通常会使用默认handler:

<mvc:default-servlet-handler />

3.处理器和适配器

<mvc:annotation-driven />
  
  1. 视图解析器

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
bean>

com.oxt.controller.HelloController

@Controller
@RequestMapping("/helloController")//类请求
public class HelloController{
    @RequestMapping("hello")
    pubulic String helloC(Model model){
        model.addAttribute("msg","hello,you,how");
        return "hello";//返回页面  视图解析加上前后缀:/WEB-INF/jsp/hello.jsp
    }
}

hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    SpringMVC


${msg}


小结

实现步骤其实非常的简单:

  1. 新建一个web项目
  2. 导入相关jar包
  3. 编写web.xml , 注册DispatcherServlet
  4. 编写springmvc配置文件
  5. 接下来就是去创建对应的控制类 , controller
  6. 最后完善前端视图和controller之间的对应
  7. 测试运行调试.

使用springMVC必须配置的三大件:

处理器映射器、处理器适配器、视图解析器

通常,我们只需要手动配置视图解析器,而处理器映射器处理器适配器只需要开启注解驱动即可,而省去了大段的xml配置

web.xml中的dispatchcer servlet用的spring总文件

spring总文件中import三层文件:springmvc,dao,service

springdao.xml中:数据源,sqlSessionFactory,

SSM整合

导入依赖

sprig+mybatis

1.编写pojo

2.编写mapper类和映射文件

3.编写service层

编写配置文件

1.spring总文件applicationContext.xml:import三层的xml文件,实际上就是一个spring文件

2.spring-dao.xml

在spring-mybatis中,用factory获取sqlsession,factory需要映射文件作为参数,sqlsession获取相应的mapper类 然后增删改查操作

  • 引入database.properties
    标签为
    ssm加上classpath:才正常运行,仅用于spring-mybatis可以不加
  • bean:dataSource
  • bean:SQLSessionFactory ,需要注入映射文件mybatis
    (mybatis文件中设置别名typeAliases 以及mappers标签中设置映射文件位置)
  • bean:配置class MapperScannerConfigurer 需要注入sqlsessionfactory
    扫描dao层的类,自动注册各个mapper类的bean

3.spring-service.xml

  • import spring-dao
  • 扫描service层
  • bean:serviceImp
  • bean:事务管理器

spring+springmvc

idea中要注意在web文件夹中添加lib依赖

web.xml

1.servlet 指定总spring配置文件

2.servlet-mapping 指定/请求处理的servlet↑

3.filter拦截请求

4.session过期时间

conroller层类编写

1.@Controller标记

2.RequestMapping,类中和方法上

3.bean:bookService 使用@AutoWired和@Qualifier指定

3.编写各个请求的处理方法 String name(Model model){return jsp页面}

4.编写相应的jsp

spring-mvc.xml

1.注解驱动

2.静态视图资源 使用默认servlet

3.视图解析 前后缀

4.扫描controller包

你可能感兴趣的:(mybatis,java,mysql,spring,mvc)