2016-07-22 58 views
0

我正在尋找一種將用戶信息存儲在Spring MVC Web應用程序中的方法。例如,我有這樣的方法:存儲有關用戶的信息Spring MVC

public int getUserId() throws NumberFormatException, SQLException{ 

    //Create the connection and the statement 
    Connection conn = dataSource.getConnection(); 
    Statement statement = conn.createStatement(); 

    //Result set for getting/executing the query 
    ResultSet rs = statement.executeQuery("SELECT user_id FROM users WHERE username='UserHere'"); 

    while(rs.next()){ 
     return Integer.parseInt(rs.getString("user_id")); 
    } 

    //Return the results 
    return -1; 
} 

通過了Web應用程序,我調用此方法來獲取usersId,我只是在尋找一種方式來調用一次這個,一度被稱爲它存儲在一個變量/我可以通過Web應用程序訪問全球嗎?

也許在主頁上加載我可以有一個!=檢查引用這個信息的某個對象,如果它沒有被創建,它將被創建。這將發生一次,直到下次使用。

感謝

+0

無關提示使用'JdbcTemplate'而不是試圖用一個簡單的'DataSource'等工作二讀的參考指南章添加爲一個變量關於緩存。 –

回答

0

你可以在會話

@RequestMapping(..) 
public String controllerMethod(HttpSession session) { 
    session.addAttribute("userid", getUserId()); 
    ... 
}