欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用idea创建一个基本的smm项目(带增删改查)

程序员文章站 2022-04-17 21:07:12
环境 idea jdk1.8 tomcat mysql 打开idea选择创建一个maven项目 然后点击next,next,finsh 然后看项目的结构 如图所示 接着创建com包,再在com包下新建四个包,分别命名为: 自定义pom.xml 在resource包下新建Directory:mappe ......

环境  idea  jdk1.8  tomcat  mysql

打开idea选择创建一个maven项目

然后点击next,next,finsh

利用idea创建一个基本的smm项目(带增删改查)

利用idea创建一个基本的smm项目(带增删改查)利用idea创建一个基本的smm项目(带增删改查)

然后看项目的结构

如图所示

接着创建com包,再在com包下新建四个包,分别命名为:

利用idea创建一个基本的smm项目(带增删改查)

 

自定义pom.xml

<?xml version="1.0" encoding="utf-8"?>

<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/xsd/maven-4.0.0.xsd">
 <modelversion>4.0.0</modelversion>

 <groupid>com.li</groupid>
 <artifactid>ssm_test_2</artifactid>
 <version>1.0-snapshot</version>
 <packaging>war</packaging>

 <name>ssm_test_2 maven webapp</name>
 <!-- 用来设置版本号 -->
 <properties>
   <srping.version>4.0.2.release</srping.version>
   <mybatis.version>3.2.8</mybatis.version>
   <slf4j.version>1.7.12</slf4j.version>
   <log4j.version>1.2.17</log4j.version>
   <druid.version>1.0.9</druid.version>
 </properties>
 <!-- 用到的jar包 -->
 <dependencies>
   <!-- servlet依赖的jar包start -->
   <dependency>
     <groupid>javax.servlet</groupid>
     <artifactid>javax.servlet-api</artifactid>
   </dependency>
   <!-- servlet依赖的jar包start -->

   <!-- jsp依赖jar包start -->
   <dependency>
     <groupid>javax.servlet.jsp</groupid>
     <artifactid>javax.servlet.jsp-api</artifactid>
     <version>2.3.1</version>
   </dependency>
   <!-- 单元测试 -->
   <dependency>
     <groupid>junit</groupid>
     <artifactid>junit</artifactid>
     <version>4.11</version>
     <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
     <scope>test</scope>
   </dependency>

   <!-- spring框架包 -->
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-test</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-core</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-oxm</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-tx</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-jdbc</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-aop</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-context</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-context-support</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-expression</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-orm</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-web</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <dependency>
     <groupid>org.springframework</groupid>
     <artifactid>spring-webmvc</artifactid>
     <version>${srping.version}</version>
   </dependency>
   <!-- spring框架包 -->
   <!-- mybatis框架包 -->
   <dependency>
     <groupid>org.mybatis</groupid>
     <artifactid>mybatis</artifactid>
     <version>${mybatis.version}</version>
   </dependency>
   <dependency>
     <groupid>org.mybatis</groupid>
     <artifactid>mybatis-spring</artifactid>
     <version>1.2.2</version>
   </dependency>
   <!-- mybatis框架包 -->
   <!-- 数据库驱动 -->
   <dependency>
     <groupid>mysql</groupid>
     <artifactid>mysql-connector-java</artifactid>
     <version>5.1.35</version>
   </dependency>
   <!-- 导入dbcp的jar包,用来在applicationcontext.xml中配置数据库 -->
   <dependency>
     <groupid>commons-dbcp</groupid>
     <artifactid>commons-dbcp</artifactid>
     <version>1.2.2</version>
   </dependency>
   <!-- jstl标签类 -->
   <dependency>
     <groupid>jstl</groupid>
     <artifactid>jstl</artifactid>
     <version>1.2</version>
   </dependency>
   <!-- log -->
   <dependency>
     <groupid>log4j</groupid>
     <artifactid>log4j</artifactid>
     <version>${log4j.version}</version>
   </dependency>
   <dependency>
     <groupid>org.slf4j</groupid>
     <artifactid>slf4j-api</artifactid>
     <version>${slf4j.version}</version>
   </dependency>
   <dependency>
     <groupid>org.slf4j</groupid>
     <artifactid>slf4j-log4j12</artifactid>
     <version>${slf4j.version}</version>
   </dependency>
   <!-- 连接池 -->
   <dependency>
     <groupid>com.alibaba</groupid>
     <artifactid>druid</artifactid>
     <version>${druid.version}</version>
   </dependency>
 </dependencies>

 <build>
   <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
   <resources>
     <resource>
       <directory>src/main/java</directory>
       <includes>
         <include>**/*.properties</include>
         <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
     </resource>
     <resource>
       <directory>src/main/resources</directory>
       <includes>
         <include>**/*.properties</include>
         <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
     </resource>
   </resources>
   <!-- java编译插件,如果maven的设置里配置好jdk版本就不用 -->
   <plugins>
     <plugin>
       <groupid>org.apache.maven.plugins</groupid>
       <artifactid>maven-compiler-plugin</artifactid>
       <version>3.2</version>
       <configuration>
         <source>1.8</source>
         <target>1.8</target>
         <encoding>utf-8</encoding>
       </configuration>
     </plugin>
   </plugins>
 </build>
</project>

在resource包下新建directory:mapper(用来放xxmapper.xml)

添加jdbc.properties和lo4j.properties文件

jdbc.properties

driver=com.mysql.jdbc.driver
url=jdbc\:mysql\://localhost\:3306/test
username=root
password=123456

initialsize=0

maxactive=20

maxidle=20

minidle=1

maxwait=60000

lo4j.properties文件

log4j.rootlogger=debug,console,file
#log4j.rootlogger=error,rolling_file
log4j.logger.com.qhit.dao=debug
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.simpledatasource=debug
log4j.logger.com.ibatis.common.jdbc.scriptrunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.sqlmapclientdelegate=debug
log4j.logger.java.sql.connection=debug
log4j.logger.java.sql.statement=debug
log4j.logger.java.sql.preparedstatement=debug
log4j.logger.java.sql.resultset=debug
log4j.logger.org.tuckey.web.filters.urlrewrite.urlrewritefilter=debug

######################################################################################
# console appender  日志在控制输出配置
######################################################################################
log4j.appender.console=org.apache.log4j.consoleappender
log4j.appender.threshold=error
log4j.appender.console.target=system.out
log4j.appender.console.layout=org.apache.log4j.patternlayout
log4j.appender.console.layout.conversionpattern= [%p] %d %c - %m%n


######################################################################################
# dailyrolling file  每天产生一个日志文件,文件名格式:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.dailyrollingfileappender
log4j.appender.file.datepattern=yyyy-mm-dd
log4j.appender.file.file=log.log
log4j.appender.file.append=true
log4j.appender.file.threshold=error
log4j.appender.file.layout=org.apache.log4j.patternlayout
log4j.appender.file.layout.conversionpattern=%d{yyyy-m-d hh:mm:ss}%x[%5p](%f:%l) %m%n


log4j.logger.com.opensymphony.xwork2=error  

 

然后创建applicationcontext.xm

<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemalocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                       http://www.springframework.org/schema/tx
                       http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

  <!-- 加载properties文件 -->
  <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">
     <property name="driverclassname" value="${driver}"/>
     <property name="url" value="${url}"/>
     <property name="username" value="${username}"/>
     <property name="password" value="${password}"/>
  </bean>

  <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->
  <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
     <property name="datasource" ref="datasource"/>
     <!-- 扫描model包 -->
     <property name="typealiasespackage" value="com.lwy.pojo"/>
     <!-- 扫描sql配置文件:mapper需要的xml文件-->
     <property name="mapperlocations" value="classpath:mapper/*.xml"/>
  </bean>

  <!-- mapper动态代理开发,扫描dao接口包-->
  <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
     <!-- 注入sqlsessionfactory -->
     <property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/>
     <!-- 给出需要扫描dao接口包 -->
     <property name="basepackage" value="com.lwy.mapper"/>
  </bean>

  <!-- 事务管理 -->
  <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
     <!--数据库连接池-->
     <property name="datasource" ref="datasource"/>
  </bean>
</beans>

创建sping-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: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.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-3.0.xsd">

  <!-- 扫描注解,这样com.xjt包下的文件都能被扫描 -->
  <context:component-scan base-package="com.lwy"/>

  <!-- 开启springmvc注解模式 -->
  <mvc:annotation-driven/>

  <!-- 静态资源默认servlet配置 -->
  <mvc:default-servlet-handler/>

  <!-- 配置返回视图的路径,以及识别后缀是jsp文件 -->
  <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
     <property name="viewclass" value="org.springframework.web.servlet.view.jstlview"/>
     <property name="prefix" value="/"/>
     <property name="suffix" value=".jsp"/>
  </bean>
</beans>

接着在webapp下web-inf配置web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
        xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">

 <display-name>mvcdemo</display-name>


 <welcome-file-list>
   <welcome-file>/pages/index.jsp</welcome-file>
 </welcome-file-list>
 <!-- 注册servletcontext监听器,创建容器对象,并且将applicationcontext对象放到application域中 -->
 <listener>
   <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
 </listener>

 <!-- 指定spring核心配置文件 -->
 <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>

   <init-param>
     <param-name>forceencoding</param-name>
     <param-value>true</param-value>
   </init-param>
 </filter>
 <filter-mapping>
   <filter-name>characterencodingfilter</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>

 <!-- 配置前端控制器 -->
 <servlet>
   <servlet-name>springmvc</servlet-name>
   <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
   <!-- 指定配置文件位置和名称 如果不设置,默认找/web-inf/<servlet-name>-servlet.xml -->
   <init-param>
     <param-name>contextconfiglocation</param-name>
     <param-value>classpath:spring-mvc.xml</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
   <async-supported>true</async-supported>
 </servlet>

 <servlet-mapping>
   <servlet-name>springmvc</servlet-name>
   <url-pattern>*.do</url-pattern>
 </servlet-mapping>

</web-app>

数据库创建一个表

drop table if exists `user`;
create table `user` (
  `id` varchar(200) not null,
  `name` varchar(200) character set utf8 not null,
  `pwd` varchar(200) character set utf8 not null
) engine=innodb default charset=latin1;

可以先添加数据方便测试

insert into `user` values ('2', '22', '44');
insert into `user` values ('5', '123', '123');
insert into `user` values ('1', '123s', '123');

开始编写代码

pojo代码

package com.lwy.pojo;

public class user {
   private string id;

   public string getid() {
       return id;
   }

   public void setid(string id) {
       this.id = id;
   }

   private string name;
   private string pwd;

   public string getname() {
       return name;
   }

   public void setname(string name) {
       this.name = name;
   }

   public string getpwd() {
       return pwd;
   }

   public void setpwd(string pwd) {
       this.pwd = pwd;
   }
}

mapper

package com.lwy.mapper;

import com.lwy.pojo.user;
import org.apache.ibatis.annotations.param;

import java.util.list;

public interface usermapper {
   user userlogin(@param("name")string name, @param("pwd") string pwd);
   int adduser(user user);
   int delteuser(string id);
   int updateuser(user user);
   user getbyid(string id);
   list<user> getalluser();
}

xxmapper.xml

<?xml version="1.0" encoding="utf-8"?>
<!doctype mapper system "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lwy.mapper.usermapper">
   <resultmap id="resultmap" type="user">
       <id property="userid" column="user_id"></id>
       <result property="name" column="name"></result>
       <result property="pwd" column="pwd"></result>
   </resultmap>
   <select id="userlogin" resulttype="user">
     select * from `user` where `name`=#{name} and pwd=#{pwd}
   </select>

   <insert id="adduser" parametertype="user">
     insert into user(id,name,pwd) values(#{id},#{name},#{pwd})
   </insert>

   <delete id="delteuser" parametertype="string">
       delete from user where id=#{id}
   </delete>
   <update id="updateuser" parametertype="user">
     update user set name=#{name}, pwd=#{pwd} where id=#{id}
   </update>

   <select id="getbyid" parametertype="string" resultmap="resultmap">
     select * from user where id=#{id}
   </select>

   <select id="getalluser"  resultmap="resultmap">
       select * from user
   </select>
</mapper>

service层

package com.lwy.service;

import com.lwy.pojo.user;
import org.apache.ibatis.annotations.param;

import java.util.list;

public interface userservice {
   user userlogin(@param("name") string name, @param("pwd") string pwd);
   int adduser(user user);
   int delteuser(string id);
   int updateuser(user user);
   user getbyid(string id);
   list<user> getalluser();
}

实现

package com.lwy.service.impl;

import com.lwy.pojo.user;
import com.lwy.mapper.usermapper;
import com.lwy.service.userservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;

import java.util.list;
import java.util.uuid;

@service
public class userserviceimpl implements userservice {
   @autowired
   usermapper usermapper;
   @override
   public int adduser(user user) {
       string id =  uuid.randomuuid().tostring();
       user.setid(id);
       return usermapper.adduser(user);
   }

   @override
   public int delteuser(string id) {
       return usermapper.delteuser(id);
   }

   @override
   public int updateuser(user user) {
       return usermapper.updateuser(user);
   }

   @override
   public user getbyid(string id) {
       return usermapper.getbyid(id);
   }

   @override
   public list<user> getalluser() {
       return usermapper.getalluser();
   }


   @override
   public user userlogin(string name, string pwd) {

       return  usermapper.userlogin(name, pwd);
   }
}

controller层

package com.lwy.controller;

import com.lwy.pojo.user;
import com.lwy.service.userservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.requestmapping;

import java.util.list;

@controller
public class usercontroller {
   @autowired
   userservice userservice;

   @requestmapping("/login.do")
   public string  login(string username, string password,model model){
       system.out.println("开始登陆");
       userservice.userlogin(username,password);
//        system.out.println("开始查询所有用户");
//        list<user> userlist = userservice.getalluser();
//        model.addattribute("userlist",userlist);
       return "redirect:/getalluser.do";
   }

   @requestmapping("/adduser.do")
   public string adduser(user user){
       userservice.adduser(user);
       return "redirect:/getalluser.do";
   }

   @requestmapping("/deleteuser.do")
   public string deleteuser(string id){
       userservice.delteuser(id);
       return  "redirect:/getalluser.do";
   }

   @requestmapping("/updateuser.do")
   public string updateuser(user user){
       userservice.updateuser(user);
       return "redirect:/getalluser.do";
   }

   @requestmapping("/getbyid.do")
   public string getuserbyid(string id,model model){

       model.addattribute("user",userservice.getbyid(id));
       return "pages/user_update";
   }

   @requestmapping("/getalluser.do")
   public string getalluser(model model){
       system.out.println("开始查询所有用户");
       list<user> userlist = userservice.getalluser();
       model.addattribute("userlist",userlist);
       return "pages/userlist";
   }

}

部署到tomcat中

如图

选择本地的tomcat 利用idea创建一个基本的smm项目(带增删改查)

页面

登陆

<%--
  created by intellij idea.
  user: hasee
  date: 2019/6/3
  time: 16:03
  to change this template use file | settings | file templates.
--%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>

<html>

<head>
    <title>title</title>
</head>
<body>
<form action="../login.do" method="post">
    账号:<input type="text" name="username" />
    密码:<input type="password" name="password" />
    <button type="submit">提交</button>
</form>
</body>
</html>

显示

<%--
  created by intellij idea.
  user: hasee
  date: 2019/6/3
  time: 18:27
  to change this template use file | settings | file templates.
--%>
<%@ 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>
列表
<a href="/pages/user_add.jsp">添加</a>
<a href="/pages/logout.do">退出</a>
 <a href="/pages/admin.jsp">admin page</a>
<table>


    <tr>
        <td>id</td>
        <td>姓名</td>
        <td>密码</td>
        <td>操作</td>

    </tr>
    <c:foreach items="${requestscope.userlist}" var="list">
        <tr>
            <td>${list.id}</td>
            <td>${list.name}</td>
            <td>${list.pwd}</td>
            <td>
                <a href="../getbyid.do?id=${list.id}">修改</a>
                <a href="../deleteuser.do?id=${list.id}">删除</a>
            </td>

        </tr>
    </c:foreach>

</table>
</body>
</html>

添加

<%--
  created by intellij idea.
  user: hasee
  date: 2019/6/3
  time: 20:18
  to change this template use file | settings | file templates.
--%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>title</title>
</head>
<body>
<form method="post" action="../adduser.do">
你的账号<input type="text" name="name">
你的密码<input type="text" name="pwd" />
    <button type="submit">保存</button>
</form>
</body>
</html>

修改

<%--
  created by intellij idea.
  user: hasee
  date: 2019/6/3
  time: 20:18
  to change this template use file | settings | file templates.
--%>
<%@ 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 method="post" action="../updateuser.do">
    <input type="hidden" name="id" value="${requestscope.user.id}"/>
gfdshjsahsdhsdhsdhsd
    你的账号<input type="text" name="name" value="${requestscope.user.name}"/>
    你的密码<input type="text" name="pwd" value="${requestscope.user.pwd}"/>
    <button type="submit">修改</button>
</form>
</body>
</html>

 

利用idea创建一个基本的smm项目(带增删改查)利用idea创建一个基本的smm项目(带增删改查)利用idea创建一个基本的smm项目(带增删改查)