基于maven 的SSM入门项目

2 篇文章 0 订阅
2 篇文章 0 订阅

整合思路:
1、spring、springmvc分容器整合:
在xml中配置spring和springmvc的前端控制器
spring、springmvc分别书写配置文件;
spring的配置文件除了controller以外所有的bean均扫描
springmvc 的配置文件配置web相关的试图解析器等且springmvc只扫描controller
2、spring、mybatis整合
mybatis 的数据库(采用C3P0连接池)在spring 的配置文件中配置(ComboPooledDataSource);
mybatis的sqlsessionFactory在spring中配置(sqlsessionFactoryBean)
在spring中配置扫描mapper(dao)接口(MapperScannerConfigurer)
文件结构

一、Maven导入jar包

<dependencies>
		<!-- servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>

		<!-- springmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.2.4.RELEASE</version>
		</dependency>
		<!-- spring jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.2.4.RELEASE</version>
		</dependency>
		<!-- jdbc -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.19</version>
		</dependency>
		<!-- C3P0 -->
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5.5</version>
		</dependency>

		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.4</version>
		</dependency>
		<!-- mybati-spring整合包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.3</version>
		</dependency>

		<!--mybatis-MBG -->
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.4.0</version>
		</dependency>
	</dependencies>

二、利用MBG生成dao、bean
1、在com.test.conf包下书写MBG配置文件mybatis-MBG.xml

/SSM/src/main/resources/com/test/conf/mybatis-MBG.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <!-- targetRuntime="MyBatis3Simple":生成简单版的CRUD
       	 MyBatis3:豪华版 -->
  <context id="DB2Tables" targetRuntime="MyBatis3Simple">
      <!--去除注释  -->
      <commentGenerator>
        <property name="suppressDate" value="true"/>
        <property name="suppressAllComments" value="true" />
    </commentGenerator>
      <!-- jdbcConnection:指定如何连接到目标数据库 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/test?allowMultiQueries=true"
        userId="root"
        password="qaz">
    </jdbcConnection>
    
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
    
    <javaModelGenerator targetPackage="com.test.bean" 
            targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!-- sqlMapGenerator:sql映射文件: -->
    <sqlMapGenerator targetPackage="com.test.dao.mapper"  
        targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- javaClientGenerator:指定mapper接口(dao)所在的位置 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.test.dao"  
        targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!-- 指定要逆向分析哪些表:根据表要创建javaBean -->
    <table tableName="student" domainObjectName="student"></table>
  </context>
</generatorConfiguration>

2、在com.test.test包下书写mbg运行文件
/SSM/src/test/java/com/test/test/mgb.java

package com.test.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class mgb {
            /*
             * 注意这里自动生成的文件不在eclipse中显示,但是在文件夹里面是有文件的;F5刷新包即可
             * */
		public static void main(String[] args) throws Exception {
	        List<String> warnings = new ArrayList<String>();
	        boolean overwrite = true;
	        File configFile = new File("src/main/resources/com/test/conf/mybatis-MBG.xml");
	        ConfigurationParser cp = new ConfigurationParser(warnings);
	        Configuration config = cp.parseConfiguration(configFile);
	        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
	        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
	        myBatisGenerator.generate(null);
	    }
	}

三、配置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">
	<display-name>SSM</display-name>
	<welcome-file-list>
	<!--主页  -->
		<welcome-file>/</welcome-file>
	</welcome-file-list>

<!-- spirng、springmvc分容器整合web.xml配置开始 -->
	<context-param> 
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:com/test/conf/applicationContext-beans.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
<!-- spirng、springmvc分容器整合web.xml配置完-->

	<!--配置springmvc的前端控制器 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:com/test/conf/applicationContext-web.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

四、配置spring
/SSM/src/main/resources/com/test/conf/applicationContext-beans.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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		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-4.3.xsd">

	<!--配置包扫描 -->
	<context:component-scan base-package="com.test">
		<!-- 不扫描controller -->
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- 引入数据库配置信息 -->
	<context:property-placeholder
		location="classpath:com/test/conf/dataSource.properties" />
	<!-- 配置数据库 -->
	<bean id="dataSource"
		class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.Driver}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.user}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
	<!--spring、mybatis整合开始  -->
	<!-- 配置sqlsessionFactory -->
	<bean id="sqlsessionFactory"
		class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation"
			value="classpath:com/test/conf/mybatis-conf.xml" />
		<property name="mapperLocations"
			value="classpath:com/test/dao/mapper/studentMapper.xml" />

	</bean>
	<!-- 配置mapper扫描(dao) -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.test.dao" />
	</bean>
	<!--spring、mybatis整合完  -->
</beans>

五、配置springmvc
/SSM/src/main/resources/com/test/conf/applicationContext-web.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">
	<!--开启全包只扫描controller -->
	<context:component-scan base-package="com.test"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- 配置视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!--开启springmvc注解扫描 -->
	<mvc:annotation-driven />

</beans>

配置mybatis
/SSM/src/main/resources/com/test/conf/mybatis-conf.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>

</configuration>

/SSM/src/main/resources/com/test/conf/dataSource.properties
数据库配置文件

jdbc.Driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.user=root
jdbc.password=qaz

六、编写controller、service层

/SSM/src/main/java/com/test/controller/studentController.java

package com.test.controller;

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

import com.test.bean.student;
import com.test.service.studentService;

@Controller
public class studentController {
	@Autowired
	studentService studentService;
	
	//设置主页
	@RequestMapping("/")
	public String index() {
		return "index";
	}
	
	/*
	 * springmvc的请求参数如果名称一样会自动封装
	 * */
	@RequestMapping(value = "t")
	public ModelAndView show(Integer id) {
		student s = studentService.selectByPrimaryKey(id);
		System.out.println(s);
		ModelAndView m = new ModelAndView();
		if(s!=null) {
			m.addObject("student", s);
		}else {
			m.addObject("student", "Information does not exist");
		}
		m.setViewName("a");
		return m;
		
	}

}

/SSM/src/main/java/com/test/service/studentService.java

package com.test.service;

import com.test.bean.student;

public interface studentService {
	student selectByPrimaryKey(Integer id);
}

/SSM/src/main/java/com/test/service/Impl/studentServiceImpl.java

package com.test.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.test.bean.student;
import com.test.dao.studentMapper;
import com.test.service.studentService;

@Service
public class studentServiceImpl implements studentService{
	@Autowired
	studentMapper studentMapper;
	@Override
	public student selectByPrimaryKey(Integer id) {
		student student = studentMapper.selectByPrimaryKey(id);
		return student;
	}

}


自动生成的bean、mapper、mapper.xml

/SSM/src/main/java/com/test/bean/student.java

package com.test.bean;

public class student {
    @Override
	public String toString() {
		return "student [id=" + id + ", name=" + name + "]";
	}

	private Integer id;

    private String name;

    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 == null ? null : name.trim();
    }
}

/SSM/src/main/java/com/test/dao/studentMapper.java

package com.test.dao;

import com.test.bean.student;
import java.util.List;

public interface studentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(student record);

    student selectByPrimaryKey(Integer id);

    List<student> selectAll();

    int updateByPrimaryKey(student record);
}

/SSM/src/main/java/com/test/dao/mapper/studentMapper.xml

<?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="com.test.dao.studentMapper">
  <resultMap id="BaseResultMap" type="com.test.bean.student">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from student
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.test.bean.student">
    insert into student (id, name)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})
  </insert>
  <update id="updateByPrimaryKey" parameterType="com.test.bean.student">
    update student
    set name = #{name,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select id, name
    from student
    where id = #{id,jdbcType=INTEGER}
  </select>
  <select id="selectAll" resultMap="BaseResultMap">
    select id, name
    from student
  </select>
</mapper>

七、编写jsp
jsp文件位于WEB-INF/jsp文件夹下

/SSM/WebContent/WEB-INF/jsp/index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="t">
		id<input type="text" name="id" id="input"> <input type="submit"
			value="submit">
	</form>
	<script type="text/javascript">
	</script>
</body>
</html>

/SSM/WebContent/WEB-INF/jsp/a.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1 style="color: orange">Result:</h1>
	<%	
	     /* 获取请求参数中的数据 */
		Object s = request.getAttribute("student");
	%>
	<%=s%>
</body>
</html>

八、运行

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值