SSM framework

Introduction

Spring+SpringMVC+MyBatis framework (SSM) is a relatively popular framework for small and medium-sized enterprise-level project development, and it is also relatively easy for novices to learn and get started. Although it is easy, there are still many problems encountered in the process of building the framework, so let’s record it with examples.

SSM


example

The first step - guide package

Spring framework package and its dependencies
MyBatis framework package and its dependencies
MyBatis-EhCache rack package
C3P0 rack package
MySql database driver package

The project rack package is as follows:
Jar包

The project structure is as follows:
Project structure

Step 2 - Integrate the Dao layer (Spring+MyBatis)

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>
    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

Because MyBatis is managed by Spring, Mapper is configured in Spring, and the configuration here only opens the second-level cache

applicationContext-dao.xml

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db_pwc" />
        <property name="user" value="pwc" />
        <property name="password" value="123456" />
        <property name="maxPoolSize" value="20" />
        <property name="minPoolSize" value="1" />
        <property name="initialPoolSize" value="3" />
        <property name="maxIdleTime" value="15" />
    </bean>

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

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.pwc.dao.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />

    </bean>

</beans>

1. This configuration automatically scans the singletoned Mapper using the proxy method. The bean name of the singletoned Mapper is the first letter of the Mapper interface. The name is lowercase.
2. Be sure to pay attention to the configLocation attribute in the bean of sqlSessionFactory, and its value must remember to add the classpath: prefix, otherwise the MyBatis configuration file cannot be loaded

Step 2 - Integrate the Service layer (Spring)

Business interface and business implementation

UserService.java

package cn.pwc.service;
import java.util.List;
import cn.pwc.pojo.User;

public interface UserService {
    public void add(User user) throws Exception;
    public void delete(User user) throws Exception;
    public User getUserById(int id) throws Exception;
    public List<User> listUserByAge(int age) throws Exception;
}

UserServiceBean.java

package cn.pwc.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.pwc.dao.mapper.UserMapper;
import cn.pwc.pojo.User;
import cn.pwc.service.UserService;


@Service @Transactional
public class UserServiceBean implements UserService{

    @Resource(name="userMapper")
    private UserMapper mapper;

    @Override
    public void add(User user) throws Exception {
        mapper.insert(user);
    }

    @Override
    public void delete(User user) throws Exception {
        mapper.deleteById(user.getId());
    }

    @Override
    public User getUserById(int id) throws Exception {
        User user=null;
        user=mapper.findById(id);
        if(user==null){
            throw new Exception("User is not existed!");
        }
        return user;
    }

    @Override
    public List<User> listUserByAge(int age) throws Exception {
        List<User> list=null;
        list=mapper.findByAge(age);
        if(list==null){
            throw new Exception("List is empty!");
        }
        return list;
    }
}

This instance adopts the method of automatic scanning and loading, so the business bean needs to be annotated with @Service
. This instance is handed over to Spring to manage transactions, so the business bean needs to be annotated with @Transactional

applicationContext-service.xml

    <context:component-scan base-package="cn.pwc.service" />

Step 3 - Add Transaction Management

applicationContext-transaction.xml

    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />

    </bean>

    <tx:annotation-driven transaction-manager="txManager" />

Step 4 - Integrate the View Layer (SpringMVC)

springmvc.xml

    <context:component-scan base-package="cn.pwc.controller"/>

    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

Use the mvc:annotation-driven tag to automatically load the view controller processor resolver, etc.

View Controller (HelloController.java)

package cn.pwc.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.pwc.pojo.User;
import cn.pwc.service.UserService;

@Controller
public class HelloController {

    @Resource(name="userServiceBean")
    private UserService service;

    @RequestMapping("/hello")
    public ModelAndView sayHello(){
        User user=null;
        User user2=null;
        User user3=null;
        try {
            user = service.getUserById(1);
            user2=service.getUserById(1);
            user3=service.getUserById(1);
            System.out.println("OK!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelAndView view=new ModelAndView("hello");
        view.addObject("user", user);
        return view;
    }
}

The Controller class needs to be annotated with @Controller and the
view control method needs to be annotated with @RequestMapping as the url request processing method

Step 5 - Loading All Configurations into the Spring Container

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>

    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

It is important to note that the url-pattern attribute value in servlet-mapping cannot be /*
loaded configuration file path must have classpath: prefix

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326138505&siteId=291194637