CRUD V1.0

标签: JavaWeb  spring  java

学习目标

  1. CRUD-不包含ajax
  2. CRUD-包含ajax
  3. CRUD-包含ajax-bootstrap

项目简介

  1. 项目的经典模块-CRUD功能
  2. 什么是CRUD
    CRUD:Create( 创 建 ) Retrieve(查询) Update(更新) Delete(删除)
  3. 使用什么技术
    ssm:SpringMVC+Spring+MyBatis
  4. 版本
    V1 : ssm
    V2 : ssm+Ajax
    V3 : ssm+Ajax+bootstrap
    在这里插入图片描述

sql

create database crud;
use crud;

create table department(
	did int primary key auto_increment,
	dname varchar(20)
);
insert into department values(null,'java');
insert into department values(null,'测试');
insert into department values(null,'需求');

create table employee(
	eid int primary key auto_increment,
	ename varchar(20),
	gender varchar(20),
	did int 
);
insert into employee values(null,'jack','1',1);
insert into employee values(null,'rose','1',1);
insert into employee values(null,'tony','1',2);

在这里插入图片描述

ssm搭建

applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--   设置扫描包,包下设置注解@Service @Repository @Component @AutoWried-->
    <context:component-scan base-package="com.vission">
        <!--    由于springmvc的controller是由springmvc来扫描,需要将controller排除在外-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 四大信息-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/crud?characterEncoding=utf-8"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="user" value="root"></property>
        <property name="password" value=""></property>
    </bean>
    <!-- session工厂-->
    <bean id="sqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.vission.bean"/>

    </bean>
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.vission.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!--配置Spring框架声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!--配置AOP增强-->
    <aop:config>
        <aop:pointcut id="service" expression="execution(* com.vission.Service.Impl.*ServiceImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
    </aop:config>
</beans>

springmvc

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--springmvc是web层  UserController  @Controller -->
    <!-- 打开组件扫描-->
    <context:component-scan base-package="com.vission">
        <!-- 只处理带@Controller的请求-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置的视图解析器对象 /WEB-INF/pages/success.jsp -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
<!--    &lt;!&ndash;过滤静态资源   .js .css png&ndash;&gt;-->
<!--    <mvc:resources location="/WEB-INF/css/" mapping="/css/**" />-->
<!--    <mvc:resources location="/WEB-INF/images/" mapping="/images/**" />-->
<!--    <mvc:resources location="/WEB-INF/js/" mapping="/js/**" />-->
<!--    &lt;!&ndash;开启SpringMVC注解的支持 @RequestMapping @RequestBody @ResponseBody&ndash;&gt;-->
<!--    <mvc:annotation-driven/>-->
</beans>

web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <filter>
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置前端控制器  controller-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器,创建该servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

log4j.preperties


# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE  debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=/logs/wlanapi/client.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

目录结构
在这里插入图片描述
bean
Department

package com.vission.bean;

public class Department {
    private int did;
    private String dname;

    public Department(String dname) {
        this.dname = dname;
    }

    public Department(int did, String dname) {
        this.did = did;
        this.dname = dname;
    }

    public int getDid() {
        return did;
    }

    public void setDid(int did) {
        this.did = did;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    @Override
    public String toString() {
        return "Department{" +
                "did=" + did +
                ", dname='" + dname + '\'' +
                '}';
    }
}

由于我是敲完项目再写的博客,我直接贴代码吧

先搞个页面出来看看

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/dept/select">
    <input type="text" name="dname"/><input type="submit" value="查找"/><br/>
</form>
<a href="${pageContext.request.contextPath}/dept/list">首页</a>
<table border="1px" width="100%">
    <tr>
        <td>编号</td>
        <td>部门名称</td>
        <td>管理</td>
    </tr>

    <c:forEach items="${depts}" var="dept">
        <tr>
            <td>${dept.did}</td>
            <td>${dept.dname}</td>
            <td><a href="${pageContext.request.contextPath}/dept/delete?did=${dept.did}">删除</a>
                <a href="${pageContext.request.contextPath}/dept/findByDid?did=${dept.did}">修改</a></td>
        </tr>
    </c:forEach>
    <form method="post" action="${pageContext.request.contextPath}/dept/save">
        <tr>
            <td>${depts[depts.size()-1].did+1}</td>
            <td><input type="text" name="dname"/></td>
            <td><input type="submit" value="保存"/></td>
        </tr>
    </form>
</table>
</body>
</html>


src\main\java\com\vission\Controller\DepartmentController.java

@Controller
@RequestMapping("/dept")
public class DepartmentController {
    private static final Logger l = LoggerFactory.getLogger(DepartmentController.class);
    @Autowired
    private DepartmentService iDepartmentService;

    @RequestMapping(path = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        List<Department> depts = iDepartmentService.findAllDepartments();
        l.info("list   depts=" + depts);
        //数据添加到页面
        model.addAttribute("depts", depts);
        return "list_depts";
    }

    @RequestMapping(path ="/save",method = RequestMethod.POST)
    public String save(String dname,Model model){
        if (dname != null && dname != ""){
//            l.info(iDepartmentService.findDepartmentByDname(dname).getDname());
            Department dept = new Department(dname);
            iDepartmentService.saveDepartment(dept);
            return "redirect:/dept/list";
        }else{
            model.addAttribute("error_msg","部门名称不能为空");
            return "forward:/error.jsp";
        }
    }

    @RequestMapping(path = "/delete",method = RequestMethod.GET)
    public String delete(Integer did){
        l.info("delete  did = "+did);
        iDepartmentService.deletetDepartmentsByDid(did);
        return "redirect:/dept/list";
    }


    @RequestMapping(path = "/findByDid",method = RequestMethod.GET)
    public String findByDid(Model model,int did){
//        System.out.println(did);
        Department dept = iDepartmentService.findDepartmentById(did);
//        System.out.println(dept);
        model.addAttribute("dept", dept);
        return "update_dept";
    }

    @RequestMapping(path = "/update",method = RequestMethod.POST)
    public String upadate(Integer did,String dname){
        //为什么不能传入对象
        Department dept = new Department(did,dname);
        System.out.println("进入update模块");
        System.out.println(dept);
        iDepartmentService.updateDepartmentById(dept);
        return "redirect:/dept/list";
    }
    @RequestMapping(path = "/select",method = RequestMethod.POST)
    public String select(String dname,Model model){
        List<Department> depts = iDepartmentService.selectDepartmentBydname("%"+dname+"%");
        model.addAttribute("depts", depts);
        return "list_depts";
    }

}

dao
IDepartmentDao

package com.vission.dao;

import com.vission.bean.Department;

import java.util.List;

public interface IDepartmentDao {
    //select * from department order by did asc;
    List<Department> findAll();

    //insert into department values(null,'');
    void save(Department dept);

    //delete from department where did = #{did};
    void deleteByDid(int did);

    Department findDeptByName(String dname);

    void update(Department dept);

    Department findById(int did);

    List<Department> selectBydname(String dname);
}

IDepartmentDao.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.vission.dao.IDepartmentDao">

    <select id="findAll" resultType="Department">
        select * from department order by did asc;
    </select>
    <insert id="save" parameterType="department">
        insert into department values(null,#{dname});
    </insert>
    <delete id="deleteByDid" parameterType="int">
        delete from department where did = #{did};
    </delete>

    <select id="findDeptByName" resultType="Department">
        select * from department where dname = #{dname};
    </select>

    <update id="update" parameterType="department">
        update department set dname = #{dname} where did = #{did};
    </update>


    <select id="findById" parameterType="int" resultType="department">
        select * from department where did = #{did};
    </select>

    <select id="selectBydname" parameterType="String" resultType="department">
        select * from department where dname like #{dname};
    </select>
</mapper>

Service
DepartmentService

package com.vission.Service;

import com.vission.bean.Department;

import java.util.List;

public interface DepartmentService {
    void saveDepartment(Department dept);
    List<Department> findAllDepartments();
    void deletetDepartmentsByDid(int did);
    Department findDepartmentByDname(String Dname);
    //根据指定id修改部门名称
    void updateDepartmentById(Department dept);
    //查找指定id的部门数据
    Department findDepartmentById(int did);
    List<Department> selectDepartmentBydname(String dname);
}

DepartmentImpl

package com.vission.Service.Impl;

import com.vission.dao.IDepartmentDao;
import com.vission.Service.DepartmentService;
import com.vission.bean.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    IDepartmentDao dao;
    @Override
    public void saveDepartment(Department dept) {
        dao.save(dept);
    }
    @Override
    public List<Department> findAllDepartments() {
        List<Department> list = dao.findAll();
        return list;
    }
    @Override
    public void deletetDepartmentsByDid(int did) {
        dao.deleteByDid(did);
    }
    @Override
    public Department findDepartmentByDname(String Dname) {
        Department  dept = dao.findDeptByName(Dname);
        return  dept;
    }
    @Override
    public void updateDepartmentById(Department dept) {
        dao.update(dept);
    }
    @Override
    public Department findDepartmentById(int did) {
        return dao.findById(did);
    }
    @Override
    public List<Department> selectDepartmentBydname(String dname) {
        List<Department> list = dao.selectBydname(dname);
        return list;
    }
}

update_depts.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${dept}
<form method="post" action="${pageContext.request.contextPath}/dept/update">
    <input type="hidden" name="did" value="${dept.did}" >
    <input type="text"  value="${dept.did}" disabled="disabled"/><br/>
    <input type="text" name="dname" value="${dept.dname}"/><br/>
    <input type="submit" value="保存修改"/><br/>
</form>

</body>
</html>


版权声明:本文为qq_40863153原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_40863153/article/details/109162679

智能推荐

Hibernate学习总结(一)

一、Hibernate简介 一个持久层的ORM框架。ORM:Object Relational Mapping(对象关系映射)。指的是将一个Java中的对象与关系型数据库中的表建立一种映射关系,从而操作对象就可以操作数据库中的表。 二、Hibernate入门 1、创建一个项目,引入jar包 hibernate用到的jar包 2、创建表 3、创建实体类 4、创建映射(*****) 映射需要通过XML...

Linux系统NFS

文章目录 1. nfs简介 1.1 nfs特点 1.2 使用nfs的好处 1.3 nfs的体系组成 1.4 nfs的应用场景 2. nfs工作机制 2.1 RPC 2.2 NIS 2.3 nfs工作机制 3. exports文件的格式 4. nfs管理 5. 作业 5.1手动搭建一个nfs服务器 5.1.1开放/nfs/shared目录,供所有用户查阅资料 5.1.2 开放/nfs/upload目...

关于java中String,StringBuffer,StringBuilder的区别以及StringBuffer,StringBuilder的安全性问题

这里的结果就是正确的然后我们来看他的append方法 它在前边加了一个synchronized来修饰,相当于同时只能有一个线程来访问他,这样就不会产生上边的问题但同时他的效率也就比StringBuilder低,...

Django连接现有mysql数据库

1、打开cmd后cd到项目位置 2、建立项目 django-admin startproject test2 3、编辑项目中的配置文件, mysite/settings.py ,告诉Django你的数据库连接参数和数据库名。具体的说,要提供 DATABASE_NAME , DATABASE_ENGINE , DATAB...

ShareSDK新浪微博登录时报错error:redirect_uri_mismatch

今天用 ShareSDK 做第三方登录的时候碰到个问题,明明在微博平台的应用审核已经通过了,但是调用登录接口的时候一直报错,错误如下: 出现这个错误是因为在微博开放平台上没有设置回调地址,或者设置的回调地址与本地XML中的地址不一致。 在sharesdk.xml文件当中对于微博的设置: 其中RedirectUrl为设置的回调地址,这里的地址必须要与微博开发平台设置的地址相同,否则就会出现上面的错误...

猜你喜欢

python解析网络封包方法

2019独角兽企业重金招聘Python工程师标准>>> 在使用Python解析网络数据包时,使用网络字节序解析,参见下表。 C语言的数据类型和Python的数据类型对照表请参见下表。 接下来对封包与解包进行举例说明。 version type id content unsigned short unsigned short unsigned int unsigned int 封包...

python3:时间方法,异常处理,系统文件相关模块(os)

文章目录 时间方法 time模块 时间表示方法: time模块的方法 datetime模块 异常处理 触发异常 创建mydiv.py脚本,要求如下: 创建myerror.py脚本,要求如下: os模块 实现ls -R(os.walk) os.path pickle模块 记账脚本 时间方法 time模块 时间表示方法: 时间戳:自1970-1-1 0:00:00到某一时间点之间的秒数 UTC时间:世...

负载均衡群集——LVS+DR模型

一、实验组成 调度器 192.168.100:41 web1 192.168.100:42 web2 192.168.100.43 NFS共享服务器 192.168.100.44 二、实验拓扑 三、实验配置 3.1在调度器配置:192.168.100.41 配置虚拟IP地址(VIP) 调整/proc响应参数 对于 DR 群集模式来说,由于 LVS 负载调度器和各节点需要共用 VIP 地址,应该关闭...

adb无线连接时appium找不到设备

问题描述 以前使用USB连接真机,运行appium时一直正常,连接参数如下: 最近为了方便,使用adb无线连接真机,adb版本为1.0.40,真机安卓版本10,连接后,通过adb devices能够查看到连接的设备: adb无线连接是正常的,但每次运行时appium都找不到无线连接的设备,陷入重启adb循环: 解决流程 1.因为是没找到设备,所以在appium连接参数中增加了"udid&...

Mybatis_CRUD(基于xml的增删改查操作)

dao IUserDao domain User QueryVo SqlMapConfig.xml com.itheima.dao IUserDao.xml com.itheima.test 执行原理图:...