SSM 入门

项目目标

实现ssm对账户查询所有功能

1.数据库准备

CREATE DATABASE ssm;
USE ssm;
CREATE TABLE account (
	id INT PRIMARY KEY auto_increment,
	name VARCHAR (32),
	money DOUBLE (6,2)
);

2.环境配置

1.创建如下的maven的工程项目

在这里插入图片描述
记得添加属性
archetypeCatalog = internal

2.创建目录结构如图

添加文件夹
在这里插入图片描述

3.pom.xml添加版本锁定和依赖的的坐标

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <!-- 版本锁定 -->
        <spring.version>5.1.0.RELEASE</spring.version>
        <mysql.version>5.1.6</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
    </properties>

    <dependencies>
        <!-- spring -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

    </dependencies>

4.创建实体类

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;

    public Account() {
    }

    public Account(Integer id, String name, Double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

5.dao,service

接口只有findAll(只是为了方便)

/**
     * 查询所有
     * @return
     */
    List<Account> findAll();

6.目前目录结构

在这里插入图片描述

3.spring部分

1.代码编写

编写Spring部分的配置文件 bean.xml

<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--要扫描的包-->
    <!--要扫描的是service和dao层的注解,需要忽略web层注解,因为web层让SpringMVC框架去管理-->
    <context:component-scan base-package="priv.xy">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

因为是自己创建的,为了方便,使用注解配置
@Service

@Service
public class AccountServiceImpl implements AccountService {
    @Override
    public List<Account> findAll() {
        System.out.println("spring");
        return null;
    }
}

2.测试功能

在这里插入图片描述

public class SpringTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean.xml");
        AccountService serviceImpl = context.getBean("accountServiceImpl",AccountService.class);
        serviceImpl.findAll();
    }
}

4.SpringMVC部分

1.代码编写

在web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--防止中文乱码-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--服务器启动的时候,让DispatcherServlet对象创建-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

创建springmxc.xml

<?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"
       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
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--要扫描的包-->
    <!--要扫描的只是web层注解-->
    <context:component-scan base-package="priv.xy">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--因为我将所有jsp页面都写在wepapp目录下的所以是/ 可以/WEB-INF/pages/(前提你将页面放在pages下)-->
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- spring开启注解mvc的支持-->
    <!-- 自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter -->
    <!-- 即处理器映射器和处理器适配器-->
    <mvc:annotation-driven/>

    <!-- 设置静态资源不过滤 -->
    <!--需要再写-->
    <!--<mvc:resources location="/img/" mapping="/img/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>-->
	<!-- <mvc:default-servlet-handler/> -->
</beans>

controller部分

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("SpringMVC");
        return "success";
    }
}

jsp部分
index.jsp

<body>
    <a href="account/findAll">test</a>
</body>

success.jsp

<body>
    <h3>success</h3>
</body>

2.测试功能

配置了服务器,页面点下,控制台看输出就完事了
目前目录结构
在这里插入图片描述

5.整合 Spring 和 SpringMVC

1.目的

在controller中能成功的调用service对象中的方法

2.问题

现在bean.xml配置文件的加载是用new ClassPathXmlApplicationContext(“classpath:bean.xml”);的方式,需要加载bean.xml

3.解决方法

1.将测试的代码加入controller(不推荐)
@RequestMapping("/findAll")
    public String findAll(){
        System.out.println("SpringMVC");
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean.xml");
        AccountService serviceImpl = context.getBean("accountServiceImpl",AccountService.class);
        serviceImpl.findAll();
        return "success";
    }
2.使用监听器加载(推荐)

在项目启动的时候,就去加载bean.xml的配置文件,在web.xml中配置ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的的配置文件)。

<!--配置spring监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--配置加载类路径的配置文件-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:bean.xml</param-value>
  </context-param>

controller

@Controller
@RequestMapping("/account")
public class AccountController {

	// 其实这种是不建议的,还不是因为方便
    @Autowired
    @Qualifier("accountServiceImpl")
    private AccountService service;
    /*
    可以这样
    private AccountService service;
    
    @Autowired
    public AccountController(AccountService service) {
        this.service = service;
    }
    */
    
    /*
    还可以这样
    private AccountService service;

    @Autowired
    @Qualifier("accountServiceImpl")
    public void setService(AccountService service) {
        this.service = service;
    }
    */

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("SpringMVC");
        service.findAll();
        return "success";
    }
}

6.Mybatis部分

1.代码

dao添加注解

public interface AccountDao {
    /**
     * 查询所有
     * @return
     */
    @Select("select * from Account ")
    List<Account> findAll();
}

创建SqlMapConfig.xml

<?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>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="priv.xy.dao"/>
    </mappers>
</configuration>

2.测试方法

public class MybatisTest {
    @Test
    public void test() throws IOException {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = factory.openSession();
        AccountDao dao = session.getMapper(AccountDao.class);
        List<Account> list = dao.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
        // 如果是CUD方法需要session.commit();
        session.close();
        is.close();
    }
}

3.目录结构

在这里插入图片描述

在这里插入图片描述

7.整合 Spring 和 Mybatis

1.目的

把SqlMapConfig.xml配置文件中的内容配置到bean.xml配置文件中

2.问题

需要加载配置文件的内容

3.解决方法

在spring的bean.xml配置文件加载,所以可以删除SqlMapConfig.xml了
bean.xml加入

<!--配置Mybatis-->
    <!--配置C3P0的连接池对象-->
    <!--不用c3p0可以配置其他数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>
    <!--配置session工厂-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置扫描的dao包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="priv.xy.dao"></property>
    </bean>

在AccountDao接口中添加@Repository注解
在service中注入dao对象,进行测试

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao dao;
    @Override
    public List<Account> findAll() {
        System.out.println("spring");
        return dao.findAll();
    }
}

controller

@RequestMapping("/findAll")
    public String findAll(Model model) {
        System.out.println("SpringMVC");
        List<Account> list = service.findAll();
        // 存入request域中
        model.addAttribute("LIST", list);
        for (Account account : list) {
            System.out.println(account);
        }
        return "success";
    }
}

jsp
success.jsp

<body>
    <h3>success</h3>
    ***${LIST}<br>
    <%--or--%>
    ***${requestScope.LIST}<br>
</body>

4.extend

如果是CUD操作需要提交事务
可以在bean.xml加入

<!--配置spring的事务管理-->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--一次执行多次查询来统计某些信息,这时为了保证数据整体的一致性,要用只读事务-->
            <tx:method name="find*" read-only="true"></tx:method>
            <tx:method name="*" isolation="DEFAULT"></tx:method>
        </tx:attributes>
    </tx:advice>
    <!--配置aop增强-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* priv.xy.service.impl.AccountServiceImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

8.总结

项目只是入门,好多关键性的东西还没有提及,自勉
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值