JAVA_SSM整合_纯注解开发

一、准备数据库配置文件

jdbc.properties,建议username这个名字最好不要用,与系统中的名字有重合会出错,加前缀区分。注意:其中有些注解不明白了看我其他相关文章,里面有讲解

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db5?serverTimezone=GMT%2B8&useSSL=false
jdbc.username=root
jdbc.password=root

二、开始整合

2.1Spring整合Mybatis

2.1.1准备MybatisConfig注解配置类
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import java.util.Properties;

public class MybatisConfig {
    @Bean
    public SqlSessionFactoryBean getSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
//        开启驼峰命名
        Configuration configuration = new Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);

        //设置分页助手
        // LIMIT mysql和oracle语法不一样, 默认使用mysql
        PageInterceptor pageInterceptor = new PageInterceptor();
        pageInterceptor.setProperties(new Properties());
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageInterceptor});
        return sqlSessionFactoryBean;
    }
//和Mybatis的配置文件中的功能类似,用来扫描sql语句所在的包
    @Bean
    public MapperScannerConfigurer getMapper(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("cn.itheima.dao");
        return mapperScannerConfigurer;
    }
}
2.1.2准备jdbcConfig注解配置类
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.url}")
    private String url;

    @Bean//专门用于将第三方类放入Spring容器
    public DataSource getDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setUrl(url);
        return druidDataSource;
    }

    @Bean
    //开启事务管理
    public DataSourceTransactionManager getTransction(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
2.1.3准备SpirngConfig这个主要的注解类用来整合以上两个
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
// excludeFilters:用来过滤掉不想扫描的包
@ComponentScan(value = "cn.itheima",excludeFilters = @ComponentScan.Filter(Controller.class))
@Import({JdbcConfig.class,MybatisConfig.class})//将两个第三方类导入,交给spring管理
@PropertySource("classpath:jdbc.properties")//加载外部配置文件,可以让其中的内容让@Value注解使用
@EnableTransactionManagement
//@EnableAspectJAutoProxy,用来开启AOP的,不用时不开启
public class SpringConfig{

}

2.2将SpringMVC进行整合

2.2.1准备DispatcherServletConfig,tomcat会将请求交给DispatcherServlet进行处理,系统会自动使用。
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;

public class DispatcherServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
   //加载spring的ioc容器
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
//加载springmvc的ioc容器
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMVCConfig.class};
    }
//设置springmvc的管理路径
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    // 添加post请求过滤器,解决请求过程中的中文乱码问题,但不能解决返回中中文乱码的问题,放回乱码问题,交给了jackson-databind这个依赖处理了
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("utf-8");
        return new Filter[]{characterEncodingFilter};
    }
}
2.2.2准备SpringMVCConfig主配置类

Springmvc主要就是替代了servlet的功能,所以controller层就是用来前后端交互的

@Configuration
@EnableWebMvc
@ComponentScan({"cn.itheima.controller","cn.itheima.config"})
public class SpringMVCConfig {

}
2.2.3配置springMVC的路径过滤
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebSupport extends WebMvcConfigurationSupport {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
    }
}

2.3整合Spring和SpirngMVC

2.3.1其实已经整合过了,就是DispatcherServlet
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;

public class DispatcherServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMVCConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    // 添加post请求过滤器,解决请求过程中的中文乱码问题,但不能解决返回中中文乱码的问题
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("utf-8");
        return new Filter[]{characterEncodingFilter};
    }
}

SSM框架整合完毕。下面小案例开始使用,不讲解过程 三、SSM的小案例使用

3.1Dao层

import cn.itheima.pojo.Users;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;


public interface UserDao {
    @Insert("insert into users values(null,#{tbUsername},#{tbZhanghao},#{tbPassword},#{tbAge},#{tbGender},#{tbAddress},#{tbBirthday})")
    public void save(Users user);

    @Update("update users set tb_username=#{tbUsername},tb_zhanghao=#{tbZhanghao},tb_password=#{tbPassword},tb_age=#{tbAge},tb_gender=#{tbGender},tb_address=#{tbAddress},tb_birthday=#{tbBirthday} where tb_uid=#{tbUid} ")
    public void update(Users user);

    @Delete("delete from users where tb_uid=#{tbUid}")
    public void delete(Integer id);

    @Select("select * from users where tb_uid=#{tbUid}")
    public Users selectById(Integer id);

    @Select("select * from users")
    public List<Users> selectAll();

    /*
     * 手写,分页查询
     * */
    @Select("select * from users limit #{start},#{pageSize}")
    public List<Users> findByPage(@Param("start") int start, @Param("pageSize") int pageSize);

    // 查询总的数据数量
    @Select("select count(*) from users")
    public int totalPage();

}

3.2domain(pojo)层

3.2.1user:
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.stereotype.Repository;

import java.util.Date;

@Repository
public class Users {
    private Integer tbUid;
    private String tbUsername;
    private String tbZhanghao;
    private Integer tbPassword;
    private Integer tbAge;
    private String tbGender;
    private String tbAddress;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date tbBirthday;

    public Users() {
    }

    public Users(Integer tbUid, String tbUsername, String tbZhanghao, Integer tbPassword, Integer tbAge, String tbGender, String tbAddress, Date tbBirthday) {
        this.tbUid = tbUid;
        this.tbUsername = tbUsername;
        this.tbZhanghao = tbZhanghao;
        this.tbPassword = tbPassword;
        this.tbAge = tbAge;
        this.tbGender = tbGender;
        this.tbAddress = tbAddress;
        this.tbBirthday = tbBirthday;
    }

    @Override
    public String toString() {
        return "Users{" +
                "tbUid=" + tbUid +
                ", tbUsername='" + tbUsername + '\'' +
                ", tbZhanghao='" + tbZhanghao + '\'' +
                ", tbPassword=" + tbPassword +
                ", tbAge=" + tbAge +
                ", tbGender='" + tbGender + '\'' +
                ", tbAddress='" + tbAddress + '\'' +
                ", tbBirthday=" + tbBirthday +
                '}';
    }

    public Integer getTbUid() {
        return tbUid;
    }

    public void setTbUid(Integer tbUid) {
        this.tbUid = tbUid;
    }

    public String getTbUsername() {
        return tbUsername;
    }

    public void setTbUsername(String tbUsername) {
        this.tbUsername = tbUsername;
    }

    public String getTbZhanghao() {
        return tbZhanghao;
    }

    public void setTbZhanghao(String tbZhanghao) {
        this.tbZhanghao = tbZhanghao;
    }

    public Integer getTbPassword() {
        return tbPassword;
    }

    public void setTbPassword(Integer tbPassword) {
        this.tbPassword = tbPassword;
    }

    public Integer getTbAge() {
        return tbAge;
    }

    public void setTbAge(Integer tbAge) {
        this.tbAge = tbAge;
    }

    public String getTbGender() {
        return tbGender;
    }

    public void setTbGender(String tbGender) {
        this.tbGender = tbGender;
    }

    public String getTbAddress() {
        return tbAddress;
    }

    public void setTbAddress(String tbAddress) {
        this.tbAddress = tbAddress;
    }

    public Date getTbBirthday() {
        return tbBirthday;
    }

    public void setTbBirthday(Date tbBirthday) {
        this.tbBirthday = tbBirthday;
    }
}

3.2.2pageDao
import org.springframework.stereotype.Repository;

import java.util.List;

/*
* 前端需要给的就是,总页数和,查询到的数据集合
* */
@Repository
public class PageDao<T> {
    private List<T> user;
    private double totalPages;

    public PageDao() {
    }

    public PageDao(List<T> user, double totalPages) {
        this.user = user;
        this.totalPages = totalPages;
    }

    public List<T> getUser() {
        return user;
    }

    public void setUser(List<T> user) {
        this.user = user;
    }

    public double getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(double totalPages) {
        this.totalPages = totalPages;
    }

    @Override
    public String toString() {
        return "PageDao{" +
                "user=" + user +
                ", totalPages=" + totalPages +
                '}';
    }
}

3.3service层:

3.3.1userService:
import cn.itheima.pojo.Users;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Transactional
public interface UserService {

    public boolean save(Users user);

    public boolean update(Users user);

    public boolean delete(Integer id);

    public Users selectById(Integer id);

    public List<Users> selectAll();
//分页助手
    PageInfo<Users> selectByPage(int currentPage, int pageSize);
//    手写分页查询
    List<Users> findByPage(double start,double pageSize);
//    总数
    double totalPages();

}
3.3.2userServiceimpl
import cn.itheima.dao.UserDao;
import cn.itheima.pojo.Users;
import cn.itheima.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public boolean save(Users user) {
        userDao.save(user);
        return true;
    }

    @Override
    public boolean update(Users user) {
        userDao.update(user);
        return true;
    }

    @Override
    public boolean delete(Integer id) {
        userDao.delete(id);
        return true;
    }

    @Override
    public Users selectById(Integer id) {

        return userDao.selectById(id);
    }

    @Override
    public List<Users> selectAll() {

        return userDao.selectAll();
    }

    @Override
    public PageInfo<Users> selectByPage(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Users> list = userDao.selectAll();
        System.out.println(list);
        PageInfo<Users> pi = new PageInfo<>(list);
        return pi;
    }

    @Override
    public double totalPages() {
        return userDao.totalPage();
    }

    @Override
    public List<Users> findByPage(double start, double pageSize) {
//        但是用在sql语句中(userDao)的数据需要是int类型,所以强转一下
        List<Users> usersList = userDao.findByPage((int)start, (int)pageSize);
        return usersList;
    }
}

3.4controller层

import cn.itheima.controller.controllerUtil.Code;
import cn.itheima.controller.controllerUtil.Result;
import cn.itheima.pojo.PageDao;
import cn.itheima.pojo.Users;
import cn.itheima.service.UserService;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;


    @GetMapping("/test")
    public String test() {
        return "ok";
    }

    @PostMapping
    public Result saveUser(@RequestBody Users user) {
        String msg;
        Result result;
        boolean save = userService.save(user);
        if (save) {
            msg = "success";
            result = new Result(save, Code.UPDATE_OK, msg);
        } else {
            msg = "保存失败";
            result = new Result(save, Code.UPDATE_ERR, msg);
        }

        return result;
    }

    @PutMapping
    public Result update(@RequestBody Users user) {
        String msg;
        Result result;
        boolean update = userService.update(user);
        if (update) {
            msg = "success";
            result = new Result(update, Code.UPDATE_OK, msg);
        } else {
            msg = "修改失败";
            result = new Result(update, Code.UPDATE_ERR, msg);
        }

        return result;
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        Result result;
        String msg;
        boolean delete = userService.delete(id);
        if (delete) {
            msg = "success";
            result = new Result(delete, Code.UPDATE_OK, msg);
        } else {
            msg = "删除失败";
            result = new Result(delete, Code.UPDATE_ERR, msg);
        }
        return result;
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        Result result;
        String msg;
        Users users = userService.selectById(id);
        System.out.println("按id查询"+users);
        if (users != null) {
            msg = "success";
            result = new Result(users, Code.SELECT_OK, msg);
        } else {
            msg = "查询失败";
            result = new Result(Code.SELECT_ERR, msg);
        }
        return result;
    }

    @GetMapping
    public Result selectAll() {
        String msg;
        Result result;
        List<Users> users = userService.selectAll();
        if (users != null) {
            msg = "success";
            result = new Result(users, Code.SELECT_OK, msg);
        } else {
            msg = "查询失败";
            result = new Result(Code.SELECT_ERR, msg);
        }
        return result;
    }
// 使用分页助手
/*    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable int currentPage, @PathVariable int pageSize) {
        System.out.println(currentPage);
        System.out.println(pageSize);
        PageInfo<Users> pi = userService.selectByPage(currentPage, pageSize);
        Result result = new Result(pi,Code.SELECT_OK,"");
        return result;
    }*/
//    手写分页查询
@GetMapping("/{currentPage}/{pageSize}")
public Result selectByPage(@PathVariable int currentPage, @PathVariable double pageSize) {
    double start = (currentPage-1)*pageSize;
//    分页查出的集合
    List<Users> usersList = userService.findByPage(start, pageSize);
//    数据总条目数
//    向上取整
    double sum = Math.ceil(userService.totalPages()/pageSize);
    PageDao pageDao = new PageDao(usersList,sum);
    Result result = new Result(pageDao,Code.SELECT_OK,"");
    return result;
}
}

3.4.1为使发送给前端的数据统一所以使用Result工具类

Result.java:

public class Result {
    public Object data;
    public String code;
    public String msg;

    public Result() {
    }

    public Result(Object data, String code) {
        this.data = data;
        this.code = code;
    }

    public Result(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Result(Object data, String code, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
3.4.2为了使通知 状态码容易理解特别写出一个类Code,写成接口就是默认final修饰
public interface Code {
    /**
     * 0结尾是成功
     * 1结尾是失败
     * 需要别的就继续往上添加
     */
    String SELECT_OK = "200";
    String SELECT_ERR = "201";

    String UPDATE_OK = "300";
    String UPDATE_ERR = "301";
}

后端逻辑写完

四、前端使用基础Vue,没有element-ui,不太会

前端展示分页展示页面:user.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
</head>
<body>
<div id="userContains">
    <table border="1px" cellspacing="0px" width="100%">
        <tr>
            <th>编号</th>
            <th>名称</th>
            <th>账号</th>
            <th>密码</th>
            <th>年龄</th>
            <th>性别</th>
            <th>住址</th>
            <th>生日</th>
            <th>操作</th>
        </tr>
        <tr v-for="(user,i) in users">
            <!--i表示索引,从0开始-->
            <td>{{i+1}}</td>
            <td>{{user.tbUsername}}</td>
            <td>{{user.tbZhanghao}}</td>
            <td>{{user.tbPassword}}</td>
            <td>{{user.tbAge}}</td>
            <td v-if="user.tbGender=='0'"></td>
            <td v-if="user.tbGender=='1'"></td>
            <td>{{user.tbAddress}}</td>
            <td>{{user.tbBirthday}}</td>
            <td><a href="#" @click="updateUser(user.tbUid)">编辑</a> |<a href="#" @click="deleteUser(user.tbUid)">删除</a></td>
        </tr>
    </table>

    <div>
        <a href="" @click.prevent="changePage(page)" v-for="page in pageDate.totalPage">{{page}}&nbsp</a>
    </div><br>
    <div>
        <a href="/day05_SSM/pages/addUser.html">添加用户</a>
    </div>
</div>


<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: "#userContains",
        data() {
            return {
                users:[],
                pageDate:{
                    currentPage:1.0,
                    pageSize:2.0,
                    totalPage:0,
                    total:0,
                }
            }
        },
        methods: {
            findAll() {
                var _this = this
                axios({
                    method: "get",
                    url: "/day05_SSM/users",
                }).then(function (resp) {

                    _this.users = resp.data.data
                })
            },

            findByPage(){
                var _this = this
                // 分页助手版,分页查询
                /*axios({
                    method: "get",
                    url: "/day05_SSM/users/"+_this.pageDate.currentPage+"/"+_this.pageDate.pageSize,
                }).then(function (resp) {
                    console.log(resp.data.data);
                    _this.users = resp.data.data.list
                    _this.pageDate.total = resp.data.data.total
                    _this.pageDate.totalPage = resp.data.data.pages
                })*/
            //    手写版分页查询
                axios({
                    method:"get",
                    url: "/day05_SSM/users/"+_this.pageDate.currentPage+"/"+_this.pageDate.pageSize,
                }).then(function (resp){
                    _this.users = resp.data.data.user
                    _this.pageDate.totalPage = resp.data.data.totalPages
                })
            },

            changePage(currentPage){
                  this.pageDate.currentPage = currentPage;
                  this.findByPage();
            },
            deleteUser(uid){
                axios({
                    method:"delete",
                    url:"/day05_SSM/users/"+uid
                }).then(function (resp){
                   alert( resp.data.msg)
                })
            },
            updateUser(uid){
                location.href="/day05_SSM/pages/updateUser.html?id="+uid;
            }

        },
        mounted() {
            //this.findAll();
            this.findByPage();
        }
    })
</script>
<script>

</script>
</body>
</html>
用户添加页面:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加操作</title>
</head>
<body>
<div id="addContains">
    <form id="form" action="" method="post">
        用户名:<input type="text" id="username" v-model="user.tbUsername"><br>
        账号:<input type="text" id="zhanghao" v-model="user.tbZhanghao"><br>
        密码:<input type="password" id="password" v-model="user.tbPassword"><br>
        性别:<input type="radio" value="0" v-model="user.tbGender"><input type="radio" value="1" v-model="user.tbGender"><br>
        地址:<input type="text" id="address" v-model="user.tbAddress"><br>
        年龄:<input type="text" id="age" v-model="user.tbAge"><br>
        生日:<input type="date" id="birthday" v-model="user.tbBirthday"><br>
        <button type="button" id="bt" value="bt" @click="adduser()">添加</button>
    </form>
</div>
<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>

<script>
    let vue = new Vue({
        el: "#addContains",
        data() {
            return {
                user: {
                    tbUsername: "",
                    tbZhanghao: "",
                    tbPassword: "",
                    tbGender: "",
                    tbAddress: "",
                    tbAge: "",
                    tbBirthday: "",
                },
                code: {
                    checkCode: ""
                }
            };
        },
        methods: {
            adduser() {
                axios({
                    method:"post",
                    url:"/day05_SSM/users",
                    data:vue.user
                }).then(function (resp){
                     if(resp.data.msg == "success"){
                         location.href="/day05_SSM/pages/user.html"
                     }else{
                         alert("这测失败");
                     }
                })
            }
        }
    });

</script>
</body>
</html>
用户修改页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="updateContains">
    <form id="form" action="" method="post">
        <input type="hidden" id="uid" v-model="user.tbUid">
        用户名:<input type="text" id="username" v-model="user.tbUsername"><br>
        账号:<input type="text" id="zhanghao" v-model="user.tbZhanghao"><br>
        密码:<input type="password" id="password" v-model="user.tbPassword"><br>
        性别:<input type="radio" value="0" v-model="user.tbGender"><input type="radio" value="1" v-model="user.tbGender"><br>
        地址:<input type="text" id="address" v-model="user.tbAddress"><br>
        年龄:<input type="text" id="age" v-model="user.tbAge"><br>
        生日:<input type="date" id="birthday" v-model="user.tbBirthday"><br>
        <button type="button" id="bt" value="bt" @click="updateuser()">修改</button>
    </form>
</div>
<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>

<script>
    C1 = window.location.href.split("?")[1];
    uid = C1.split("=")[1];

    let vue = new Vue({
        el: "#updateContains",
        data() {
            return {
                user: {
                    tbUid:"",
                    tbUsername: "",
                    tbZhanghao: "",
                    tbPassword: "",
                    tbGender: "",
                    tbAddress: "",
                    tbAge: "",
                    tbBirthday: "",
                },
                code: {
                    checkCode: ""
                }
            };
        },
        methods: {
            findById() {
                var _this = this
                axios({
                    method: "get",
                    url: "/day05_SSM/users/" + uid
                }).then(function (resp) {
                    _this.user.tbUid = resp.data.data.tbUid
                    _this.user.tbUsername = resp.data.data.tbUsername
                    _this.user.tbZhanghao = resp.data.data.tbZhanghao
                    _this.user.tbPassword = resp.data.data.tbPassword
                    _this.user.tbGender = resp.data.data.tbGender
                    _this.user.tbAddress = resp.data.data.tbAddress
                    _this.user.tbAge = resp.data.data.tbAge
                    _this.user.tbBirthday = resp.data.data.tbBirthday
                })
            },
            updateuser() {
                axios({
                    method: "put",
                    url: "/day05_SSM/users",
                    data: vue.user
                }).then(function (resp) {
                    if (resp.data.msg == "success") {
                        location.href = "/day05_SSM/pages/user.html"
                    } else {
                        alert("这测失败");
                    }
                })
            }
        },
        mounted() {
           this.findById();
        }
    });

</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值