SpringBoot實戰(二)-getParameter -setAttribute -Session -H2(Fail) -集成Mybatis

Servlet

中文教程:https://www.runoob.com/servlet/servlet-form-data.html

API:https://docs.oracle.com/cd/E17802_01/products/products/servlet/2.5/docs/servlet-2_5-mr2/javax/servlet/package-summary.html

Servlet 表單數據

GET 方法讀取表單數據

GET 方法是默認的從瀏覽器向 Web 服務器傳遞信息的方法,它會產生一個很長的字符串,出現在瀏覽器的地址欄中。

String getParameter(String name)
以字符串形式返回請求參數的值,或者如果參數不存在則返回 null。

使用 URL 的 GET 方法實例:

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                                        throws ServletException, IOException {
        ...
        String name =new String(request.getParameter("name");
        ...
}

/*通過request.getParameter方法獲取地址欄裏的參數*/

使用表單的 GET 方法實例:

<form action="HelloForm" method="GET">
網址名:<input type="text" name="name">
<br />
網址:<input type="text" name="url" />
<input type="submit" value="提交" />

使用表單的 POST 方法實例
和GET差不多

Servlet Cookie 處理
Cookie 剖析
Cookie 通常設置在 HTTP 頭信息中
Servlet 就能夠通過請求方法 request.getCookies() 訪問 Cookie,該方法將返回一個 Cookie 對象的數組。

Session 跟蹤
你需要在向客戶端發送任何文檔內容之前調用 request.getSession()。下面總結了 HttpSession 對象中可用的幾個重要的方法:

public void setAttribute(String name, Object value)
該方法使用指定的名稱綁定一個對象到該 session 會話。

public Object getAttribute(String name)
該方法返回在該 session 會話中具有指定名稱的對象,如果沒有指定名稱的對象,則返回 null。

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // 如果不存在 session 會話,則創建一個 session 對象
        HttpSession session = request.getSession(true);

        Integer visitCount = new Integer(0);
        String visitCountKey = new String("visitCount");
        session.setAttribute(visitCountKey, new Integer(0));

        visitCount = (Integer)session.getAttribute(visitCountKey);
        visitCount = visitCount + 1;
    }

 

加入Session:

@Controller
public class AuthorizeController {

    @Autowired
    private GithubProvider githubProvider;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletRequest request) {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();

        accessTokenDTO.setCode(code);
        accessTokenDTO.setClient_id("d91ecbf97a04759b945e");
        accessTokenDTO.setClient_secret("749a87845bceadf74377271113392a9eb0a70");
        accessTokenDTO.setRedirect_uri("http://localhost:8080/callback");
        accessTokenDTO.setState(state);

        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        GithubUser user = githubProvider.getUser(accessToken);
        
        if(user != null) {
            //登錄成功,寫cookie和session
            request.getSession().setAttribute("user", user);
            return "redirect:/";
        } else {
            //登錄失敗
            return "redirect:/";
        }
    }
}

 

使用thymeleaf語法:點擊“登錄”之後變成“我”

 搜索:thymeleaf session / thymeleaf瞭解thymeleaf的語法

<li class="dropdown" th:if="${session.user != null}">
                    
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">我<span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">消息中心</a></li>
                        <li><a href="#">個人資料</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">退出登錄</a></li>
                    </ul>
                </li>
                <li th:if="${session.user == null}">
                    
<a href="https://github.com/login/oauth/authorize?client_id=d91ecbf97a04759b945e&redirect_uri=http://localhost:8080/callback&scope=user&state=1">登錄</a>
               
</li>

 

把“我“改成用戶名

 

H2數據庫的使用:http://www.h2database.com/html/quickstart.html 


This database can be used in embedded mode, or in server mode. 
To use it in embedded mode, you need to:

Add the h2*.jar to the classpath (H2 does not have any dependencies)
Use the JDBC driver class: org.h2.Driver
The database URL jdbc:h2:~/test opens the database test in your user home directory
A new database is automatically created

使用IDEA內置數據庫(右邊豎條)

表user 

PS:H2密碼不對,換成mysql了

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/community?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=...
spring.datasource.password=...
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.12</version>
</dependency>

Git的錯誤Error: Failed connect to github.com:443解決辦法

集成mybatis:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

Maven

If you are using Maven just add the following dependency to your pom.xml:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

Quick Setup

As you may already know, to use MyBatis with Spring you need at least an SqlSessionFactory and at least one mapper interface.

MyBatis-Spring-Boot-Starter will:

  • Autodetect an existing DataSource //他會自動尋找Spring Boot裏存在的數據源
  • Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean
  • Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory
  • Auto-scan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans

Spring Boot數據源:https://docs.spring.io/spring-boot/docs/2.0.0.RC1/reference/htmlsingle/#using-boot-devtools 

If you use the spring-boot-starter-jdbc or spring-boot-starter-data-jpa “starters”,

you automatically get a dependency to HikariCP.

//如果您使用spring-boot-starter-jdbc或spring-boot-starter-data-jpa,則會自動獲得對HikariCP的依賴。

DataSource configuration is controlled by external configuration properties in spring.datasource.*. For example, you might declare the following section in application.properties:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

//在application.properties裏配置

回到Mybatis的QuickStart:創建MAPPER

Suppose we have the following mapper:

@Mapper
public interface CityMapper {

  @Select("SELECT * FROM CITY WHERE state = #{state}")
  City findByState(@Param("state") String state);

}

life.majiang.community.mapper.UserMapper

@Mapper
public interface UserMapper {
    @Insert("insert into user (name, account_id, token, gmt_create,gmt_modified) values (#{name}, #{accountId}, #{token}, #{gmtCreate}, #{gmtModified})")
    void insert(User user);
}
public class User {
    private Integer id;
    private String name;
    private String accountId;
    private String token;
    private Long gmtCreate;
    private Long gmtModified;
}

在Navicat裏獲取到了數據:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章