• 1.SSM整合_单表的增删改查


    1. 目标:增删改查
    2. 环境:Maven+Eclipse+Tomcat7+JDK7
    3. 思维导图:
      在这里插入图片描述
    4. 表结构
      在这里插入图片描述
    5. 目录结构
      在这里插入图片描述在这里插入图片描述在这里插入图片描述
    6. 依赖
     <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <!-- SpringMVC -->
        <!-- 1)核心组件 -->
        <dependency>
        	<groupId>org.springframework</groupId>
    		<artifactId>spring-core</artifactId>
    		<version>4.3.10.RELEASE</version>    	
        </dependency>    
        <dependency>
        	<groupId>org.springframework</groupId>
    		<artifactId>spring-context</artifactId>
    		<version>4.3.10.RELEASE</version>    	
        </dependency>
        <dependency>
        	<groupId>org.springframework</groupId>
    		<artifactId>spring-beans</artifactId>
    		<version>4.3.10.RELEASE</version>    	
        </dependency>
        
        <!-- spring dao层组件 -->
       	<dependency>
       		<groupId>org.springframework</groupId>
       		<artifactId>spring-jdbc</artifactId>
       		<version>4.3.10.RELEASE</version>
       	</dependency>
       	<dependency>
       		<groupId>org.springframework</groupId>
       		<artifactId>spring-tx</artifactId>
       		<version>4.3.10.RELEASE</version>
       	</dependency>
        <!-- spring web组件  -->
       	<dependency>
       		<groupId>org.springframework</groupId>
       		<artifactId>spring-web</artifactId>
       		<version>4.3.10.RELEASE</version>
       	</dependency>
       	<dependency>
       		<groupId>org.springframework</groupId>
       		<artifactId>spring-webmvc</artifactId>
       		<version>4.3.10.RELEASE</version>
       	</dependency>
    
        <!-- mybatis和spring整合的依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- 数据库连接池 和驱动-->
        <dependency>
    	    <groupId>c3p0</groupId>
    	    <artifactId>c3p0</artifactId>
    	    <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.43</version>
        </dependency>
    
        <!-- jstl servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
    	    <groupId>taglibs</groupId>
    	    <artifactId>standard</artifactId>
    	    <version>1.1.2</version>
    	</dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    
        <!-- spring单元测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.10.RELEASE</version>
            <scope>test</scope>
        </dependency>
    
    	<!-- JSON包 -->
    	<dependency>
    	    <groupId>net.sf.json-lib</groupId>
    	    <artifactId>json-lib</artifactId>
    	    <version>2.4</version>
    	    <classifier>jdk15</classifier>
    	</dependency>
      </dependencies>
    

    页面上引入了Bootstrap,只是简单的使用的一下,复杂的我并不太会。下载的Bootstrap的包直接复制到webapp目录下就行,除此之外还有JQuery的包。
    在这里插入图片描述

    1. 实体类
    public class User {
    	private int id;
    	private String userName;
    	private String age;
    	//省略getter和setter
    	...
    }
    
    1. 接口和映射文件
    接口:
    public interface UserMapper {
    
    	public void addUser(User user);
    	
    	public void deleteUser(String name);
    	
    	public void updateUser(User user);
    	
    	public User getUser(String name);
    	
    	public List<User> getUser2(String name);
    
    	public List<User> getAllUser();
    }
    映射文件:
    <!-- namespace的属性值命名规则:文件所在的包路径+文件名 -->
    <mapper namespace="com.demo.mapper.UserMapper">
    	<!-- 添加 -->
    	<select id="addUser" parameterType="User">
    		insert into t_user(t_id,t_name,t_age) value(#{id},#{userName},#{age})
    	</select>
    	
    	<!-- 删除 -->
    	<delete id="deleteUser" parameterType="String">
    		delete from t_user where t_name = #{name}
    	</delete>
    	
    	<!-- 修改 -->
    	<update id="updateUser" parameterType="User">
    		update t_user set t_name = #{userName}, t_age = #{age} where t_id = #{id}
    	</update>
    	
    	<!-- 查找 -->
    	<select id="getUser" parameterType="String" resultType="User">
    		select t_id id, t_name userName, t_age age from t_user where t_name = #{id}
    	</select>
    	
    	<!-- 模糊查询 -->
    	<select id="getUser2" parameterType="String" resultType="User">
    		select t_id id, t_name userName, t_age age from t_user where t_name like "%"#{name}"%"
    	</select>
    	
    	<!-- 查找所有 -->
    	<select id="getAllUser" resultType="User">
    		select t_id id, t_name userName, t_age age from t_user
    	</select>
    	
    </mapper>
    
    1. service和其实现类
    service层:
    public interface IUserService {
    
    	public void addUser(User user);
    	
    	public void delectUser(String name);
    	
    	public void updateUser(User user);
    	
    	public User getUser(String name);
    
    	public List<User> getUser2(String name);
    	
    	public List<User> getAll();
    	
    }
    实现类:
    @Service
    @Transactional
    public class UserServiceImp implements IUserService{
    
    	@Resource  
    	private UserMapper mapper;
    	
    	@Override
    	public void addUser(User user) {
    		mapper.addUser(user);
    	}
    
    	@Override
    	public void delectUser(String name) {
    		mapper.deleteUser(name);
    	}
    
    	@Override
    	public void updateUser(User user) {
    		mapper.updateUser(user);
    	}
    
    	@Override
    	public User getUser(String name) {
    		return mapper.getUser(name);
    	}
    
    	@Override
    	public List<User> getAll() {
    		return mapper.getAllUser();
    	}
    
    	@Override
    	public List<User> getUser2(String name) {
    		return mapper.getUser2(name);
    	}
    
    }
    
    1. controller
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
    	@Autowired
    	private IUserService userService;
    	
    	/**
    	 * 跳转到添加页面
    	 * @return
    	 */
    	@RequestMapping("/toAddUser")
    	public String toAddUser(){
    		return "adduser";
    	}
    	
    	/**
    	 * 添加用户
    	 */
    	@RequestMapping("/addUser")
    	public String addUser(User user,Model model){
    		userService.addUser(user);
    		return "redirect:/user/getAll";
    	}
    	
    	/**
    	 * 删除用户
    	 */
    	@RequestMapping("/deleteUser")
    	public String deleteUser(String name){
    		userService.delectUser(name);
    		return "redirect:/user/getAll";
    	}
    	
    	/**
    	 * 跳转到修改页面,修改页面和新增页面共用一个JSP
    	 * @param name
    	 * @param request
    	 * @return
    	 */
    	@RequestMapping("/toUpdateUser")
    	public String toUpdateUser(String name, HttpServletRequest request){
    		User user = userService.getUser(name);
    		request.setAttribute("user", user);
    		return "adduser";
    	}
    	/**
    	 * 修改用户:forward可以传参数,redirect不能传参数
    	 */
    	@RequestMapping("/updateUser")
    	public String updateUser(User user,HttpServletRequest request){
    		userService.updateUser(user);
    		return "redirect:/user/getAll";
    	}
    	
    	/**
    	 * 查询
    	 */
    	@RequestMapping("/getUser")
    	public String getUser(String name, HttpServletRequest request){
    		User user = userService.getUser(name);
    		request.setAttribute("user", user);
    		return "/userlist";
    	}
    	
    	/**
    	 * 模糊查询
    	 * @param name
    	 * @return
    	 */
    	@RequestMapping("/getUser2")
    	public String getUser2(String name, HttpServletRequest request){
    		List list = userService.getUser2(name);
    		request.setAttribute("userList", list);
    		return "/userlist";
    	}
    	
    	/**
    	 * 获取所有的用户
    	 */
    	@RequestMapping("/getAll")
    	public String getAll(HttpServletRequest request){
    		List<User> userList = userService.getAll();
    		request.setAttribute("userList", userList);
    		return "/userlist";
    	}
    	
    }
    
    
    1. 配置文件_web.xml
    web.xml
    <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">
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath:spring.xml</param-value>
    	</context-param>
    	<!--2.加载spring的配置文件 -->
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    
    	<!--1. 加载springmvc的配置文件 -->
    	<servlet>
    		<servlet-name>springDispatcherServlet</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>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>springDispatcherServlet</servlet-name>
    		<url-pattern>/</url-pattern>
    	</servlet-mapping>
    
    	<!-- 3.编码方式 -->
    	<filter>
    		<filter-name>CharacterEncoding</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>CharacterEncoding</filter-name>
    		<url-pattern>/*</url-pattern>	
    	</filter-mapping>
    	<welcome-file-list>
    		<welcome-file>index.jsp</welcome-file>
    	</welcome-file-list>
    </web-app>
    
    1. spring配置文件
    	<!-- 1.扫描Service包 -->
    	<context:component-scan base-package="com.demo.service"></context:component-scan>
    	<context:component-scan base-package="com.demo1.service"></context:component-scan>
    
    	<!-- 2.引用数据库配置文件  -->
    	<context:property-placeholder location="classpath:jdbc.properties"/>
    
    	<!-- 3.数据库连接池 -->
    	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    		<property name="user" value="${jdbc.username}"></property>
    		<property name="password" value="${jdbc.password}"></property>
    		<property name="driverClass" value="${jdbc.driverClass}"></property>
    		<property name="jdbcUrl" value="${jdbc.url}"></property>
    	</bean>
    
    	<!-- 4.Spring 和 Mybatis整合 -->
    	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<!-- 注入数据源 -->
    		<property name="dataSource" ref="dataSource"></property>
    		<!-- 加载mybatis的全局文件 -->
    		<property name="configLocation" value="classpath:mybatis-cfg.xml"></property>
    		<!-- 扫描mybatis的映射文件,此处可以不配置,但是需要在Mybatis的全局配置文件中配置<mappers>标签,二选一
    			   一个目录:classpath:com/demo/mapper/*.xml,多个目录:classpath*:com/demo*/mapper/*.xml
    		 -->
    		<property name="mapperLocations" value="classpath*:com/demo*/mapper/*.xml"></property>
    		<!-- 配置别名,多个包之间用逗号或分号隔开 -->
    		<property name="typeAliasesPackage" value="com.demo.model;com.demo1.model"></property>		
    	</bean>
    	
    	<!-- 5.mybatis自动扫描加载SQL映射文件/接口:MapperScannerConfigurer sqlSessionFactory,
    		   basePackage: 指定SQL映射文件/接口所在的包(自动扫描)
    	-->
    	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    		<!-- 扫描接口 ,扫描多个接口使用逗号隔开-->
    		<property name="basePackage" value="com.demo.mapper,com.demo1.mapper"></property>
    		<property name="sqlSessionFactoryBeanName" value="sqlSession"></property>
    	</bean>
    	
    	<!-- 6.事务管理 DataSourceTransactionManager dataSource:引用数据源-->
    	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<property name="dataSource" ref="dataSource"></property>
    	</bean>
    	
    	<!-- 7.声明式事务 -->
    	<tx:annotation-driven transaction-manager="txManager"/>
    
    1. springmvc配置文件
    	<!-- 扫描Controller层 -->
    	<context:component-scan base-package="com.demo.controller"></context:component-scan>
    	<context:component-scan base-package="com.demo1.controller"></context:component-scan>
    
    	<!-- 会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,
    		HandlerMapping的实现类的作用:
    		实现类RequestMappingHandlerMapping,它会处理@RequestMapping 注解,并将其注册到请求映射表中。
    		HandlerAdapter的实现类的作用:
    		实现类RequestMappingHandlerAdapter,则是处理请求的适配器,确定调用哪个类的哪个方法,并且构造方法参数,返回值。
    		当配置了mvc:annotation-driven/后,Spring就知道了我们启用注解驱动。然后Spring通过context:component-scan/标签的配置,
    		会自动为我们将扫描到的@Component,@Controller,@Service,@Repository等注解标记的组件注册到工厂中,来处理我们的请求。
    	 	如果不配置该标签则,spring默认注册这两个Bean,但是如果为了不拦截静态资源,而配置了<mvc:default-servlet-handler/>标签,
    	 	此标签使spring不再默认注册RequestMappingHandlerAdapter的bean,这个bean能够处理@RequestMapping这个注解。
    	 	所以单独的使用<mvc:default-servlet-handler/>标签,会导致@RequestMapping失效
    	 -->
    	<mvc:annotation-driven/>
    	<!-- 表示上述配置的 css 文件不属 viewResolver 解析 -->
    	<mvc:default-servlet-handler/>
    	
    	<!-- 配置 springMVC 不拦截的静态资源 -->
    	<!-- css 下所有文件都映射到 /bootstrap/css/ (*: 只处理文件夹下一级; **: 文件夹下多级) -->
    	<mvc:resources mapping="/css/**" location="/bootstrap-3.3.7-dist/css/"/>
    	<mvc:resources mapping="/js/**" location="/bootstrap-3.3.7-dist/js/"/>
    	
    	<!-- 配置视图解析器 -->
    	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="prefix" value="/WEB-INF/jsp/"></property>
    		<property name="suffix" value=".jsp"></property>
    	</bean>
    
    1. mybatis-cfg.xml(可有可无)
    <configuration>
    <!-- mybatis配置文件 -->
    	<!-- 别名,Spring配置文件中配置了typeAliasesPackage属性后,此处不需要配置 -->
    	<!-- <typeAliases>
    		<package name="com.demo.model"/>
    		<package name="com.demo1.model"/>
    	</typeAliases> -->
    	
    	<!-- Spring配置文件中配置了MapperLocation属性后,此处不需要配置 -->
    	<!-- <mappers>
    		<mapper resource="com/demo/mapper/userMapper.xml"/>
    	</mappers> -->
    </configuration>
    
    1. jdbc.properties
    jdbc.url=jdbc:mysql://localhost:3306/ssm_test?useUnicode=true&amp;characterEncoding=utf8
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.username=root
    jdbc.password=root
    
    1. log4j.properties
    ### set log levels ###   
    log4j.rootLogger = info , Console , D  
    #Console  
    log4j.appender.Console=org.apache.log4j.ConsoleAppender  
    log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
    log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
    log4j.logger.java.sql.ResultSet=INFO  
    log4j.logger.org.apache=INFO  
    log4j.logger.java.sql.Connection=INFO  
    log4j.logger.java.sql.Statement=INFO  
    log4j.logger.java.sql.PreparedStatement=INFO  
    #output2file  
    log4j.appender.D = org.apache.log4j.DailyRollingFileAppender   
    log4j.appender.D.File = D:/logs/log.log   
    log4j.appender.D.Append = true   
    log4j.appender.D.Threshold = INFO ## u00E8u00BEu0093u00E5u0087u00BAinfou00E7u00BAu00A7u00E5u0088u00ABu00E4u00BBu00A5u00E4u00B8u008Au00E7u009Au0084u00E6u0097u00A5u00E5u00BFu0097   
    log4j.appender.D.layout = org.apache.log4j.PatternLayout   
    log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n  
    

    17.jsp页面

    列表页:userlist.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
    <%
    	String path = request.getContextPath();
    	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
    	request.setAttribute("basePath", basePath);
    %>
    <!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">
    <!-- 引入CSS样式 -->
    <link rel="stylesheet" href="${pageContext.request.contextPath }/css/bootstrap.min.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/css/bootstrap-theme.css">
    <!-- 引入Bootstrap文件,JS包放在Bootstrap包上 -->
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/bootstrap.min.js"></script>
    <title></title>
    </head>
    <body>
    	<div>
    		<h2 align="center">信息</h2>
    	</div>
    	<div align="center" style="margin-bottom: 50px">
    		<form action="${basePath }/user/getUser2" method="post">
    			<input type="text" name="name"><input type="submit" value="Search">
    		</form>
    	</div>
    	<div align="center">
    		<a href="${basePath }/user/toAddUser">新增</a>
    	</div>
    	<div class="container" align="center" style="margin-bottom: 50px">
    		<table class="table  table-bordered">
    			<tr>
    				<th>序号</th>
    				<th>ID</th>
    				<th>姓名</th>
    				<th>年龄</th>
    				<th>操作</th>
    			</tr>
    			<c:forEach items="${userList}" var="user" varStatus="status">
    				<tr>
    					<td>${status.count }</td>
    					<td>${user.id }</td>
    					<td>${user.userName }</td>
    					<td>${user.age }</td>
    					<td><a href="${basePath }/user/toUpdateUser?name=${user.userName }">修改</a><a href="${basePath }/user/deleteUser?name=${user.userName }">删除</a></td>
    				</tr>
    			</c:forEach>
    		</table>
    	</div>	
    </body>
    </html>
    添加修改页:adduser.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
    <%
    	String path = request.getContextPath();
    	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
    	request.setAttribute("basePath", basePath);
    %>
    <!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">
    <!-- 引入CSS样式 -->
    <link rel="stylesheet" href="${pageContext.request.contextPath }/css/bootstrap.min.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/css/bootstrap-theme.css">
    <!-- 引入Bootstrap文件,JS包放在Bootstrap包上 -->
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/bootstrap.min.js"></script>
    <title></title>
    </head>
    <body>
    	
    	<div  align="center">
    		<c:if test="${empty user }">
    			<h2>新增</h2>
    		</c:if>
    		<c:if test="${not empty user }">
    			<h2>修改</h2>
    		</c:if>
    		<c:if test="${empty user }">
    			<form action="${basePath }/user/addUser" method="post" >
    		</c:if>
    		<c:if test="${not empty user }">
    			<form action="${basePath }/user/updateUser" method="post" >
    		</c:if>
    			序号:<input type="text" name="id" value="${user.id }">	
    			<br>		
    			姓名:<input type="text" name="userName" value="${user.userName }">
    			<br>		
    			年龄:<input type="text" name="age" value="${user.age }">
    			<br>		
    			<button type="submit" class="btn btn-default">提交</button>
    		</form>
    	</div>
    </body>
    </html>
    
    

    源码:链接: https://pan.baidu.com/s/1x7hIvRhmiCh1gkzaCwLu8Q 提取码: 8ci5

  • 相关阅读:
    C语言-10-位域与共用体
    python-并发编程
    计算机操作系统
    网络编程-Socket
    网络编程-基础
    python-面向对象进阶
    python-面向对象
    python-模块分类与导入
    python-函数进阶
    python-函数内置方法
  • 原文地址:https://www.cnblogs.com/tengpengfei/p/10453926.html
Copyright © 2020-2023  润新知