当前位置: 移动技术网 > IT编程>数据库>Mysql > SpringMVC+JDBC实现数据库操作

SpringMVC+JDBC实现数据库操作

2019年04月19日  | 移动技术网IT编程  | 我要评论

springmvc+jdbc实现操作。这段时间研究了下spring,确实很强大,对于数据库的操作也学习了一下,以jdbc为切入点,先把springjdbc的基本调用搞懂了,然后想编写个demo来操作jdbc调用my。本来想用android作为界面实现,但是既然用了spring,就顺便学一下springmvc,于是就有了下面这个小demo。由于只支持了mysql,就没有在考虑策略模式来支持多数据库,直接上来就是mysql的耦合连接。

先是用maven new一个webapp出来,然后配置工程的java build path为1.8,这样工程里就会自动出现我们需要的src/main/java文件夹。
整个工程的文件结构如下图:
\
工程建完以后配置pom:
pom.xml


  4.0.0
  com.xiakaihui.springmvc
  textbox
  war
  0.0.1-snapshot
  textbox maven webapp
  https://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    

    
    org.springframework
    spring-webmvc
    4.3.9.release
    

    
    javax.servlet
    javax.servlet-api
    4.0.0-b07
    

    
        mysql
        mysql-connector-java
        5.1.34
    

    
        org.springframework
        spring-jdbc
        4.3.9.release
    
  
  
    textbox
  

先把student这个最基本数据类建好:
student.java

package com.xiakaihui.springmvc;

public class student {
    private integer age;
    private string  name;
    private integer id;
    public integer getage() {
        return age;
    }
    public void setage(integer age) {
        this.age = age;
    }
    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public integer getid() {
        return id;
    }
    public void setid(integer id) {
        this.id = id;
    }

}

这样配置就可以了。spring-mvc会把spring里基本我们需要的包,包括spring-core、spring-context都自动配置进来,maven确实很人性化。
mysql-connector是为了建立mysql数据库连接的,而spring-jdbc可以让我们用spring提供的框架跟方便安全健壮得建立数据库连接和调用数据库。

既然是数据库操作,那就先把数据库操作的类给写好:

jdbcoperater.java

package com.xiakaihui.springmvc.jdbc;

import java.util.hashmap;
import java.util.list;
import java.util.map;

import com.xiakaihui.springmvc.student;

import org.springframework.jdbc.core.beanpropertyrowmapper;
import org.springframework.jdbc.core.namedparam.namedparameterjdbcdaosupport;
public class jdbcoperater extends namedparameterjdbcdaosupport {


    public void insertnamedparameter(student student) {
        string sql = "insert into student(id, name, age)"
                + "values(:id, :name, :age)";
        map parameters = new hashmap();
        parameters.put("name", student.getname());
        parameters.put("age", student.getage());
        parameters.put("id", student.getid());

        getnamedparameterjdbctemplate().update(sql, parameters);
    }

    public student findbystudentid(int id) {
        string sql = "select * from student where id = ?";
        student student = getjdbctemplate().queryforobject(sql, new object[] {id}, new beanpropertyrowmapper(student.class));
        return student;
    }

    public list findall() {
        string sql = "select * from student";

        list students = getjdbctemplate().query(sql, new beanpropertyrowmapper(student.class));
        return students;
    }

}

这里用了spring的getnamedparameterjdbctemplate,来直接对数据库插入我们所要的对象,getjdbctemplate也是很重要的spring jdbc操作类,这里用它查询数据库,它的queryforobject会根据我们的需求自动为我们封装对象值。
我们因尽量用spring提供的template方法来操作数据库,而不是自己根据mysql-connector-java来再写一套,当然用来学习下是可以。但是毕竟spring做的更加稳定,它处理异常和关闭连接也更加全面和安全。

接下来就是写好spring关于数据库调用的bean文件:

sping-database.xml



    
        
        
        
        
    
    
        
    

这里创建数据库时要注意,要这样create table **()charset utf8 collate utf8_general_ci;不然会出现java.sql.sqlexception: incorrect string value:
‘\xe6\x88\x91\xe7\x9a\x84…’ for column的错误,就是因为你传给数据库的是utf-8,但是建表的时候不是utf-8的,所以数据库不认就会抛异常。

数据库的操作已经写完了,然后我们把页面跳转给写好:
studentcontroller.java

package com.xiakaihui.springmvc;

import org.springframework.context.applicationcontext;
import org.springframework.context.configurableapplicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.modelattribute;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.servlet.modelandview;

import com.xiakaihui.springmvc.jdbc.jdbcoperater;

@controller
public class studentcontroller {

    @requestmapping(value="/student", method=requestmethod.get)
    public modelandview student() {
        student st = new student();
        return new modelandview("student", "command", st);
    }

    @requestmapping(value="/addstudent", method=requestmethod.post)
    public string addstudent(@modelattribute("springweb")student student, model model) {
        model.addattribute("name", student.getname());
        model.addattribute("age", student.getage());
        model.addattribute("id", student.getid());
        applicationcontext context = new classpathxmlapplicationcontext("spring-database.xml");
        jdbcoperater jdbcop = (jdbcoperater) context.getbean("student");
        jdbcop.insertnamedparameter(student);
        ((configurableapplicationcontext)context).close();
        return "result";
    }
}

这段代码的原理很简单,要注意的是这段代码:
((configurableapplicationcontext)context).close();要记得读完bean之后要把上下文给close掉,防止泄露。

好了,先是web制定servlet
web.xml



   helloworldspring

   
       spring-mvc
       
           org.springframework.web.servlet.dispatcherservlet
       
       1
      

   
       spring-mvc
       /
   

     
      
        set character encoding  
        org.springframework.web.filter.characterencodingfilter  
          
            encoding  
            utf-8  
          
          
            forceencoding  
            true  
          
      
      
        set character encoding  
        /*  
      
      

这个filter是我刚写的时候为了解决中文乱码问题的,这是网页显示的中文乱码问题,上面是解决数据库的中文乱码问题。

下面就是servlet的配置了
spring-mvc-servlet.xml




    
    

    
        
           /web-inf/jsp/
       

       
           .jsp
       
    

springmvc的controller类已经用了,基本的servlet配置也已近ok,接下来就是我们要跳转的两个jsp了:
student.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8"
    pageencoding="utf-8"%>
<%@taglib uri="https://www.springframework.org/tags/form" prefix="form" %>

学生信息

姓名:
年龄:
编号:

result.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8"
    pageencoding="utf-8"%>
<%@taglib uri="https://www.springframework.org/tags/form" prefix="form"%>

提交的学生信息如下

姓名 ${name}
年龄 ${age}
编号 ${id}

这里要注意<%@taglib uri=”https://www.springframework.org/tags/form” prefix=”form”%>这个配置,说明是表单,不然文本框无法显示。
还有编码都要改为utf-8,不然中文会乱码。

好了,这就是spring + jdbc + springmvc实现的简单demo虽然现在只写了一个插入,但是基本框架已经用了,查询接口已经预留好,以后随着对springmvc的理解会再完善这个demo。

但是实现这个小demo确实花了一个月时间,每天加完班去完健身房回到家看和敲一个多小时再睡觉。从对spring的一无所知,到能简单的通过spring调用数据库,再到对jdbc的深入学习,也顺便熟悉了mysql的基本语法,为了能够界面展示抛弃了用过的android,继续学习springmvc,最后搭出来这样一套数据库的调用。也多亏前段时间对设计模式和重构的理解,现在搞这种感觉都是围绕策略、工厂、模板等实现的,万变不离其宗。
最后附上最后程序运行结果,数据库里有几个是中文乱码,展示下是什么样的:
student

addstudent

这里写图片描述

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网