如何搭建SSM(SpringMvc+mybatis+Spring)java web工程

本文详细介绍了一个基于Spring、MyBatis、SpringMVC框架的Web应用搭建过程,包括开发环境配置、项目结构设置、框架集成及配置文件编写,并通过具体示例展示了如何实现基本的CRUD操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

No.1   首先将web工程结构建好

1.1.1 开发环境介绍

 在这里我是采用的是mysql数据库 

  编译器版本采用的是jdk使用的是1.8

 开发工具是使用的是eclipse Mars版本

  web容器采用的是tomcat 版本是7.0版本 


  在这里我将我自己写好的Demo工程目录结构截图展示出来方便大家新建项目


这张图图片清晰地将我的工程清晰地展示出来,先简单介绍下吧 ,项目主包是以com.cntv开始的 。在之下又分为好几个子包,分别是mapper、controller、service、dao、mapper、logs、config、base、entity、test包,其中controller包是负责接收前台请求执行部分业务逻辑的action,熟悉struts框架的应该知道Action哈 在这里我就不详细说了。mapper包主要是负责mybatis框架实体映射,config包是主要存储项目配置文件。  其他的包就不一一介绍了,都是些常规的包。


NO.2  准备好相应的jar包

这里我是采用Spring是.2.0版本 mybatis是3.3.0版本的


图中框选的jar包是一些依赖性jar包   不要以为这就是完整的jar包   还有呢....

到此为止 jar包已准备完毕  现在就来开始准备框架的相关的配置了  首先是Spring+mybatis关联的配置

NO.3 配置框架相关功能的配置文件

在src目录中config文件夹中新建spring-mybatis.xml文件 ,通过这个文件集成并关联Spring+mybatis框架

<span style="font-size: 14px;"><</span><span style="font-size:18px;">?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:p="http://www.springframework.org/schema/p"
	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-3.1.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<span style="color:#ff0000;"><!-- 自动扫描 --></span>
	<context:component-scan base-package="com.cntv" />
	<span style="color:#ff0000;"><!-- 引入配置文件 --></span>
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<span style="color:#ff0000;"><!-- 初始化连接大小 --></span>
		<property name="initialSize" value="${initialSize}"></property>
		<span style="color:#ff0000;"><!-- 连接池最大数量 --></span>
		<property name="maxActive" value="${maxActive}"></property>
		<span style="color:#ff0000;"><!-- 连接池最大空闲 --></span>
		<property name="maxIdle" value="${maxIdle}"></property>
		<span style="color:#ff0000;"><!-- 连接池最小空闲 --></span>
		<property name="minIdle" value="${minIdle}"></property>
		<span style="color:#ff0000;"><!-- 获取连接最大等待时间 --></span>
		<property name="maxWait" value="${maxWait}"></property>
	</bean>

	<span style="color:#ff0000;"><!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --></span>
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<span style="color:#ff0000;"><!-- 自动扫描mapping.xml文件 --></span>
		<property name="mapperLocations" value="classpath:com/cntv/mapper/*.xml"></property>
	</bean>

	<span style="color:#ff0000;"><!-- DAO接口所在包名,Spring会自动查找其下的类 --></span>
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.cn.hnust.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>

	<span style="color:#ff0000;"><!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --></span>
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

</beans></span>



紧接着在src下config包下新建jdbc.properties文化  把数据库的配置放在这个配置文件里面

<span style="font-size:18px;">driver=com.mysql.jdbc.Driver
url=jdbc:mysql://125.221.225.113:3306/<span style="color:#ff0000;">db_zsl</span>
username=demao
password=demao
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000</span>

说明:第一行是加载jdbc驱动地址 

第二行是连接数据库 加红色字体是数据库名字  前面是Ip地址+mysql数据库端口号

userName是数据库连接用户名

password是连接数据库密码


接下来配置SpringMvc相关的配置 

还是跟之前一样,在src目录下的config文件夹中新建spring-mvc.xml配置文件 

 这个文件主要是负责Mvc架构视图,前后台数据交互等。

<span style="font-size:18px;"><span style="font-size:18px;"><?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:p="http://www.springframework.org/schema/p"
 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-3.1.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.1.xsd  
    http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<span style="color:#ff0000;"><!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --></span>
	<context:component-scan base-package="com.cntv.controller" />
	<span style="color:#ff0000;"><!--避免IE执行AJAX时,返回JSON出现下载文件 --></span>
	<bean id="mappingJacksonHttpMessageConverter"
	
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
	</bean>
	<span style="color:#ff0000;"><!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --></span>
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" ></ref><span style="color:#ff0000;">	<!-- JSON转换器 --></span>
			</list>
		</property>
	</bean> 
	<span style="color:#ff0000;"><!-- 定义跳转的文件的前后缀 ,视图模式配置--></span>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<span style="color:#ff0000;"><!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --></span>
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<span style="color:#ff0000;"><!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --></span>
	  <!--  <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        默认编码
        <property name="defaultEncoding" value="utf-8" />  
        文件大小最大值
        <property name="maxUploadSize" value="10485760000" />  
        内存中的最大值
        <property name="maxInMemorySize" value="40960" />  
    </bean> -->
</beans></span></span>

最后配置web.xml文件

项目总配置文件将spring-mybatis.xml和spring-mvc.xml集成到web.xml里面

<span style="font-size:18px;"><?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"
	version="3.0">
	<display-name>Archetype Created Web Application</display-name>
	<span style="color:#ff0000;"><!-- Spring和mybatis的配置文件 --></span>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mybatis.xml</param-value>
	</context-param>
	<span style="color:#ff0000;"><!-- 编码过滤器 --></span>
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/</url-pattern>
	</filter-mapping>
	<span style="color:#ff0000;"><!-- Spring监听器 --></span>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<span style="color:#ff0000;"><!-- 防止Spring内存溢出监听器 --></span>
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	<!-- Spring MVC servlet -->
	<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:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<span style="color:#ff0000;"><!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --></span>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>
	<span style="color:#ff0000;"><!-- 配置SESSION超时,单位是分钟 --></span>
	<session-config>
		<session-timeout>15</session-timeout>
	</session-config>

</web-app></span>


NO.4 收官完成 测试框架能否正常运行

直到这里我们已经把框架配置好了现在我们就要写一些实在的东西了 把接口和service定一下

4.1.1  定义一个接口 

在dao包下新建IUserDao.java类
<span style="font-size:18px;"><span style="font-size:18px;">package com.cntv.dao;

import org.springframework.stereotype.Repository;

import com.cntv.entity.User;
@Repository
public interface IUserDao {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}</span></span>

4.1.2 定义一个service接口

 同样的在service包下新建IUserService.java类
<span style="font-size:18px;"><span style="font-size:18px;">package com.cntv.service;

import com.cntv.entity.User;

public interface IUserService {
	public User getUserById(int userId);
}</span><span style="font-size:14px;">
</span></span>

4.1.3定义一个javaBean

<span style="font-size:18px;"><span style="font-size:18px;">package com.cntv.entity;
public class User {
    private Integer id;

    private String userName;

    private String password;

    private Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
    
}</span></span>

4.1.4 定义一个mapper.xml实体映射 

很简单,在mapper文件夹下新建UserMapper.xml配置文件
<span style="font-size:18px;"><span style="font-size:18px;"><?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.cntv.dao.IUserDao" >
  <resultMap id="BaseResultMap" type="com.cntv.entity.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, user_name, password, age
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user_t
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user_t
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.cntv.entity.User" >
    insert into user_t (id, user_name, password, 
      age)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.cntv.entity.User" >
    insert into user_t
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="age != null" >
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.cntv.entity.User" >
    update user_t
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.cntv.entity.User" >
    update user_t
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper></span></span>
这个文件就包含CRUD操作 sql语句在标签中都有定义 ,需要注意的是这里面sql语句用到的一些参数全部是从dao层获取的
mapper文件是映射数据库表对应的javaBean实体 mapper中可以写sql语句 很方便。


4.1.5 定义一个service实现类

在service包下serviceImpl包下新建UserServiceImpl类
<span style="font-size:18px;"><span style="font-size:18px;">package com.cntv.service.serviceImpl;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import com.cntv.dao.IUserDao;
import com.cntv.entity.User;
import com.cntv.service.IUserService;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@Service
public class UserServiceImpl implements IUserService {
	@Resource
	private IUserDao userDao;
	@Override
	public User getUserById(int userId) {
		// TODO Auto-generated method stub
		return this.userDao.selectByPrimaryKey(userId);
	}
   public static void main(String[] args) {
	   ApplicationContext ca= new ClassPathXmlApplicationContext("spring-mybatis.xml");
	   UserServiceImpl u=(UserServiceImpl) ca.getBean("userServiceImpl");
	  User ue= u.getUserById(12);
	   System.out.println("用户名:"+ue.getUserName());
<span>	</span>   System.out.println("用户密码:"+ue.getPassword());
}
public IUserDao getUserDao() {
	return userDao;
}
public void setUserDao(IUserDao userDao) {
	this.userDao = userDao;
}
   
}</span><span style="font-size:14px;">
</span></span>

4.1.6 定义一个controller

在src目录下的controller包下新建一个controller,在这里我新建的是UserController.java
<span style="font-size:18px;"><span style="font-size:18px;">package com.cntv.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.coyote.Request;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cntv.entity.User;
import com.cntv.service.serviceImpl.UserServiceImpl;

@Controller
public class UserController {
	@Resource
	private UserServiceImpl userService;
	@RequestMapping("test.do")
	public ModelAndView  testCon(HttpServletRequest request,Model model){
		System.out.println("hello");
		System.out.println(request.getParameter("id"));
		User u=userService.getUserById(new Integer(request.getParameter("id")));
		System.out.println(u.getUserName());
		ModelAndView mod=new ModelAndView();
		mod.setViewName("success");
		return mod;
	}
	/**
	 * @deprecated
	 * 根据前台封装的javaBean属性进行封装  这里是进行User对象的封装
	 * 测试后台是否能正常能拿到数据       
	 * @param user 获取前台穿过来的对象
	 * @param request
	 * @return
	 */
	@RequestMapping("submit.do")
	public String testBean(User user,HttpServletRequest request){
		System.out.println("========+"+user.getUserName()+"..."+user.getPassword());
		return "success";
		
	}
	public UserServiceImpl getUserService() {
		return userService;
	}
	public void setUserService(UserServiceImpl userService) {
		this.userService = userService;
	}
	
}</span><span style="font-size:14px;">
</span></span>


Ok!!!现在就来测试下吧后台数据库和service层到底能不能打通吧  



再来对照下数据库中数据吧!!


 经过测试持久层和业务层是能互通的 测试通过!!!!

  

啦啦啦!  现在测试前后台数据能不能互通了  ....


前端新建一个jsp测试页面  测试请求和数据能不能到达后台controller里面
在这里我新建的是eg.jsp

<span style="font-size:18px;"><span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="js/jquery-1.7.js"></script>
<title>Insert title here</title>
</head>
<body>
<input id="inp" type="hidden" maxlength="20">
<h2>Test formMait</h2>
<form action="submit.do" method="post" >
账户<input type="text" name="userName"><br>
密码<input type="text" name="password"><br>
<button>提交</button>

</form>
<script type="text/javascript">
 $(function(){
	// alert("json hello");
	 
 })
 function clicBt(){
	 console.log("hello friends!!!")
	 $.ajax({
		   type: "POST",
		   url: "test.do?id="+$("#inp").val(),
		   data: "name=John&location=Boston",
		   success: function(msg){
		     alert("china is hello  and you are okau!");
		   }
		});
	 
	 
 }
</script>
</body>
</html></span></span>

重点来了!!!测试前台数据和请求能不能到达后台

>>>>>>输入 http://127.0.0.1:8080/SpringMybat/eg.jsp 进入测试页面 

到后台来看看控制台有什么反应木有??



哈哈哈  前台输入的账号密码成功到达后台controlLee并打印出来了!

测试圆满成功!!!


现在我们就可以根据业务需求来做我们自己想做的事情了,后台框架搭建完成了,如果需要其他相关配置可以查阅其他资料完成配置。



项目全部jar包下载地址是:http://download.csdn.net/detail/jason763/9646274 下载这个文件就可以了   按照我说的配置就可以用了。

项目源码地址为:http://download.csdn.net/detail/jason763/9646304 如有需要可以下载源码。

注:本博文为博主原创,未经允许不得转载。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值