1. 程式人生 > >idea建立ssm專案、增刪改查操作,以及注意事項!

idea建立ssm專案、增刪改查操作,以及注意事項!

專案技術工具:

  • jsp + springmvc + spring + mybatis +mysql5.7
  • maven 3.3.9
  • tomcat 8.5 + jdk 1.8

idea建立專案:

這裡寫圖片描述
或者
這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述
或者
這裡寫圖片描述
next然後finish即可,生成的專案目錄:
這裡寫圖片描述
需要新增成的目錄:

這裡寫圖片描述
當生成java目錄和resource目錄時需要處理一下:
原始:
這裡寫圖片描述
處理:
這裡寫圖片描述

這裡寫圖片描述
處理之後:
這裡寫圖片描述
處理的原因:
idea不會自動識別資源,需要手動設定!eclipse專案匯入idea時需要常常注意這個問題!

  • web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>ssm</display-name> <welcome-file-list
>
<welcome-file>index.jsp</welcome-file> </welcome-file-list> <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*:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
  • 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: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">

    <!-- 配置DataSource資料來源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/twjitm"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>

    </bean>

    <!--配置工廠, 建立SqlSessionFactory,同時指定資料來源 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自動掃描mapping.xml檔案 -->
        <property name="mapperLocations" value="classpath*:com.ssm/dao/EmpMapper.xml"></property>
    </bean>

    <!-- 配置MapperScannerConfigurer  -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- DAO介面所在地包,spring會自動查詢 -->
        <property name="basePackage" value="com.ssm.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- 開啟註解掃描
     某個類的頭上有特定的註解
     @Component,@Repository,@Service,@Controller,就會將這個物件作為Bean註冊進Spring容器。
     -->
    <context:component-scan base-package="com.ssm"/>

    <!-- 開啟RequestMapping 註解 -->
    <mvc:annotation-driven/>

    <!-- 處理請求轉發 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/emp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  • log4j.properties
log4j.rootLogger=CONSOLE,FILE
#log4j.rootLogger=DEBUG,CONSOLE,FILE
log4j.addivity.org.apache=true

# 應用於控制檯  
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=INFO
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.Encoding=GBK
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

# 每天新建日誌  
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.File=E:/log4j/log
log4j.appender.A1.Encoding=GBK
log4j.appender.A1.Threshold=DEBUG
log4j.appender.A1.DatePattern='.'yyyy-MM-dd
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L : %m%n

#應用於檔案  
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=E:/log4j/file.log
log4j.appender.FILE.Append=false
log4j.appender.FILE.Encoding=GBK
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

# 應用於檔案回滾  
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE.Threshold=ERROR
log4j.appender.ROLLING_FILE.File=rolling.log
log4j.appender.ROLLING_FILE.Append=true
log4j.appender.CONSOLE_FILE.Encoding=GBK
log4j.appender.ROLLING_FILE.MaxFileSize=10KB
log4j.appender.ROLLING_FILE.MaxBackupIndex=1
log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

#自定義Appender  
#log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender
#log4j.appender.im.host = mail.cybercorlin.net
#log4j.appender.im.username = username
#log4j.appender.im.password = password
#log4j.appender.im.recipient = [email protected]
#log4j.appender.im.layout=org.apache.log4j.PatternLayout
#log4j.appender.im.layout.ConversionPattern =[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

#應用於socket
log4j.appender.SOCKET=org.apache.log4j.RollingFileAppender
log4j.appender.SOCKET.RemoteHost=localhost
log4j.appender.SOCKET.Port=5001
log4j.appender.SOCKET.LocationInfo=true
# Set up for Log Facter 5  
log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout
log4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n  
# Log Factor 5 Appender  
log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender
log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000

# 傳送日誌給郵件  
#log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
#log4j.appender.MAIL.Threshold=FATAL
#log4j.appender.MAIL.BufferSize=10
#[email protected]
#log4j.appender.MAIL.SMTPHost=www.wusetu.com
#log4j.appender.MAIL.Subject=Log4J Message
#[email protected]
#log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout
#log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
  • entity
    — Condition.java
package com.ssm.entity;

import java.util.List;

public class Condition {

    private Integer deptno;
    private Double salary;
    private List<Integer> empnos;

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public List<Integer> getEmpnos() {
        return empnos;
    }

    public void setEmpnos(List<Integer> empnos) {
        this.empnos = empnos;
    }
    }

— Emp.java

package com.ssm.entity;

import java.util.Date;

public class Emp {

        private Integer empno;
        private String ename;
        private String job;
        private Integer mgr;
        private Date hiredate;
        private Double sal;
        private Double comm;
        private Integer deptno;

        public Integer getEmpno() {
            return empno;
        }

        public void setEmpno(Integer empno) {
            this.empno = empno;
        }

        public String getEname() {
            return ename;
        }

        public void setEname(String ename) {
            this.ename = ename;
        }

        public String getJob() {
            return job;
        }

        public void setJob(String job) {
            this.job = job;
        }

        public Integer getMgr() {
            return mgr;
        }

        public void setMgr(Integer mgr) {
            this.mgr = mgr;
        }

        public Date getHiredate() {
            return hiredate;
        }

        public void setHiredate(Date hiredate) {
            this.hiredate = hiredate;
        }

        public Double getSal() {
            return sal;
        }

        public void setSal(Double sal) {
            this.sal = sal;
        }

        public Double getComm() {
            return comm;
        }

        public void setComm(Double comm) {
            this.comm = comm;
        }

        public Integer getDeptno() {
            return deptno;
        }

        public void setDeptno(Integer deptno) {
            this.deptno = deptno;
        }

    }
  • dao層
    — EmpDao介面
package com.ssm.dao;

import com.ssm.entity.Emp;

import java.util.List;

public interface EmpDao {
    public List<Emp> findAll();        // 查詢全部

    public void save(Emp emp);            // 新增

    public Emp findById(int id);        // 按id查詢

    public void update(Emp emp);        // 更新

    public void delete(int id);            // 刪除

}
---EmpMapper.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.ssm.dao.EmpDao">
    <select id="findAll" resultType="com.ssm.entity.Emp">
        select * from t_emp order by empno
    </select>
    <insert id="save" parameterType="com.ssm.entity.Emp" useGeneratedKeys="true" keyProperty="empno">
        insert into t_emp values(
        #{ename,jdbcType=VARCHAR},
        #{job,jdbcType=VARCHAR},
        #{mgr,jdbcType=NUMERIC},
        #{hiredate,jdbcType=DATE},
        #{sal,jdbcType=NUMERIC},
        #{comm,jdbcType=NUMERIC},
        #{deptno,jdbcType=NUMERIC},
        #{empno,jdbcType=INTEGER}
        )
    </insert>
    <select id="findById" parameterType="java.lang.Integer" resultType="com.ssm.entity.Emp">
        select * from t_emp where empno=#{id}
    </select>
    <update id="update" parameterType="com.ssm.entity.Emp">
        update t_emp set
        ename = #{ename,jdbcType=VARCHAR},
        job = #{job,jdbcType=VARCHAR},
        sal = #{sal,jdbcType=NUMERIC}
        where empno=#{empno,jdbcType=NUMERIC}
    </update>
    <delete id="delete" parameterType="java.lang.Integer">
        delete from t_emp where empno=#{id}
    </delete>
</mapper>
  • Controller層
    —EmpController.java
package com.ssm.controller;

import com.ssm.dao.EmpDao;
import com.ssm.entity.Emp;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class EmpController {
    @Resource
    private EmpDao empDao;
    public void setEmpDao(EmpDao empDao) {
        this.empDao = empDao;
    }

    @RequestMapping("/find.do")
    public String find(Model model) {
        List<Emp> list = empDao.findAll();
        model.addAttribute("emps", list);
        return "emp_list";
    }

    /*
     * 開啟新頁面
     */
    @RequestMapping("/toAddEmp.do")
    public String toAdd(){
        return "emp_add";
    }
    /*
     * 新增儲存
     */
    @RequestMapping("/addEmp.do")
    public String add(Emp emp){
        empDao.save(emp);
        return "redirect:find.do";
    }

    /*
     * 開啟修改頁面
     */
    @RequestMapping("/toUpdateEmp.do")
    public String toUpdate(@RequestParam("id") int id, Model model){
        Emp emp =empDao.findById(id);
        model.addAttribute("emp",emp);
        return "emp_update";
    }

    /*
     * 修改儲存
     */
    @RequestMapping("/updateEmp.do")
    public String update(Emp emp){
        empDao.update(emp);
        return "redirect:find.do";
    }

    /*
     * 刪除
     */
    @RequestMapping("/deleteEmp.do")
    public String delete(@RequestParam("id") int id){
        empDao.delete(id);
        return "redirect:find.do";
    }


}
  • jsp前端頁面
    —emp_add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>add_emp.jsp</title>
</head>
<body>
<form action="addEmp.do" method="post">
    <table width="40%" border="1" cellpadding="2" cellspacing="0" align="center" >
        <tr>
            <td>姓名</td>
            <td><input type="text" name="ename" /></td>
        </tr>
        <tr>
            <td>崗位</td>
            <td><input type="text" name="job" /></td>
        </tr>
        <tr>
            <td>工資</td>
            <td><input type="text" name="sal" /></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="儲存" /></td>
        </tr>
    </table>
</form>
</body>
</html>

—emp_list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>emp_list.jsp</title>
    <script type="text/javascript">
        function delete_emp(id){
            var str = window.confirm("are you sure ?");

            if(str){
                location.href="deleteEmp.do?id="+id;
            }
        }
    </script>
</head>
<body>
<div align="center">
    <input type="button" value="新增" onclick="location.href='toAddEmp.do'" >
</div>
<table width="80%" border="1" cellpadding="2" cellspacing="0" align="center">
    <tr>
        <th>EMPNO</th>
        <th>ENAME</th>
        <th>JOB</th>
        <th>MGR</th>
        <th>HIREDATE</th>
        <th>SAL</th>
        <th>COMM</th>
        <th>DEPTNO</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${emps}" var="emp">
        <tr>
            <td>${emp.empno}</td>
            <td>${emp.ename}</td>
            <td>${emp.job}</td>
            <td>${emp.mgr}</td>
            <td>${emp.hiredate}</td>
            <td>${emp.sal}</td>
            <td>${emp.comm}</td>
            <td>${emp.deptno}</td>
            <td>
                <input type="button" value="修改" onclick="location.href='toUpdateEmp.do?id=${emp.empno}'" />
                <input type="button" value="刪除" onclick="delete_emp(${emp.empno});" />
            </td>
        </tr>
    </c:forEach>
</table>
</body>

</html>

—emp_update.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="updateEmp.do" method="post">
    <table width="40%" align="center" border="1" cellpadding="2" cellspacing="0" >
        <tr>
            <td>EMPNO:</td>
            <td><input type="text" name="empno" value="${emp.empno }" disabled> </td>
        </tr>
        <tr>
            <td>姓名:</td>
            <td><input type="text" name="ename" value="${emp.ename }" > </td>
        </tr>
        <tr>
            <td>崗位:</td>
            <td><input type="text" name="job" value="${emp.job }" > </td>
        </tr>
        <tr>
            <td>工資:</td>
            <td><input type="text" name="sal" value="${emp.sal }" > </td>
        </tr>
        <tr>
            <td> <input type="submit" value="儲存" > </td>
        </tr>
    </table>
</form>
</body>
</html>

資料庫表:

DROP TABLE IF EXISTS `t_emp`;
CREATE TABLE `t_emp` (
  `ename` varchar(255) DEFAULT NULL,
  `job` varchar(255) DEFAULT NULL,
  `mgr` decimal(10,0) DEFAULT NULL,
  `hiredate` date DEFAULT NULL,
  `sal` decimal(10,0) DEFAULT NULL,
  `comm` decimal(10,0) DEFAULT NULL,
  `deptno` decimal(10,0) DEFAULT NULL,
  `empno` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`empno`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_emp
-- ----------------------------
INSERT INTO `t_emp` VALUES ('aaa', 'a', '12', '2018-08-23', '12', '1', '12', '1');
INSERT INTO `t_emp` VALUES ('i', 'a', '12', '2018-08-23', '12', '1', '12', '2');
INSERT INTO `t_emp` VALUES ('b', 'a', '12', '2018-08-23', '12', '1', '12', '3');
INSERT INTO `t_emp` VALUES ('c', 'a', '12', '2018-08-23', '12', '1', '12', '4');
INSERT INTO `t_emp` VALUES ('d', 'a', '12', '2018-08-23', '12', '1', '12', '5');
INSERT INTO `t_emp` VALUES ('e', 'a', '12', '2018-08-23', '12', '1', '12', '6');
INSERT INTO `t_emp` VALUES ('f', 'a', '12', '2018-08-23', '12', '1', '12', '7');
INSERT INTO `t_emp` VALUES ('g', 'a', '12'