搭建SSM环境_注解版_基于maven的web项目详解

 

一.基本信息:

数据库

CREATE DATABASE webdemo001;
USE webdemo001;
CREATE TABLE t_student(
  sid INT PRIMARY KEY AUTO_INCREMENT,
  student_name VARCHAR(50),
  age INT
);
INSERT INTO t_student(student_name,age) VALUES('jack',18);
INSERT INTO t_student(student_name,age) VALUES('rose',21);

 

JavaBean

@Table(name = "t_student")
public class Student {
    @Id
    private Integer sid;

    @Column(name = "student_name")
    private String studentName;

    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", studentName='" + studentName + '\'' +
                ", age=" + age +
                '}';
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student() {
    }

    public Student(Integer sid, String studentName, Integer age) {
        this.sid = sid;
        this.studentName = studentName;
        this.age = age;
    }

 

二.maven web项目:注解版

搭建SSM环境_注解版_基于maven的web项目详解_第1张图片

 

1. pom.xml坐标




    
        ssm_all
        com.czxy
        1.0-SNAPSHOT
    
    4.0.0

    web_annotation
    war


    
    
        5.1.32
        1.0.31
        3.4.6
        3.5.3
        1.3.2
        5.1.6.RELEASE
        5.1.2
        2.1
        3.1.0
        1.2
        2.9.8
    

    
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        
        
        
            com.alibaba
            druid
            ${druid.version}
        
        
        
            org.mybatis
            mybatis
            ${mybatis.version}
        
        
            tk.mybatis
            mapper
            ${mapper.version}
        
        
            org.mybatis
            mybatis-spring
            ${mybatis.spring.version}
        
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-aspects
            ${spring.version}
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        
            org.springframework
            spring-test
            ${spring.version}
        
        
        
            com.github.pagehelper
            pagehelper
            ${pagehelper.version}
        
        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        
        
        
            javax.servlet.jsp
            jsp-api
            ${jsp.version}
            provided
        
        
            javax.servlet
            javax.servlet-api
            ${servlet.version}
            provided
        
        
            javax.servlet
            jstl
            ${jstl.version}
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            ${jackson.version}
        
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.5.1
                
                    1.8
                    1.8
                
            
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.2
                
                    8080
                    /
                
            
        
    

 

 

2.​​​​​​​配置类:MyBatis

搭建SSM环境_注解版_基于maven的web项目详解_第2张图片

MyBatisConfiguration .class

package com.czxy.webdemo.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;
import java.util.Properties;

public class MyBatisConfiguration {
	/**
	 * 配置session工厂
	 * @param dataSource
	 * @return
	 * @throws Exception
	 */
	@Bean
	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{
		//1 创建 factoryBean
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		//2 设置数据
		// 2.1 数据源 
		factoryBean.setDataSource(dataSource);
		
		// 2.2 驼峰命名
		Configuration configuration = new Configuration();
		configuration.setMapUnderscoreToCamelCase(true);
		factoryBean.setConfiguration(configuration);
		
		// 2.3 分页插件
		Properties props = new Properties();
		// 设置方言
		props.setProperty("helperDialect", "mysql");
		// 分页的同时进行count查询
		props.setProperty("rowBoundsWithCount", "true");
		// 分页合理化参数,pageNum<=0 时会查询第一页,pageNum>pages (超过总数时),会查询最后一页
		props.setProperty("reasonable", "true");

		PageInterceptor pageInterceptor = new PageInterceptor();
		pageInterceptor.setProperties(props);

		factoryBean.setPlugins(new Interceptor[] {pageInterceptor});
		
		//3 通过factorybean获得对应
		return factoryBean.getObject();
	}
	/**
	 * 映射扫描器
	 * @return
	 */
	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer(){
		//1 创建
		MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
		//2设置包
		mapperScanner.setBasePackage("com.czxy.webdemo.mapper");
		
		return mapperScanner;
	}

}

 

​​​​​​​3.配置类:Spring

搭建SSM环境_注解版_基于maven的web项目详解_第3张图片

 

db.properties 文件中配置数据相关信息

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/webdemo001
jdbc.username=root
jdbc.password=1234

 

SpringConfiguration 配置spring 数据库/事务相关信息

package com.czxy.webdemo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@ComponentScan(basePackages="com.czxy.webdemo.service")
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
public class SpringConfiguration {
	/**
	 * 获得properties文件中内容,并注入对应变量
	 */
	@Value("${jdbc.driver}")
	private String driver;
	
	@Value("${jdbc.url}")
	private String url;
	
	@Value("${jdbc.username}")
	private String username;
	
	@Value("${jdbc.password}")
	private String password;
	/**
	 * 配置数据源
	 * @return
	 */
	@Bean
	public DataSource dataSource(){
		DruidDataSource druidDataSource = new DruidDataSource(); 
		druidDataSource.setDriverClassName(driver);
		druidDataSource.setUrl(url);
		druidDataSource.setUsername(username);
		druidDataSource.setPassword(password);
		return druidDataSource;
	}
	/**
	 * 修复spring4.2bug
	 * @return
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
		return new PropertySourcesPlaceholderConfigurer();
	}
	 */

	/**
	 * 事务管理器
	 * @param dataSource
	 * @return
	 */
	@Bean
	public DataSourceTransactionManager txManager(DataSource dataSource){
		return new DataSourceTransactionManager(dataSource);
	}

}

 

 

 

4.​​​​​​​配置类:Spring MVC

搭建SSM环境_注解版_基于maven的web项目详解_第4张图片

 

package com.czxy.webdemo.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;
import java.util.Properties;

public class MyBatisConfiguration {
	/**
	 * 配置session工厂
	 * @param dataSource
	 * @return
	 * @throws Exception
	 */
	@Bean
	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{
		//1 创建 factoryBean
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		//2 设置数据
		// 2.1 数据源 
		factoryBean.setDataSource(dataSource);
		
		// 2.2 驼峰命名
		Configuration configuration = new Configuration();
		configuration.setMapUnderscoreToCamelCase(true);
		factoryBean.setConfiguration(configuration);
		
		// 2.3 分页插件
		Properties props = new Properties();
		// 设置方言
		props.setProperty("helperDialect", "mysql");
		// 分页的同时进行count查询
		props.setProperty("rowBoundsWithCount", "true");
		// 分页合理化参数,pageNum<=0 时会查询第一页,pageNum>pages (超过总数时),会查询最后一页
		props.setProperty("reasonable", "true");

		PageInterceptor pageInterceptor = new PageInterceptor();
		pageInterceptor.setProperties(props);

		factoryBean.setPlugins(new Interceptor[] {pageInterceptor});
		
		//3 通过factorybean获得对应
		return factoryBean.getObject();
	}
	/**
	 * 映射扫描器
	 * @return
	 */
	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer(){
		//1 创建
		MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
		//2设置包
		mapperScanner.setBasePackage("com.czxy.webdemo.mapper");
		
		return mapperScanner;
	}

}

 

 

5.​​​​​​​配置类:初始化加载类

搭建SSM环境_注解版_基于maven的web项目详解_第5张图片

package com.czxy.webdemo.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		//1 配置spring工厂
		AnnotationConfigWebApplicationContext application = new AnnotationConfigWebApplicationContext();
		// 注册所有的配置类
		application.register(MyBatisConfiguration.class);
		application.register(SpringConfiguration.class);
		application.register(MvcConfiguration.class);
		
		//2 post中文乱码
		FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding", new CharacterEncodingFilter("UTF-8"));
		encodingFilter.addMappingForUrlPatterns(null, true, "/*");
		
		//3 核心控制器
		ServletRegistration.Dynamic mvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(application));
		//mvcServlet.addMapping("*.action");
		mvcServlet.addMapping("/");
		mvcServlet.setLoadOnStartup(2);	//tomcat启动时,执行servlet的初始化方法
		
	}

}

 

 

6.功能:查询所有

搭建SSM环境_注解版_基于maven的web项目详解_第6张图片

步骤一:编写Mapper

@org.apache.ibatis.annotations.Mapper
public interface StudentMapper extends Mapper {
}

 

 

步骤二:编写service

搭建SSM环境_注解版_基于maven的web项目详解_第7张图片

 

接口

public interface StudentService {
    /**
     * 查询所有
     * @return
     */
    List findAll();
}

 

 

实现类

@Service
@Transactional
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper studentMapper;

   
    @Override
    public List findAll() {
        return studentMapper.selectAll();
    }
}

 

 

步骤三:编写controller

controller确定视图的名称

@Controller
@RequestMapping("/student")
public class StudentController {
    @Resource
    private StudentService studentService;

    @GetMapping
    public String findAll(Model model) {
        //查询所有
        List slist = studentService.findAll();
        //存放到作用域
        model.addAttribute("list", slist);
        return "student_list";
    }
}

 

 

编写jsp,显示查询结果

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>



    


 
         
编号 姓名 年龄 操作
${vs.count} ${student.studentName} ${student.age} 修改 删除

 

 

步骤四:首页

搭建SSM环境_注解版_基于maven的web项目详解_第8张图片

 




    
    web巩固案例


    查询所有

 

 

步骤五:启动

搭建SSM环境_注解版_基于maven的web项目详解_第9张图片

浏览器:

搭建SSM环境_注解版_基于maven的web项目详解_第10张图片

 

 

看完恭喜你,又知道了一点点!!!

你知道的越多,不知道的越多! 

~感谢志同道合的你阅读,  你的支持是我学习的最大动力 ! 加油 ,陌生人一起努力,共勉!!

你可能感兴趣的:(SSM,spring,mybatis,mysql,mvc,intellij,idea)