1、pom.xml配置
<!--jdbc访问--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- MYSQL驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- json支持 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency>
2、testController
package com.csp.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; @RestController public class testController { @Autowired private JdbcTemplate jdbcTemplate; @GetMapping("/test") public String getTest(){ return "hello,victor"; } @PostMapping("/register") public String reqTest(@RequestBody JSONObject req){ String userName = req.getString("userName"); String userPwd = req.getString("userPwd"); try{ String sql = "insert into users(username,userpassword)values(?,?)"; jdbcTemplate.update(sql,userName,userPwd); return "success"; }catch (Exception e){ return "failed"; } } @PostMapping("/login") public String login(@RequestBody JSONObject req){ String userName = req.getString("userName"); String userPwd = req.getString("userPwd"); try{ String sql = "select * from users where username = ? "; List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql,userName); if(maps.size()==0){ return "no user"; } else{ String pwd = (String) maps.get(0).get("userpassword"); if(pwd.equals(userPwd)){ return "success"; } else{ return "pwd error"; } } }catch (Exception e){ return "failed"; } } @GetMapping("/all") public List<Map<String, Object>> getqueryall(){ try{ String sql = "select * from users "; List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); System.out.println(maps); return maps; }catch (Exception e){ return null; } } }