springboot 入門 踩坑 jdbc 代碼

#mysql配置信息
#spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false
spring.datasource.url=jdbc:mysql://localhost:3306/webtest?characterEncoding=utf-8&useSSL=true&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=mxy
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#server.context-path=/crud
spring.thymeleaf.cache=false




mybatis.config-location=classpath:config/mybatis-config.xml
mybatis.mapper-locations= classpath:mapper/*.xml


#porn.xml內容
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mxy</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>

        <java.version>1.8</java.version>
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
          <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>

        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>




      <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
      </dependency>


      <!--缺少此jar包,導致@Mapper註解無效-->
      <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.2.0</version>
      </dependency>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
      </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


//DemoApplicationTests.java
package com.mxy.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void contextLoads() {
    }
    @Test
    public void testMySql(){
        List<Map<String,Object>> result = jdbcTemplate.queryForList(
                "select * from ay_test");
        System.out.println("query result is"+result.size());
        System.out.println("success");
    }

}
#index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Signin Template for Bootstrap</title>
  <!-- Bootstrap core CSS -->
  <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
  <!-- Custom styles for this template -->
  <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
</head>

<body class="text-center">
<form class="form-signin" action="dashboard.html" th:action="@{/user/index}" method="post">
  <img class="mb-4" th:src="@{asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt=""
       width="72" height="72">
  <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
  <p style="color:orangered" th:text="#{msg}" th:if="${not #strings.isEmpty(msg) }"></p>
  <label class="sr-only">Username</label>
  <input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
  <br> <br>
  <label class="sr-only">Password</label>

  <input type="password" name="password" class="form-control" placeholder="Password" required="">
  <div class="checkbox mb-3">
    <label>
      <input type="checkbox" value="remember-me"> Remember me
    </label>
  </div>
  <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
  <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
  <a class="btn btn-sm">中文</a>
  <a class="btn btn-sm">English</a>
</form>

</body>

</html>

#LoginController
package com.mxy.demo;

import com.mysql.cj.util.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import  java.util.*;
import java.util.Map;

@Controller
public class LoginController {
    private JdbcTemplate jdbcTemplate;
    @PostMapping(value="/user/index")
    //@RequestMapping(value="/user/login",method= RequestMethod.POST)
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String,Object> map){
        if(!StringUtils.isNullOrEmpty(username)&&"123456".equals(password)){
          //  List<Map<String,Object>> result = jdbcTemplate.queryForList(
       //             "select * from ay_test");
         //   jdbcTemplate.execute("update ay_test set name='mxy'where id='2'");
            return "dashboard";
        }else{
            map.put("msg","用戶名密碼錯誤");
            return "index";
        }



    }
}

package com.mxy.demo.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(urlPatterns ="/=/login")
public class login extends HttpServlet {
  private static final long serialVersionUID = 1L;

  static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost:3306/rent?serverTimezone=UTC";
  static final String USER = "root";
  static final String PASS = "mxy";

  public login() {
    super();
    // TODO Auto-generated constructor stub
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("utf-8");

    Connection conn = null;
    Statement stmt = null;
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    PrintWriter out = response.getWriter();
    out.println("<p> " + username + "</p>");
    out.println("<p> " + "******" + "</p>");


    if (username.equals("admin") && password.equals("123")) {
      out.println("<p> " + "登陸成功" + "</p>");

    //response.sendRedirect("success.html");
      request.getRequestDispatcher("/success").forward(request, response);
   //request.getRequestDispatcher("/success").forward(request, response);
    }

    try {

      Class.forName("com.mysql.cj.jdbc.Driver");

      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      stmt = conn.createStatement();

      String sql;
      sql = "select “userName”,“password” from userinfo WHERE “userName”='" + username + "'  ";

      ResultSet rs = stmt.executeQuery(sql);

      out.println("賬號判斷完成");
      if (rs.next()) {
        out.println("查詢成功");
        String userName = rs.getString("“userName”");
        String passWord = rs.getString("“password”");
        out.println("查詢成功");
        out.println("<p>name2:" + userName + "</p>");
        out.println("<p>pwd2:" + passWord + "</p>");


        if (password.equals(passWord))
          //request.getRequestDispatcher("bin/main.html").forward(request, response);
          out.println("查詢成功");
        else

          out.println("賬號或密碼錯誤");

       // request.getRequestDispatcher("/errorServlet").forward(request, response);

      } else {
        //	out.println(" 對不起,沒有找到該圖書: " );

      }
      rs.close();
      stmt.close();
      conn.close();
    } catch (SQLException se) {

      se.printStackTrace();
    } catch (Exception e) {

      e.printStackTrace();
    } finally {

      try {
        if (stmt != null)
          stmt.close();
      } catch (SQLException se2) {
      }
      try {
        if (conn != null)
          conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      }
    }
  }

}

//HelloController
package com.mxy.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Map;

@Controller
public class HelloController {
    @RequestMapping({"/","/login.html"})
    public String index(){
        return "index";
    }
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "hello world";
    }

    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("hello","<h1>你好</h1>");
        map.put("users", Arrays.asList("zhangsan","lisi","wangwu"));
        return "success";
    }

  @RequestMapping("/test")
  public String test(Map<String,Object> map){
    map.put("hello","<h1>你好</h1>");
    map.put("users", Arrays.asList("zhangsan","lisi","wangwu"));
    return "test";
  }



}
發佈了19 篇原創文章 · 獲贊 3 · 訪問量 2205
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章