IDEA搭建SSM实现增、删、改、查及登录判断、注册功能

Maven搭建SSM项目

使用Intellij idea 搭建基本的maven项目 new->project

IDEA搭建SSM实现增、删、改、查及登录判断、注册功能_第1张图片


最后Finish,Maven项目搭建完成

IDEA搭建SSM实现增、删、改、查及登录判断、注册功能_第2张图片


配置Maven

IDEA搭建SSM实现增、删、改、查及登录判断、注册功能_第3张图片

构建项目基本目录结构

如下图:

IDEA搭建SSM实现增、删、改、查及登录判断、注册功能_第4张图片


controller:http(GET和POST等)请求的入口,调用Service,向客户端返回数据

dao:接口,定义了数据表映射成的对象,具有的操作

mapping:具体是sql语句,以xml格式存在,即mybatis的语法文件

service:controller调用的服务,service调用dao里面定义的数据库行为方法,来执行对应mapping里的mybatis,从而完成与数据库完整的交互。


Pom.xml中配置相关Jar包信息

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>hugogroupId>
  <artifactId>exampleartifactId>
  <packaging>warpackaging>
  <version>1.0-SNAPSHOTversion>
  <name>hugo Maven Webappname>
  <url>http://maven.apache.orgurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    
    <spring.version>4.1.4.RELEASEspring.version>
    
    <mybatis.version>3.2.8mybatis.version>
    
    <slf4j.version>1.7.7slf4j.version>
    <log4j.version>1.2.17log4j.version>
    
    <jackson.version>2.5.0jackson.version>
  properties>
  
  <dependencies>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.2.2version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
      <scope>testscope>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-beansartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.0.1version>
      <scope>providedscope>
    dependency>

    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.2version>
      <scope>providedscope>
    dependency>

    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.30version>
    dependency>

    
    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>1.2.2version>
    dependency>

    
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
    
    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>${log4j.version}version>
    dependency>


    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>fastjsonartifactId>
      <version>1.1.41version>
    dependency>


    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${slf4j.version}version>
    dependency>
    
    
    <dependency>
      <groupId>org.codehaus.jacksongroupId>
      <artifactId>jackson-mapper-aslartifactId>
      <version>1.9.13version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.1.0version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>2.1.0version>
    dependency>

    
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.1version>
    dependency>
    <dependency>
      <groupId>commons-iogroupId>
      <artifactId>commons-ioartifactId>
      <version>2.4version>
    dependency>
    <dependency>
      <groupId>commons-codecgroupId>
      <artifactId>commons-codecartifactId>
      <version>1.9version>
    dependency>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      
      <scope>testscope>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>4.1.7.RELEASEversion>
    dependency>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>RELEASEversion>
    dependency>

    <dependency>
      <groupId>org.jsoupgroupId>
      <artifactId>jsoupartifactId>
      <version>1.8.1version>
    dependency>

    <dependency>
      <groupId>net.sourceforge.htmlunitgroupId>
      <artifactId>htmlunitartifactId>
      <version>2.15version>
    dependency>


    <dependency>
      <groupId>org.seleniumhq.seleniumgroupId>
      <artifactId>selenium-javaartifactId>
      <version>2.33.0version>
    dependency>

    <dependency>
      <groupId>us.codecraftgroupId>
      <artifactId>webmagic-coreartifactId>
      <version>0.6.1version>
    dependency>
    <dependency>
      <groupId>us.codecraftgroupId>
      <artifactId>webmagic-extensionartifactId>
      <version>0.6.1version>
    dependency>


  dependencies>
  <build>
    <finalName>hugofinalName>
  <resources>
    <resource>
      <directory>src/main/javadirectory>
      <includes>
        <include>**/*.xmlinclude>
      includes>
      <filtering>truefiltering>
    resource>
  resources>
  build>

project>

配置好后基本骨架如下图

IDEA搭建SSM实现增、删、改、查及登录判断、注册功能_第5张图片

配置resources目录文件

jdbc.properties配置:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mine?useUnicode=true&characterEncoding=utf-8
username=root
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

log4j.properties配置:

#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

log4j.xml配置:

xml version="1.0" encoding="UTF-8"?>
 log4j:configuration SYSTEM "http://toolkit.alibaba-inc.com/dtd/log4j/log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://jakarta.apache.org/log4j/ ">
    
    
    
    <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}]-[%c]-[%t] %x - %m%n"/>
        layout>
    appender>

    
    <logger name="org.apache.ibatis" additivity="true">
        <level value="DEBUG"/>
        <appender-ref ref="consoleAppender"/>
    logger>

    <logger name="org.mybatis.spring" additivity="true">
        <level value="ERROR"/>
        <appender-ref ref="consoleAppender"/>
    logger>
    <logger name="java.sql" additivity="true">
        <level value="DEBUG"/>
        <appender-ref ref="consoleAppender"/>
    logger>

    <logger name="java.sql.Connection" additivity="true">
        <level value="DEBUG"/>
        <appender-ref ref="consoleAppender"/>
    logger>

    <logger name="java.sql.Statement" additivity="true">
        <level value="DEBUG"/>
        <appender-ref ref="consoleAppender"/>
    logger>

    <logger name="java.sql.PreparedStatement" additivity="true">
        <level value="DEBUG"/>
        <appender-ref ref="consoleAppender"/>
    logger>

    
    <logger name="org.springframework" additivity="true">
        <level value="ERROR"/>
        <appender-ref ref="consoleAppender"/>
    logger>

    
    <logger name="org.apache.activemq" additivity="true">
        <level value="ERROR"/>
        <appender-ref ref="consoleAppender"/>
    logger>
    
    
    
    <root>
        <level value="DEBUG"/>
        <appender-ref ref="consoleAppender"/>
    root>
log4j:configuration>

mybatis-config.xml配置:

xml version="1.0" encoding="UTF-8" ?>
 configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <settings>
        <setting name="logImpl" value="LOG4J" />
        <setting name="cacheEnabled" value="true"/>
    settings>
configuration>



spring-mvc.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">
   
   <context:component-scan base-package="com.springmvc.controller" />

   
   <bean id="mappingJacksonHttpMessageConverter"
      class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="supportedMediaTypes">
         <list>
            <value>text/html;charset=UTF-8value>
         list>
      property>
   bean>
   
   <bean
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      <property name="messageConverters">
         <list>
            <ref bean="mappingJacksonHttpMessageConverter" />  
         list>
      property>
   bean>
   
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      
      <property name="prefix" value="/" />
      <property name="suffix" value=".jsp" />
   bean>
   
   
   <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>

spring-mybatis配置

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">
   
   <context:component-scan base-package="com.springmvc" />
   
   <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}" />
      
      <property name="initialSize" value="${initialSize}">property>
      
      <property name="maxActive" value="${maxActive}">property>
      
      <property name="maxIdle" value="${maxIdle}">property>
      
      <property name="minIdle" value="${minIdle}">property>
      
      <property name="maxWait" value="${maxWait}">property>
   bean>

   
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="configLocation" value="classpath:/mybatis-config.xml">property>
      
      <property name="mapperLocations" value="classpath:com/springmvc/mapping/*.xml">property>

   bean>

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

   
   <bean id="transactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource" />
   bean>

beans>

项目配置基本完成,接下来我们一起来看看具体实现代码:

IDEA搭建SSM实现增、删、改、查及登录判断、注册功能_第6张图片

图中箭头指向类可通过mybatis-generator Jar包和generatorConfig.xml配置文件逆向生成,具体操作详见下篇博客

Main类代码:

package com.springmvc.controller;

import com.springmvc.pojo.Admin;
import com.springmvc.service.AdminService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class main {
@Autowired
private  AdminService service;
   // @RequestMapping("/getUser")
////    public String getUser(int id, HttpServletRequest request, Model model){
////        request.setAttribute("user",service.getAdmin(id));
////        model.addAttribute("user",service.getAdmin(id));
////        return "/editUser";
////    }
@RequestMapping("/add")
public String addUser(Admin admin,Model model){
    System.out.println("ok");
 service.insertAdmin(admin);

    return "allUser";
}
@RequestMapping("/find")
public String chaxun (HttpServletRequest request, Model model){
    System.out.println("qian");
     List userList = service.finall();
    System.out.println(userList.toString());
    System.out.println("hou");
    model.addAttribute("userList",userList);
    request.setAttribute("userList",userList);
    return "allUser";

}
    @RequestMapping("/getUser")
    public String getUser(int id,HttpServletRequest request,Model model){
        request.setAttribute("user",service.getAdmin(id));
        model.addAttribute("user",service.getAdmin(id));
        return "editUser";
    }
    @RequestMapping("/updateUser")
    public String updateUser(Admin admin,HttpServletRequest request,Model model){
       if(service.update(admin)){
            admin=service.getAdmin(admin.getId());
            request.setAttribute("admin",admin);
            model.addAttribute("admin",admin);
            return "redirect:/find;";
        }else{
            return "error";
        }
    }

    @RequestMapping("/deleUser")
    public  String deleted(int id,HttpServletRequest request,Model model){
       service.delete(id);
        return "redirect:/find;";
    }
    @RequestMapping("/LoginUser")
    public  String login(Admin admin,Model model){
       System.out.println(""+admin.getName()+",,,,"+admin.getPassword());
        Admin admin1=service.login(admin);
        System.out.println("我传值进去了");
        if(admin1!=null){
            System.out.println("我能判断");
            return "redirect:/find;";
        }else {

        }
        return  "error";

    }

}

AdminMapper接口代码:

package com.springmvc.dao;

import com.springmvc.pojo.Admin;

import java.util.List;

public interface AdminMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Admin record);
     List find();
    int insertSelective(Admin record);

    Admin selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Admin record);

    boolean updateByPrimaryKey(Admin record);
    Admin login(Admin a);

}

AdminMapper.xml

xml version="1.0" encoding="UTF-8" ?>
 mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.springmvc.dao.AdminMapper" >
  <resultMap id="BaseResultMap" type="com.springmvc.pojo.Admin" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  resultMap>
  <sql id="Base_Column_List" >
    id, name, password
  sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from admin
    where id = #{id,jdbcType=INTEGER}
  select>
  <select id="find" resultMap="BaseResultMap" parameterType="java.lang.Integer">
      select* from admin

  select>

  <select id="login" resultMap="BaseResultMap" parameterType="com.springmvc.pojo.Admin">
     select*from admin where name=#{name} and password=#{password}

  select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from admin
    where id = #{id,jdbcType=INTEGER}
  delete>
  <insert id="insert" parameterType="com.springmvc.pojo.Admin" >
    insert into admin (name, password
      )
    values (
    #{name},#{password}
      )
  insert>
  <insert id="insertSelective" parameterType="com.springmvc.pojo.Admin" >
    insert into admin
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      if>
      <if test="name != null" >
        name,
      if>
      <if test="password != null" >
        password,
      if>
    trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      if>
    trim>
  insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.springmvc.pojo.Admin" >
    update admin
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      if>
    set>
    where id = #{id,jdbcType=INTEGER}
  update>
  <update id="updateByPrimaryKey" parameterType="com.springmvc.pojo.Admin" >
    update admin
    set name = #{name,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  update>
mapper>

Admin

package com.springmvc.pojo;

public class Admin {
    private Integer id;

    private String name;

    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "Admin{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

AdminService

package com.springmvc.pojo;

public class Admin {
    private Integer id;

    private String name;

    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "Admin{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

ok,后台代码及配置文件已全部写完,前端页面可自行选择

注意:数据库配置文件按需求修改,Tomcat运行时一定记得把项目打包成war包

IDEA搭建SSM实现增、删、改、查及登录判断、注册功能_第7张图片


源码下载:https://download.csdn.net/download/blogsdemo/10375360(内含前端页面)







你可能感兴趣的:(IDEA搭建SSM实现增、删、改、查及登录判断、注册功能)