SSM整合

SSM整合

第一步:创建项目,导入jar包

第二步:配置web.xml

首先配置DispatcherServlet,类在spring-webmvc-4.2.1.RELEASE.jar下的org.springframework.web.servlet

再配置CharacterEncodingFilter,类在spring-web-4.2.1.RELEASE.jar下的org.springframework.web.filter

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ssm_1_01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 配置前端拦截器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 配置编码拦截器 -->
  <filter>
    <filter-name>encoding</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>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

第三步:配置springmvc-servlet.xml

首先配置数据库的数据源

dataSource在spring-jdbc-4.2.1.RELEASE.jar的org.springframework.jdbc.datasource的DriverManagerDataSource类

配置spring和mybatis的整合

sqlSessionFactory在mybatis-spring-1.0.0-RC3.jar的org.mybatis.spring.SqlSessionFactoryBean

配置扫描dao 在mybatis-spring-1.0.0-RC3.jar的org.mybatis.spring.mapper.MapperScannerConfigurer

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xmlns:mvc="http://www.springframework.org/schema/mvc"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 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">
      <!-- 开启spring和springmvc的注解 -->       
      <context:component-scan base-package="com.hp"/>
      <mvc:annotation-driven/>
    <!-- 数据库连接数据源 -->
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
     </bean>
     
     <!-- 配置spring和mybatis的整合 -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 引用数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!--自动扫描mapper的配置文件  -->
        <property name="mapperLocations" value="classpath:com/hp/mapper/*.xml"></property>
     </bean>
     <!-- 扫描dao层 并注入spring容器-->
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        <property name="basePackage" value="com.hp.dao"></property>
     </bean>
 </beans> 

实现xml文档提示

bean的xsd文档在spring-beans-4.2.1.RELEASE的org\springframework\beans\factory\xml找到spring-beans-4.2.xsd

context的xsd文档在spring-context-4.2.1.RELEASE的org\springframework\context\config找到spring-context-4.2.xsd

mvc的xsd文档在spring-webmvc-4.2.1.RELEASE的org\springframework\web\servlet\config找到spring-mvc-4.2.xsd

mybatis的mapper的dtd文档在mybatis-3.0.3.jarorg\apache\ibatis\builder\xml找到mybatis-3-mapper.dtd

在windows 的references的找到xml catalog通过add按钮添加

登录实现

第一步:创建数据库和表

create database mydb;
use mydb;
​
create table userinfo(
  uid int primary key auto_increment,
    username VARCHAR(20) not null,
  password VARCHAR(20) not null,
  truename  VARCHAR(20) not null
);
​
INSERT INTO userinfo VALUES(null,'tom','123','张三');
INSERT INTO userinfo VALUES(null,'jack','123','李四');
INSERT INTO userinfo VALUES(null,'mark','123','王五');
​
create table assetinfo(
  aid int primary key auto_increment,
    aname VARCHAR(20) not null,
  model VARCHAR(20) not null,
    price int,
  department  VARCHAR(20) not null,
    producetime date not NULL,
    uid int,
    FOREIGN KEY(uid) REFERENCES userinfo(uid)
);
​
INSERT INTO assetinfo VALUES(null,'设备1','TX01',300,'开发部','2020-09-09',1);
INSERT INTO assetinfo VALUES(null,'设备2','TX01',400,'研发部','2020-09-09',2);
INSERT INTO assetinfo VALUES(null,'设备3','TX01',500,'开发部','2020-09-09',3);
​

第二步:创建bean对象

public class Userinfo {
    private Integer uid;
    private String username;
    private String password;
    private String truename;
    //省略get和set方法
}
public class Assetinfo {
    private Integer aid;
    private String aname;
    private String model;
    private Integer price;
    private String department;
    private String producetime;
    private Userinfo userinfo;
     //省略get和set方法
}

第三步:创建dao层和mapper配置文件

import com.hp.bean.Userinfo;
​
public interface AssinfoDao {
    public Userinfo login(Userinfo userinfo);
}
<?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.hp.dao.AssinfoDao">
    <!-- 登录sql -->
    <select id="login" parameterType="com.hp.bean.Userinfo" resultType="com.hp.bean.Userinfo">
        select * from userinfo where username = #{username} and password = #{password}
    </select>
</mapper>

第四步:创建service层和实现类

import com.hp.bean.Userinfo;
​
public interface AssetinfoService {
    public Userinfo login(Userinfo userinfo);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
​
import com.hp.bean.Userinfo;
import com.hp.dao.AssetinfoDao;
import com.hp.service.AssetinfoService;
​
@Service
public class AssetinfoServiceImpl implements AssetinfoService{
    @Autowired
    private AssetinfoDao assetinfoDao;
    
    public Userinfo login(Userinfo userinfo) {
        
        return assetinfoDao.login(userinfo);
    }
​
}
​

第五步:创建controller控制器

package com.hp.controller;

import javax.servlet.http.HttpSession;

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

import com.hp.bean.Userinfo;
import com.hp.service.AssetinfoService;

@Controller
@Scope("prototype")//配置控制器为多例模式
public class AssetinfoController {
	@Autowired
	private AssetinfoService assetinfoService;
	
	/**
	 * 登录功能
	 * @return
	 */
	@RequestMapping("/login")
	public ModelAndView login(Userinfo userinfo, HttpSession session){
		ModelAndView mv = new ModelAndView();
		Userinfo user = assetinfoService.login(userinfo);
		//判断是否成功
		if (null != user) {
			//保存登录信息
			session.setAttribute("userinfo", user);
			mv.setViewName("list");
		}else {
			mv.setViewName("index.jsp");
		}
		return mv;
	}
	
	/**
	 * 列表功能
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(){
		ModelAndView mv = new ModelAndView("list.jsp");
		return mv;
	}
}

第六步:创建登录页面:

<%@ 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">
<title>Insert title here</title>
</head>
<body>
	<form action="login" method="post">
		用户名:<input type="text" name="username"><br>
		密码:<input type="password" name="password"><br>
		<input type="submit" value="登录">
	</form>
</body>
</html>

列表实现

第一步:在AssetinfoDao接口添加查询所有的方法findAll,在AssetinfoMapper添加对应sql

import java.util.List;

import com.hp.bean.Assetinfo;
import com.hp.bean.Userinfo;

public interface AssetinfoDao {
	//登录功能
	public Userinfo login(Userinfo userinfo);
	//查询列表
	public List<Assetinfo> findAll();
}
<?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.hp.dao.AssetinfoDao">
	<!-- 创建resultMap -->
	<resultMap type="com.hp.bean.Assetinfo" id="baseMap">
		<id column="aid" property="aid"/>
		<result column="aname" property="aname"/>
		<result column="model" property="model"/>
		<result column="price" property="price"/>
		<result column="department" property="department"/>
		<result column="producetime" property="producetime"/>
		<!-- 配置一对一关系 -->
		<association property="userinfo" javaType="com.hp.bean.Userinfo" column="uid">
			<id column="uid" property="uid"/>
			<result column="truename" property="truename"/>
		</association>
	</resultMap>
	<!-- 登录sql -->
	<select id="login" parameterType="com.hp.bean.Userinfo" resultType="com.hp.bean.Userinfo">
		select * from userinfo where username = #{username} and password = #{password}
	</select>
	<!-- 查询所有sql -->
	<select id="findAll" resultMap="baseMap">
		select * from assetinfo a, userinfo u where a.uid = u.uid
	</select>
</mapper>

第二步:在AssetinfoService中添加findALl方法并在实现类中调用dao的findAll方法

import java.util.List;

import com.hp.bean.Assetinfo;
import com.hp.bean.Userinfo;

public interface AssetinfoService {
	//登录功能
	public Userinfo login(Userinfo userinfo);
	//查询列表
	public List<Assetinfo> findAll();
}
import java.util.List;

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

import com.hp.bean.Assetinfo;
import com.hp.bean.Userinfo;
import com.hp.dao.AssetinfoDao;
import com.hp.service.AssetinfoService;

@Service
public class AssetinfoServiceImpl implements AssetinfoService{
	@Autowired
	private AssetinfoDao assetinfoDao;
	
	public Userinfo login(Userinfo userinfo) {
		return assetinfoDao.login(userinfo);
	}

	@Override
	public List<Assetinfo> findAll() {
		return assetinfoDao.findAll();
	}

}

第三步:在AssetinfoController在查询所有的方法list中实现

@Controller @Scope("prototype")//配置控制器为多例模式 public class AssetinfoController { @Autowired private AssetinfoService assetinfoService;

/**
 * 登录功能
 * @return
 */
@RequestMapping("/login")
public ModelAndView login(Userinfo userinfo, HttpSession session){
	ModelAndView mv = new ModelAndView();
	Userinfo user = assetinfoService.login(userinfo);
	//判断是否成功
	if (null != user) {
		//保存登录信息
		session.setAttribute("userinfo", user);
		mv.setViewName("list");
	}else {
		mv.setViewName("index.jsp");
	}
	return mv;
}

/**
 * 列表功能
 * @return
 */
@RequestMapping("/list")
public ModelAndView list(){
	ModelAndView mv = new ModelAndView("list.jsp");
	//查询所有列表
	List<Assetinfo> list = assetinfoService.findAll();
	//向页面传值
	mv.addObject("list", list);
	return mv;
}

}

第四步:页面布局

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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">
<title>Insert title here</title>
<style type="text/css">
	table{
		background: gray;
		margin: 50px auto;
		width: 60%;
	}
	th,td{
		background: white;
		padding: 4px;
	}
</style>
</head>
<body>
	<table>
		<tr>
			<td colspan="7">
				<a href="">新增</a>
			</td>
		</tr>
		<tr>
			<th>设备名称</th>
			<th>设备型号</th>
			<th>设备价格</th>
			<th>使用部门</th>
			<th>生产日期</th>
			<th>登记人</th>
			<th>操作</th>
		</tr>
		<c:forEach items="${list }" var="asset">
			<tr align="center">
				<td>${asset.aname }</td>
				<td>${asset.model }</td>
				<td>${asset.price }</td>
				<td>${asset.department }</td>
				<td>${asset.producetime }</td>
				<td>${asset.userinfo.truename }</td>
				<td>
					<a href="">修改</a>
					<a href="">删除</a>
				</td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>

添加实现

第一步:在AssetinfoDao接口添加查询所有的方法findAll,在AssetinfoMapper添加对应sql

	//添加方法
	public int add(Assetinfo assetinfo);
<!-- 添加sql -->
	<insert id="add" parameterType="com.hp.bean.Assetinfo">
		insert into assetinfo values(null,#{aname},#{model},#{price},#{department},#{producetime},#{userinfo.uid})
	</insert>

第二步:在AssetinfoService中添加findALl方法并在实现类中调用dao的findAll方法

	//添加方法
	public int add(Assetinfo assetinfo);
	@Override
	public int add(Assetinfo assetinfo) {
		return assetinfoDao.add(assetinfo);
	}

第三步:在AssetinfoController在查询所有的方法list中实现

/**
	 * 添加功能
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add(Assetinfo assetinfo, HttpSession session){
		ModelAndView mv = new ModelAndView();
		//获取登录人信息
		Userinfo userinfo = (Userinfo) session.getAttribute("userinfo");
		//保存到assetinfo对象里面
		assetinfo.setUserinfo(userinfo);
		//执行添加
		int i = assetinfoService.add(assetinfo);
		if (i > 0) {
			mv.setViewName("list");
		}else {
			mv.setViewName("add.jsp");
		}
		return mv;
	}

第四步:页面布局

<%@ 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">
<title>Insert title here</title>
</head>
<body>
	<form action="add" method="post">
		设备名称:<input type="text" name="aname"><br>
		设备类型:<input type="text" name="model"><br>
		设备价格:<input type="text" name="price"><br>
		使用部门:<input type="text" name="department"><br>
		生产日期:<input type="text" name="producetime"><br>
		<input type="submit" value="添加">
	</form>
</body>
</html>

修改实现

第一步:在AssetinfoDao接口添加方法findById和update,在AssetinfoMapper添加对应sql

//根据ID查询设备
	public Assetinfo findById(Integer aid);
	//修改功能
	public int update(Assetinfo assetinfo);
<!-- 根据ID查询设备sql -->
	<select id="findById" resultType="com.hp.bean.Assetinfo">
		select * from assetinfo where aid = #{aid}
	</select>
	<!-- 修改sql -->
	<update id="update" parameterType="com.hp.bean.Assetinfo">
		update assetinfo set
		aname = #{aname},
		model = #{model},
		price = #{price},
		department = #{department},
		producetime = #{producetime}
		where aid = #{aid}
	</update>

第二步:在AssetinfoService中添加方法findById和update并在实现类中调用dao的方法

//根据ID查询设备
	public Assetinfo findById(Integer aid);
	//修改功能
	public int update(Assetinfo assetinfo);
@Override
	public Assetinfo findById(Integer aid) {
		// TODO Auto-generated method stub
		return assetinfoDao.findById(aid);
	}

	@Override
	public int update(Assetinfo assetinfo) {
		// TODO Auto-generated method stub
		return assetinfoDao.update(assetinfo);
	}

第三步:在AssetinfoController在查询所有的方法findById和update中实现

/**
	 * 根据ID查询设备
	 * @param aid
	 * @return
	 */
	@RequestMapping("/findById")
	public ModelAndView findById(Integer aid){
		ModelAndView mv = new ModelAndView("update.jsp");
		//根据ID查询设备详情
		Assetinfo assetinfo = assetinfoService.findById(aid);
		//将数据传到修改页面
		mv.addObject("assetinfo", assetinfo);
		return mv;
	}
	/**
	 * 修改设备
	 * @param aid
	 * @return
	 */
	@RequestMapping("/update")
	public ModelAndView update(Assetinfo assetinfo){
		ModelAndView mv = new ModelAndView("list");
		//修改数据
		int i = assetinfoService.update(assetinfo);
		return mv;
	}

第四步:页面布局


删除实现

第一步:在AssetinfoDao接口添加删除方法delete,在AssetinfoMapper添加对应sql

//删除功能
	public int delete(Integer aid);
<!-- 删除sql -->
	<delete id="delete">
		delete from assetinfo where aid = #{aid}
	</delete>

第二步:在AssetinfoService中添加删除方法delete并在实现类中调用dao的findAll方法

//删除功能
	public int delete(Integer aid);
@Override
	public int delete(Integer aid) {
		// TODO Auto-generated method stub
		return assetinfoDao.delete(aid);
	}

第三步:在AssetinfoController在删除方法delete中实现

/**
	 * 删除设备
	 * @param aid
	 * @return
	 */
	@RequestMapping("/delete")
	public ModelAndView delete(Integer aid){
		ModelAndView mv = new ModelAndView("list");
		//删除数据
		assetinfoService.delete(aid);
		return mv;
	}

第四步:页面布局

	<td>
					<a href="findById?aid=${asset.aid }">修改</a>
					<a href="delete?aid=${asset.aid }" οnclick="return confirm('确定删除该数据?')">删除</a>
				</td>
上一篇:leetcode每日一题1405. 最长快乐字符串 快乐么 或许今天的你并不快乐 贪心 + 优先队列


下一篇:小程序项目:基于微信小程序的竞赛管理系统ssm框架