Maven+SSM框架实现简单的增删改查
spring介绍:
spring 使用基本的 javabean 来完成以前只可能由 ejb 完成的事情。然而, spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何java 应用都可以从 spring 中受益。 简单来说, spring 是一个轻量级的控制反转(ioc )和面向切面( aop )的容器框架。
springmvc介绍
spring mvc 属于 springframework 的后续产品,已经融合在spring web flow 里面。 spring mvc 分离了 控制器 、模型 对象 、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
mybatis介绍
mybatis 本是 apache 的一个开源项目 ibatis , 2010 年这个项目由apache software foundation 迁移到了 google code ,并且改名为 mybatis 。mybatis 是一个基于 java 的 持久层 框架。 ibatis 提供的 持久层 框架包括sql maps 和 data access objects ( dao ) mybatis 消除了几乎所有的 jdbc 代码和参数的手工设置以及结果集的检索。 mybatis 使用简单的 xml 或注解用于配置和原始映射,将接口和 java 的 pojos ( plain old java objects ,普通的 java 对象)映射成数据库中的记录。
首先不是maven架构整合的 ssm 框架
创建数据库、表db_zsl t_user user_t【最下面有sql语句】
1.项目整体结构
2.添加相关jar 包
3.项目整体结构出来了
4.创建model【user】
package comlytmodel; /** * 用户 * @author * */ public class user { private int id; private string username; private string age; @override public string tostring() { return "user [id=" + id + ", age=" + age + ", username=" + username + "]"; } public user(){ super(); } public int getid() { return id; } public void setid(int id) { thisid = id; } public string getage() { return age; } public void setage(string age) { thisage = age; } public string getusername() { return username; } public void setusername(string username) { thisusername = username; } public user(int id, string age, string username) { super(); thisid = id; thisage = age; thisusername = username; } }
5.创建dao接口【在mybatis中 mapper就相当于dao】
package comlytmapper; import javautillist; import comlytmodeluser; /** * 做为 dao的接口 * @author */ public interface usermapper { void save(user user); boolean update(user user); boolean delete(int id); user findbyid(int id); list<user> findall(); }
6.实现dao接口【mybatis中就是usermapper.xml文件】
<?xml version="0" encoding="utf-8"?> <!doctype mapper public "-//mybatisorg//dtd mapper 0//en" "http://mybatisorg/dtd/mybatis-3-mapperdtd"> <!-- namespace:必须与对应的接口全类名一致 usermapperjava id :必须与对应接口的某个对应的方法名一致即必须要和usermapperjava接口中的方法同名。 --> <mapper namespace="comlytmapperusermapper"> <insert id="save" parametertype="user"> insert into t_user(user_name,user_age) values(#{username},#{age}) </insert> <update id="update" parametertype="user"> update t_user set user_name=#{username},user_age=#{age} where user_id=#{id} </update> <delete id="delete" parametertype="int"> delete from t_user where user_id=#{id} </delete> <!-- mybsits_config中配置的alias类别名,也可直接配置resulttype为类路径 --> <select id="findbyid" parametertype="int" resulttype="user"> select user_id id,user_name username,user_age age from t_user where user_id=#{id} </select> <select id="findall" resulttype="user"> select user_id id,user_name username,user_age age from t_user </select> </mapper>
这里对这个xml文件作几点说明:
1、namespace必须与对应的接口全类名一致。
2、id必须与对应接口的某个对应的方法名一致即必须要和usermapper.java接口中的方法同名。
7.mybatis与spring整合【spring-common.xml】放在src的根目录下
对于mybatis和spring的整合是这篇博文的重点,需要配置的内容在下面有详细的解释。
<?xml version="0" encoding="utf-8"?> <beans xmlns="http://wwwspringframeworkorg/schema/beans" xmlns:xsi="http://wwwworg/2001/xmlschema-instance" xmlns:p="http://wwwspringframeworkorg/schema/p" xmlns:context="http://wwwspringframeworkorg/schema/context" xmlns:tx="http://wwwspringframeworkorg/schema/tx" xsi:schemalocation=" http://wwwspringframeworkorg/schema/beans http://wwwspringframeworkorg/schema/beans/spring-beans-xsd http://wwwspringframeworkorg/schema/context http://wwwspringframeworkorg/schema/context/spring-context-xsd http://wwwspringframeworkorg/schema/tx http://wwwspringframeworkorg/schema/tx/spring-tx-xsd"> <!-- mybatis和spring的整合 --> <!-- 数据源 : drivermanagerdatasource --> <bean id="datasource" class="orgspringframeworkjdbcdatasourcedrivermanagerdatasource"> <property name="driverclassname" value="commysqljdbcdriver" /> <property name="url" value="jdbc:mysql://localhost:3306/db_zsl" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- mybatis的sqlsession的工厂: sqlsessionfactorybean datasource:引用数据源 mybatis定义数据源,同意加载配置 --> <bean id="sqlsessionfactory" class="orgmybatisspringsqlsessionfactorybean"> <property name="datasource" ref="datasource"></property> <property name="configlocation" value="classpath:mybatis-configxml" /> </bean> <!-- mybatis自动扫描加载sql映射文件/接口 : mapperscannerconfigurer sqlsessionfactory basepackage:指定sql映射文件/接口所在的包(自动扫描) --> <bean class="orgmybatisspringmappermapperscannerconfigurer"> <property name="basepackage" value="comlytmapper"></property> <property name="sqlsessionfactory" ref="sqlsessionfactory"></property> </bean> <!-- 事务管理 : datasourcetransactionmanager datasource:引用上面定义的数据源 --> <bean id="txmanager" class="orgspringframeworkjdbcdatasourcedatasourcetransactionmanager"> <property name="datasource" ref="datasource"></property> </bean> <!-- 使用声明式事务 transaction-manager:引用上面定义的事务管理器 --> <tx:annotation-driven transaction-manager="txmanager" /> </beans>
8.mybatis配置文件【mybatis-config.xml】放在src目录下
<?xml version="0" encoding="utf-8"?> <!doctype configuration public "-//mybatisorg//dtd config 0//en" "http://mybatisorg/dtd/mybatis-3-configdtd"> <configuration> <!-- 实体类,简称 -设置别名 --> <typealiases> <typealias alias="user" type="comlytmodeluser" /> </typealiases> <!-- 实体接口映射资源 --> <!-- 说明:如果xxmapperxml配置文件放在和xxmapperjava统一目录下,mappers也可以省略,因为orgmybatisspringmappermapperfactorybean默认会去查找与xxmapperjava相同目录和名称的xxmapperxml --> <mappers> <mapper resource="com/lyt/mapper/usermapperxml" /> </mappers> </configuration>
配置log4j.properties
### set log levels ### log4jrootlogger = info , console , d #console log4jappenderconsole=orgapachelog4jconsoleappender log4jappenderconsolelayout=orgapachelog4jpatternlayout log4jappenderconsolelayoutconversionpattern=%d [%t] %-5p [%c] - %m%n log4jloggerjavasqlresultset=info log4jloggerorgapache=info log4jloggerjavasqlconnection=info log4jloggerjavasqlstatement=info log4jloggerjavasqlpreparedstatement=info #output2file log4jappenderd = orgapachelog4jdailyrollingfileappender log4jappenderdfile = d\:/logs/loglog log4jappenderdappend = true log4jappenderdthreshold = info \#\# \u00e8\u00be\u0093\u00e5\u0087\u00bainfo\u00e7\u00ba\u00a7\u00e5\u0088\u00ab\u00e4\u00bb\u00a5\u00e4\u00b8\u008a\u00e7\u009a\u0084\u00e6\u0097\u00a5\u00e5\u00bf\u0097 log4jappenderdlayout = orgapachelog4jpatternlayout log4jappenderdlayoutconversionpattern = %-d{yyyy-mm-dd hh\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n
10.整合springmvc
配置【spring-mvc.xml】放在src根目录下
<?xml version="0" encoding="utf-8"?> <beans xmlns="http://wwwspringframeworkorg/schema/beans" xmlns:xsi="http://wwwworg/2001/xmlschema-instance" xmlns:context="http://wwwspringframeworkorg/schema/context" xmlns:mvc="http://wwwspringframeworkorg/schema/mvc" xsi:schemalocation="http://wwwspringframeworkorg/schema/beans http://wwwspringframeworkorg/schema/beans/spring-beansxsd http://wwwspringframeworkorg/schema/context http://wwwspringframeworkorg/schema/context/spring-context-xsd http://wwwspringframeworkorg/schema/mvc http://wwwspringframeworkorg/schema/mvc/spring-mvc-xsd"> <!-- 注解扫描包 --> <context:component-scan base-package="comlytcontroller" /> <context:component-scan base-package="comlytservice" /> <!-- 开启注解 --> <mvc:annotation-driven /> <!-- 配置静态资源,直接映射到对应的文件夹,不被dispatcherservlet处理,04新增功能,需要重新设置spring-mvc-xsd --> <mvc:resources mapping="/img/**" location="/img/" /> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/html/**" location="/html/" /> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean id="viewresolver" class="orgspringframeworkwebservletviewinternalresourceviewresolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/web-inf/jsp/" /> <property name="suffix" value="jsp" /> </bean> </beans>
11.配置web.xml
<?xml version="0" encoding="utf-8"?> <web-app version="5" xmlns="http://javasuncom/xml/ns/javaee" xmlns:xsi="http://wwwworg/2001/xmlschema-instance" xsi:schemalocation="http://javasuncom/xml/ns/javaee http://javasuncom/xml/ns/javaee/web-app_2_xsd"> <!-- 加载spring容器配置 --> <listener> <listener-class>orgspringframeworkwebcontextcontextloaderlistener</listener-class> </listener> <!-- 设置spring容器加载所有的配置文件的路径 --> <context-param> <param-name>contextconfiglocation</param-name> <!-- <param-value>classpath:config/spring-*xml</param-value> --> <param-value>classpath:spring-commonxml,classpath:spring-mvcxml</param-value> </context-param> <!-- 配置springmvc核心控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>orgspringframeworkwebservletdispatcherservlet</servlet-class> <!-- 配置初始配置化文件,前面contextconfiglocation看情况二选一 --> <init-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:spring-commonxml,classpath:spring-mvcxml</param-value> </init-param> <!-- 启动加载一次 --> <load-on-startup>1</load-on-startup> </servlet> <!--为dispatcherservlet建立映射 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 此处可以可以配置成*do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 防止spring内存溢出监听器 --> <listener> <listener-class>orgspringframeworkwebutilintrospectorcleanuplistener</listener-class> </listener> <!-- 解决工程编码过滤器 --> <filter> <filter-name>encodingfilter</filter-name> <filter-class>orgspringframeworkwebfiltercharacterencodingfilter</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>encodingfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>indexjsp</welcome-file> </welcome-file-list> </web-app>
12.建立service以及service实现【userservice.java】
package comlytservice; import javautillist; import comlytmodeluser; public interface userservice { void save(user user); boolean update(user user); boolean delete(int id); user findbyid(int id); list<user> findall(); }
【userserviceimpl.java】
package comlytserviceimpl; import javautillist; import javaxannotationresource; import orgspringframeworkstereotypeservice; import orgspringframeworktransactionannotationtransactional; import comlytmapperusermapper; import comlytmodeluser; import comlytserviceuserservice; @service @transactional // 此处不再进行创建sqlsession和提交事务,都已交由spring去管理了。 public class userserviceimpl implements userservice { @resource private usermapper mapper; /** * 根据 id 删除 数据 */ public boolean delete(int id) { return mapperdelete(id); } /** * 查询user的全部数据 */ public list<user> findall() { list<user> findalllist = mapperfindall(); return findalllist; } /** * 根据 id 查询 对应数据 */ public user findbyid(int id) { user user = mapperfindbyid(id); return user; } /** * 新增数据 */ public void save(user user) { mappersave(user); } /** * 根据 id 修改对应数据 */ public boolean update(user user) { return mapperupdate(user); } }
13.建立controller【usercontroller.java】
package comlytcontroller; import javaioioexception; import javaioprintwriter; import javautillist; import javaxservlethttphttpservletrequest; import javaxservlethttphttpservletresponse; import orgspringframeworkbeansfactoryannotationautowired; import orgspringframeworkstereotypecontroller; import orgspringframeworkuimodel; import orgspringframeworkwebbindannotationrequestmapping; import comlytmodeluser; import comlytserviceuserservice; @controller @requestmapping("/user") public class usercontroller { @autowired private userservice userservice; /** * 获取所有用户列表 * @param request * @return */ @requestmapping("/getalluser") public string getalluser(httpservletrequest request,model model){ list<user> user = userservicefindall(); modeladdattribute("userlist", user); requestsetattribute("userlist", user); return "/alluser"; } /** * 跳转到添加用户界面 * @param request * @return */ @requestmapping("/toadduser") public string toadduser(){ return "/adduser"; } /** * 添加用户并重定向 * @param user * @param request * @return */ @requestmapping("/adduser") public string adduser(user user,model model){ userservicesave(user); return "redirect:/user/getalluser"; } /** *编辑用户 * @param user * @param request * @return */ @requestmapping("/updateuser") public string updateuser(user user,httpservletrequest request,model model){ if(userserviceupdate(user)){ user = userservicefindbyid(usergetid()); requestsetattribute("user", user); modeladdattribute("user", user); return "redirect:/user/getalluser"; }else{ return "/error"; } } /** * 根据id查询单个用户 * @param id * @param request * @return */ @requestmapping("/getuser") public string getuser(int id,httpservletrequest request,model model){ requestsetattribute("user", userservicefindbyid(id)); modeladdattribute("user", userservicefindbyid(id)); return "/edituser"; } /** * 删除用户 * @param id * @param request * @param response */ @requestmapping("/deluser") public void deluser(int id,httpservletrequest request,httpservletresponse response){ string result = "{\"result\":\"error\"}"; if(userservicedelete(id)){ result = "{\"result\":\"success\"}"; } responsesetcontenttype("application/json"); try { printwriter out = responsegetwriter(); outwrite(result); } catch (ioexception e) { eprintstacktrace(); } } }
至此 大部分架构以及代码已经搭建完成
我们来做前台页面--修改index.jsp
<%@ page language="java" import="javautil*" pageencoding="utf-8"%> <% string path = requestgetcontextpath(); string basepath = requestgetscheme() + "://" + requestgetservername() + ":" + requestgetserverport() + path + "/"; %> <!doctype html public "-//w3c//dtd html 01 transitional//en"> <html> <head> <base href="<%=basepath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <title>首页</title> </head> <body> <h5> <a href="<%=basepath%>user/getalluser" rel="external nofollow" >进入用户管理页</a> </h5> </body> </html>
在 web-inf 下新建jsp文件夹【里面新建以下文件】【adduser.jsp】【alluser.jsp】【edituser.jsp】
adduser.jsp内容
<%@ page language="java" import="javautil*" pageencoding="utf-8"%> <% string path = requestgetcontextpath(); string basepath = requestgetscheme()+"://"+requestgetservername()+":"+requestgetserverport()+path+"/"; %> <%@ taglib uri="http://javasuncom/jsp/jstl/core" prefix="c"%> <!doctype html public "-//w3c//dtd html 01 transitional//en"> <html> <head> <base href="<%=basepath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <title>添加用户</title> <script type="text/javascript"> function adduser(){ var form = documentforms[0]; formaction = "<%=basepath%>user/adduser"; formmethod="post"; formsubmit(); } </script> </head> <body> <h1><%=path%>添加用户<%=basepath%></h1> <form action="" name="userform"> 姓名:<input type="text" name="username"> 年龄:<input type="text" name="age"> <input type="button" value="添加" onclick="adduser()"> </form> </body> </html>
alluser.jsp
<%@ page language="java" import="javautil*" pageencoding="utf-8"%> <% string path = requestgetcontextpath(); string basepath = requestgetscheme()+"://"+requestgetservername()+":"+requestgetserverport()+path+"/"; %> <%@ taglib uri="http://javasuncom/jsp/jstl/core" prefix="c"%> <!doctype html public "-//w3c//dtd html 01 transitional//en"> <html> <head> <base href="<%=basepath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <script type="text/javascript" src="js/jquery-js"></script> <title>用户列表</title> <script type="text/javascript"> function del(id){ $get("<%=basepath%>user/deluser?id=" + id,function(data){ if("success" == dataresult){ alert("删除成功"); windowlocationreload(); }else{ alert("删除失败"); } }); } </script> </head> <body> <h6><a href="<%=basepath%>user/toadduser" rel="external nofollow" >添加用户</a></h6> <table border="1"> <tbody> <tr> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> <c:if test="${!empty userlist }"> <c:foreach items="${userlist}" var="user"> <tr> <td>${userusername }</td> <td>${userage }</td> <td> <a href="<%=basepath%>user/getuser?id=${userid}" rel="external nofollow" >编辑</a> <a href="javascript:del('${userid }')" rel="external nofollow" >删除</a> </td> </tr> </c:foreach> </c:if> </tbody> </table> </body> </html>
edituser.jsp
<%@ page language="java" import="javautil*" pageencoding="utf-8"%> <% string path = requestgetcontextpath(); string basepath = requestgetscheme()+"://"+requestgetservername()+":"+requestgetserverport()+path+"/"; %> <%@ taglib uri="http://javasuncom/jsp/jstl/core" prefix="c"%> <!doctype html public "-//w3c//dtd html 01 transitional//en"> <html> <head> <base href="<%=basepath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <title>编辑用户</title> <script type="text/javascript"> function updateuser(){ var form = documentforms[0]; formaction = "<%=basepath%>user/updateuser"; formmethod="post"; formsubmit(); } </script> </head> <body> <h1>添加用户</h1> <form action="" name="userform"> <input type="hidden" name="id" value="${userid }"/> 姓名:<input type="text" name="username" value="${userusername }"/> 年龄:<input type="text" name="age" value="${userage }"/> <input type="button" value="编辑" onclick="updateuser()"/> </form> </body> </html>
到此 简单的整合ssm 【基本的操作内容已经完成】
让你们看下界面运行,地址:http://localhost:8088/springmvc_spring_mybatis/
首页:
点击编辑进去:
点击添加进去:
由于我在网络问题 图片暂时没有上传上去。【现在我把图片都正上去了,希望多多支持】
对应的数据库 表
/* navicat mysql data transfer source server : localhost source server version : 50515 source host : localhost:3306 source database : db_zsl target server type : mysql target server version : 50515 file encoding : 65001 date: 2016-05-16 16:10:51 */ set foreign_key_checks=0; -- ---------------------------- -- table structure for `t_user` -- ---------------------------- drop table if exists `t_user`; create table `t_user` ( `user_id` int(11) not null auto_increment, `user_name` varchar(20) not null, `user_age` varchar(20) not null, primary key (`user_id`) ) engine=innodb auto_increment=10 default charset=utf8; -- ---------------------------- -- records of t_user -- ---------------------------- insert into `t_user` values ('2', '朱佳鹏', '25'); insert into `t_user` values ('3', '傻狍子', '150'); insert into `t_user` values ('4', 'jiuqiyuliang', '23'); insert into `t_user` values ('5', 'jiuqiyuliang', '23'); insert into `t_user` values ('6', 'jiuqiyuliang', '23'); insert into `t_user` values ('7', 'jiuqiyuliang', '23'); insert into `t_user` values ('9', 'liyintao123', '23123'); -- ---------------------------- -- table structure for `user_t` -- ---------------------------- drop table if exists `user_t`; create table `user_t` ( `id` int(11) not null auto_increment, `user_name` varchar(40) not null, `password` varchar(255) not null, `age` int(4) not null, primary key (`id`) ) engine=innodb auto_increment=2 default charset=utf8; -- ---------------------------- -- records of user_t -- ---------------------------- insert into `user_t` values ('1', '测试', 'sfasgfaf', '24');
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。