环境 idea jdk1.8 tomcat mysql
打开idea选择创建一个maven项目
然后点击next,next,finsh
然后看项目的结构
如图所示
接着创建com包,再在com包下新建四个包,分别命名为:
自定义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.0modelVersion> <groupId>com.ligroupId> <artifactId>ssm_test_2artifactId> <version>1.0-SNAPSHOTversion> <packaging>warpackaging> <name>ssm_test_2 Maven Webappname> <properties> <srping.version>4.0.2.RELEASEsrping.version> <mybatis.version>3.2.8mybatis.version> <slf4j.version>1.7.12slf4j.version> <log4j.version>1.2.17log4j.version> <druid.version>1.0.9druid.version> properties> <dependencies> <dependency> <groupId>javax.servletgroupId> <artifactId>javax.servlet-apiartifactId> dependency> <dependency> <groupId>javax.servlet.jspgroupId> <artifactId>javax.servlet.jsp-apiartifactId> <version>2.3.1version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.11version> <scope>testscope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-coreartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-oxmartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aopartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-context-supportartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-expressionartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-ormartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${srping.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${srping.version}version> 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>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>5.1.35version> 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>org.slf4jgroupId> <artifactId>slf4j-apiartifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-log4j12artifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>${druid.version}version> dependency> dependencies> <build> <resources> <resource> <directory>src/main/javadirectory> <includes> <include>**/*.propertiesinclude> <include>**/*.xmlinclude> includes> <filtering>falsefiltering> resource> <resource> <directory>src/main/resourcesdirectory> <includes> <include>**/*.propertiesinclude> <include>**/*.xmlinclude> includes> <filtering>falsefiltering> resource> resources> <plugins> <plugin> <groupId>org.apache.maven.pluginsgroupId> <artifactId>maven-compiler-pluginartifactId> <version>3.2version> <configuration> <source>1.8source> <target>1.8target> <encoding>UTF-8encoding> 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"> <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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="com.lwy.pojo"/> <property name="mapperLocations" value="classpath:mapper/*.xml"/> bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <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"> <context:component-scan base-package="com.lwy"/> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <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>mvcDemodisplay-name> <welcome-file-list> <welcome-file>/pages/index.jspwelcome-file> welcome-file-list> <listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class> listener> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:applicationContext.xmlparam-value> context-param> <filter> <filter-name>CharacterEncodingFilterfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <init-param> <param-name>encodingparam-name> <param-value>utf-8param-value> init-param> <init-param> <param-name>forceEncodingparam-name> <param-value>trueparam-value> init-param> filter> <filter-mapping> <filter-name>CharacterEncodingFilterfilter-name> <url-pattern>/*url-pattern> filter-mapping> <servlet> <servlet-name>springmvcservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:spring-mvc.xmlparam-value> init-param> <load-on-startup>1load-on-startup> <async-supported>trueasync-supported> servlet> <servlet-mapping> <servlet-name>springmvcservlet-name> <url-pattern>*.dourl-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); ListgetallUser(); }
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); ListgetallUser(); }
实现
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 ListgetallUser() { 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("开始查询所有用户"); // Listuserlist = 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("开始查询所有用户"); Listuserlist = userService.getallUser(); model.addAttribute("userlist",userlist); return "pages/userlist"; } }
部署到tomcat中
如图
页面
登陆
<%-- 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" %>Title
显示
<%-- 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>Titletitle> head> <body> 列表 <a href="/pages/user_add.jsp">添加a> <a href="/pages/logout.do">退出a> <a href="/pages/admin.jsp">admin pagea> <table> <tr> <td>idtd> <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>Titletitle> 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>Titletitle> 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>