利用SpringMVC如何操作数据库并进行增删改查操作?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
虽然已经在做关于SpringMVC的项目。但是还没有写一些比较系统的博客。今天就先来说一说最简单的增删改查吧。这个例子是基于SpringMVC+Spring+Mybatis实现的。
环境配置
主要是几项配置:springmvc的配置,spring的配置,MyBatis的配置,jdbc的配置,和web.xml配置
springmvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- 文件扫描 --> <context:component-scan base-package="com.zhao"></context:component-scan> <!-- annotation-driven:默认创建了多个对象:RequestMappingHandlerMapping,RequestMappingHandlerAdapter 也就提供对json格式支持 --> <mvc:annotation-driven/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
beans.xml(Spring的配置)
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <context:component-scan base-package="com.zhao"></context:component-scan> <!-- 第一步:配置数据源 --> <context:property-placeholder location="classpath:jdbc.properties" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="driverClass" value="${jdbc.driver}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 第二步:创建sqlSessionFactory。生产sqlSession --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> </bean> <!-- 配置mybatis接口代理开发 * 接口类名和映射文件必须同名 * 接口类和映射文件必须在同一个目录 下 * 映射文件namespace名字必须是接口的全类路径名 * 接口的方法名必须和映射Statement的id一致 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zhao.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 第三步:事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 配置拦截service --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zhao.service.*.*(..))"/> </aop:config> </beans>
jdbc.properties(数据库jdbc的配置)
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc\:mysql\://localhost\:8888/blog jdbc.username=root jdbc.password=123456
web.xml的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <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> </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> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.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> </web-app>
spring的配置中已经添加了对数据源的支持。。在基础的应用中我们并不需要对MyBatis做什么配置。因此基本的配置就是如上所示。
增删改查的操作
首先是查的操作
列表显示所有信息
Controller层实现
@RequestMapping("/list") public String UserList(Model model) { List<User> list =userService.findAll(); //传递数据至前端 model.addAttribute("list",list); //返回对应视图 return "itemsList"; }
对应的Service实现层
@Override public List<User> findAll() { UserExample example = new UserExample(); List<User> list= userMapper.selectByExample(example); return list; }
前端页面实现细节
<table width="100%" border=1> <tr> <td>ID</td> <td>用户名</td> <td>密码</td> <td>昵称</td> <td>电子邮箱</td> <td>操作</td> </tr> <c:forEach items="${list}" var="item"> <tr> <td> <input type="checkbox" name="iduser" value="${item.iduser}"> </td> <td>${item.username }</td> <td>${item.password }</td> <td>${item.nickname }</td> <td>${item.email }</td> <td><a href="${pageContext.request.contextPath }/user/edit?iduser=${item.iduser}" rel="external nofollow" >修改</a> <a href="${pageContext.request.contextPath }/user/deleteByID?iduser=${item.iduser}" rel="external nofollow" >删除</a> </td> </tr> </c:forEach>
根据id修改相应的数据
Controller层实现
@RequestMapping("/edit") public String Edit(Integer iduser,Model model) { User user=userService.findById(iduser); model.addAttribute("item",user); return "editItem"; }
Service实现层实现
@RequestMapping("/edit") public String Edit(Integer iduser,Model model) { User user=userService.findById(iduser); //将要修改的值传递到前端 model.addAttribute("item",user); return "editItem"; } @RequestMapping(value ="/saveOrUpdate",method = RequestMethod.POST) public String saveOrUpdate(User user) { //保存修改的值 userService.update(user); //跳转到对应的list路由 return "redirect:list"; }
前端页面实现
<form id="itemForm" action="${pageContext.request.contextPath }/user/saveOrUpdate" method="post"> <input type="hidden" name="iduser" value="${item.iduser }"/> 修改商品信息: <table width="100%" border=1> <tr> <td>用户名称</td> <td><input type="text" name="username" value="${item.username }"/></td> </tr> <tr> <td>密码</td> <td><input type="text" name="password" value="${item.password}"/></td> </tr> <tr> <td>昵称</td> <td><input type="text" name="nickname" value="${item.nickname}"/></td> </tr> <tr> <td>email</td> <td><input type="text" name="email" value="${item.email}"/></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="提交"/> </td> </tr> </table> </form>
上述流程并未对是否查询成功做对应处理。有兴趣的同学可以尝试将其补充完整
根据id删除对应的数据
Controller层实现
@RequestMapping("/deleteByID") public String deleteByID(Integer iduser) { userService.deleteById(iduser); return "redirect:list"; }
Service实现层实现
@Override public void deleteById(Integer iduser) { // TODO Auto-generated method stub userMapper.deleteByPrimaryKey(iduser); }
前端页面上需要做的修改。已经在上述列表页面展示过了。在此不再赘述。
新增数据
Controller层实现
//超链接到对应的页面 @RequestMapping("/add") public String Add() { return "AddUser"; } //保存数据到数据库后跳转到列表页面 @RequestMapping("/addUser") public String Insert(User user) { userService.insert(user); return "redirect:list"; }
Service实现层实现
@Override public void insert(User user) { userMapper.insert(user); }
前端页面实现
<form id="itemForm" action="${pageContext.request.contextPath }/user/addUser" method="post"> 商品信息: <table width="100%" border=1> <tr> <td>用户名称</td> <td><input type="text" name="username"/></td> </tr> <tr> <td>密码</td> <td><input type="text" name="password"/></td> </tr> <tr> <td>昵称</td> <td><input type="text" name="nickname" /></td> </tr> <tr> <td>email</td> <td><input type="text" name="email"/></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="提交"/> </td> </tr> </table> </form>
看完上述内容,你们掌握利用SpringMVC如何操作数据库并进行增删改查操作的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。