1. 程式人生 > 資料庫 >資料庫查詢語句

資料庫查詢語句

01.為什麼要資料庫連線池


為了避免頻繁的建立資料庫連線,資料庫連線池應運而生。資料庫連線池負責分配、管理和釋放資料庫連線。它允許應用程式重複使用現有的資料庫連線,而不是重新建立。

資料庫連線池在初始化的時候建立一定數量的資料庫連線放到資料庫連線池中,當應用程式訪問時向連線池申請一個Connection。如果有空閒的Connection,則將其返回,否則建立新的Connection。使用完畢後,連線池會將該Connection收回,交付給其它執行緒使用,以減少建立資料庫連線的次數,提高資料庫訪問的效率。

資料庫連線池
概念:其實就是一個容器(集合),存放資料庫連線的容器。
特點:節約了資源,使用者訪問高效。

02.資料庫連線池的實現

標準介面:DataSource介面
在javax.sql包下。
為了獲取資料庫連線物件,JDBC提供了javax.sql。DataSource介面,他負責與資料庫建立連線,並定義了返回值為Connection物件的方法。
1.方法:

[plain]view plaincopy
  1. 獲取連線:
  2. ConnectiongetConnection()
  3. ConnectiongetConnection(Stringusername,Stringpassword)
  4. 歸還連線:如果連線物件Connection時是從連線池中獲取的,
  5. 那麼呼叫Connection.close()方法,則不會再關閉連線了。
  6. 而是歸還連線

2.一般我們不去實現它,由資料庫廠商來實現。
通常把實現了DataSource介面的類稱為資料來源,資料來源儲存了所有建立資料庫連線的資訊。資料來源中包含資料庫連線池。
常用的

03.C3P0:資料庫連線池技術

步驟:
1.匯入jar包:c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar

2.定義配置檔案(自動載入)
名稱:c3p0.properties 或者 c3p0-config.xml
路徑:直接將檔案放在src目錄下。

3.建立核心物件,資料庫連線池物件 ComboPooledDataSource

DataSourceds=newComboPooledDataSource();

4.獲取資料庫連線物件

Connectionconn=ds.getConnection();

5.剩下操作跟基本操作相同。

[plain]view plaincopy
  1. @WebServlet("/C3p0ServletTest1")publicclassC3p0ServletTest1extendsHttpServlet{
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  3. request.setCharacterEncoding("utf-8");
  4. response.setContentType("text/html;charset=utf-8");
  5. PrintWriterout=response.getWriter();
  6. //1.建立資料庫連線池物件
  7. DataSourceds=newComboPooledDataSource();
  8. Connectionconn=null;
  9. PreparedStatementpstat=null;
  10. ResultSetrs=null;
  11. try{
  12. //2.獲取連線物件
  13. conn=ds.getConnection();
  14. //3.定義sql
  15. Stringsql="select*fromstudentwheresex=?";
  16. //4.獲取執行sql的物件
  17. pstat=conn.prepareStatement(sql);
  18. pstat.setString(1,"男");
  19. //5.執行sql
  20. rs=pstat.executeQuery();
  21. while(rs.next()){
  22. Stringsequence=rs.getString("sequence");
  23. Stringname=rs.getString("name");
  24. Stringsex=rs.getString("sex");
  25. out.println("<p>"+sequence+""+name+""+sex+"<p>");
  26. }
  27. }catch(SQLExceptionthrowables){
  28. throwables.printStackTrace();
  29. }finally{
  30. try{
  31. if(rs!=null){
  32. rs.close();
  33. }
  34. }catch(SQLExceptionthrowables){
  35. throwables.printStackTrace();
  36. }
  37. if(pstat!=null){
  38. try{
  39. pstat.close();
  40. }catch(SQLExceptionthrowables){
  41. throwables.printStackTrace();
  42. }
  43. }
  44. if(conn!=null){
  45. try{
  46. conn.close();
  47. }catch(SQLExceptionthrowables){
  48. throwables.printStackTrace();
  49. }
  50. }
  51. }
  52. }
  53. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throws
  54. ServletException,IOException{
  55. doPost(request,response);
  56. }}

04.Druid:資料庫連線池實現技術

Druid由阿里巴巴提供。

步驟:
1.匯入jar包:druid-1.0.9.jar。

2.定義配置檔案:
是proporties形式。
名稱:可以交任意名稱,可以放在任意目錄下(需要手動載入)

3.獲取資料庫連線池物件:通過工廠類來獲取
DruidDataSourceFactory

4.獲取連線

5.其他的步驟相同

[plain]view plaincopy
  1. @WebServlet("/DruidServletTest1")publicclassDruidServletTest1extendsHttpServlet{
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  3. request.setCharacterEncoding("utf-8");
  4. response.setContentType("text/html;charset=utf-8");
  5. PrintWriterout=response.getWriter();
  6. DataSourceds=null;
  7. Connectionconn=null;
  8. PreparedStatementpstat=null;
  9. //1.載入配置檔案
  10. Propertiespro=newProperties();
  11. InputStreamis=DruidServletTest1.class.getClassLoader().getResourceAsStream("druid.properties");
  12. pro.load(is);
  13. //2.獲取連線池物件
  14. try{
  15. ds=DruidDataSourceFactory.createDataSource(pro);
  16. }catch(Exceptione){
  17. e.printStackTrace();
  18. }
  19. try{
  20. //5.獲取連線
  21. conn=ds.getConnection();
  22. //3.定義sql
  23. Stringsql="updatestudentsetname=?wherebirthday=?";
  24. //4.獲取執行sql的物件
  25. pstat=conn.prepareStatement(sql);
  26. pstat.setString(1,"夢陽辰");
  27. pstat.setString(2,"1999-10-18");
  28. //5.執行sql
  29. intcount=pstat.executeUpdate();
  30. if(count>0){
  31. out.print("修改成功!");
  32. }else{
  33. out.print("修改失敗!");
  34. }
  35. }catch(SQLExceptionthrowables){
  36. throwables.printStackTrace();
  37. }finally{
  38. if(pstat!=null){
  39. try{
  40. pstat.close();
  41. }catch(SQLExceptionthrowables){
  42. throwables.printStackTrace();
  43. }
  44. }
  45. if(conn!=null){
  46. try{
  47. conn.close();
  48. }catch(SQLExceptionthrowables){
  49. throwables.printStackTrace();
  50. }
  51. }
  52. }
  53. }
  54. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  55. doPost(request,response);
  56. }}

2.定義工具類,簡化開發
定義一個JDBCUtils類。
提供方法:
1.獲取連線的方法:通過資料庫連線池獲取。

2.釋放資源

3.獲取連線池的方法。

[plain]view plaincopy
  1. /**
  2. *Druid連線池的工具類
  3. */publicclassJdbcUtils{
  4. //1.定義成員變數DateaSource
  5. privatestaticDataSourceds;
  6. static{
  7. try{
  8. //1.載入配置檔案
  9. Propertiespro=newProperties();
  10. InputStreamis=JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
  11. pro.load(is);
  12. //2.獲取DataSource
  13. ds=DruidDataSourceFactory.createDataSource(pro);
  14. }catch(IOExceptione){
  15. e.printStackTrace();
  16. }catch(Exceptione){
  17. e.printStackTrace();
  18. }
  19. }
  20. /**
  21. *獲取連線
  22. */
  23. publicstaticConnectiongetConntion()throwsSQLException{
  24. returnds.getConnection();
  25. }
  26. /**
  27. *釋放資源
  28. */
  29. publicstaticvoidclose(Statementstmt,Connectionconn){
  30. /*if(stmt!=null){
  31. try{
  32. stmt.close();
  33. }catch(SQLExceptionthrowables){
  34. throwables.printStackTrace();
  35. }
  36. }
  37. if(conn!=null){//歸還連線
  38. try{
  39. stmt.close();
  40. }catch(SQLExceptionthrowables){
  41. throwables.printStackTrace();
  42. }
  43. }*/
  44. close(null,stmt,conn);
  45. }
  46. /**
  47. *釋放資源
  48. */
  49. publicstaticvoidclose(ResultSetrs,Statementstmt,Connectionconn){
  50. if(rs!=null){
  51. try{
  52. rs.close();
  53. }catch(SQLExceptionthrowables){
  54. throwables.printStackTrace();
  55. }
  56. }
  57. if(stmt!=null){
  58. try{
  59. stmt.close();
  60. }catch(SQLExceptionthrowables){
  61. throwables.printStackTrace();
  62. }
  63. }
  64. if(conn!=null){//歸還連線
  65. try{
  66. stmt.close();
  67. }catch(SQLExceptionthrowables){
  68. throwables.printStackTrace();
  69. }
  70. }
  71. }
  72. /**
  73. *獲取連線池
  74. */
  75. publicstaticDataSourcegetDataSource(){
  76. returnds;
  77. }}

05.Spring JDBC

JDBC已經能夠滿足大部分使用者最基本的需求,但是在使用JDBC時,必須自己來管理資料庫資源如:獲取 PreparedStatement,設定SQL語句引數,關閉連線等步驟。JdbcTemplate就是Spring對JDBC的封裝,目的是使 JDBC更加易於使用。JdbcTemplate是Spring的一部分。 JdbcTemplate處理了資源的建立和釋放。他幫助我們避免一些常見的錯誤,比如忘了總要關閉連線。他執行核心的JDBC工作流,如Statement的建立和執行,而我們只需 要提供SQL語句和提取結果。

JDBC的工具類,目的是為了簡化開發步驟。
Spring框架對JDBC的簡單框架,提供了一個JdbcTemplate物件簡化JDBC的開發。

步驟:
1.匯入jar包。

2.建立JdbcTemplate物件,依賴於資料來源DataSource。

JdbcTemplatetemplate=newJdbcTemplate(ds);

3.呼叫JdbcTemplate的方法來完成CRUD的操作。

[plain]view plaincopy
  1. update():執行DML語句(insert,update,delete)。
  2. queryForMap():查詢結果將結果封裝為map集合。結果只能為1條,
  3. 列名為key,值為value
  4. queryForList():查詢結果將結果集封裝為list集合。
  5. 先將資料封裝為一個Map集合,再將Map集合轉載到List集合中
  6. query():查詢結果,將結果封裝為JavaBean物件。(重點)
  7. 一般我們使用BeanPropertyRowMapper實現類。
  8. 可以完成到JavaBean的自動封裝。
  9. newBeanPropertyRowMapper<型別>(型別.class)
  10. queryForObject:查詢結果,將結果封裝為物件。
  11. 一般用於聚合函式的查詢

update()練習:

[plain]view plaincopy
  1. @WebServlet("/jdbcTemplateServletTest1")publicclassjdbcTemplateServletTest1extendsHttpServlet{
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  3. request.setCharacterEncoding("utf-8");
  4. response.setContentType("text/html;charset=utf-8");
  5. PrintWriterout=response.getWriter();
  6. //1.匯入jar包
  7. //2.建立JdbcTemplate物件
  8. JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
  9. //定義sql
  10. Stringsql="insertintostudent(sequence,sex,name,birthday)values(?,?,?,?)";
  11. //呼叫方法
  12. intcount=template.update(sql,"101000","男","張三","2020-11-19");
  13. out.print(count);
  14. }
  15. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  16. doPost(request,response);
  17. }}

queryForMap()練習:

[plain]view plaincopy
  1. @WebServlet("/jdbcTemplateServletTestl2")publicclassjdbcTemp
  2. 8000
  3. lateServletTestl2extendsHttpServlet{
  4. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  5. request.setCharacterEncoding("utf-8");
  6. response.setContentType("text/html;charset=utf-8");
  7. PrintWriterout=response.getWriter();
  8. JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
  9. Stringsql="select*fromstudentwhereid=?";
  10. //只能封裝1條
  11. Map<String,Object>map=template.queryForMap(sql,1);
  12. out.print(map);
  13. }
  14. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  15. doPost(request,response);
  16. }}

queryForList()練習:

[plain]view plaincopy
  1. @WebServlet("/jdbcTemplateServletTestl2")publicclassjdbcTemplateServletTestl2extendsHttpServlet{
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  3. request.setCharacterEncoding("utf-8");
  4. response.setContentType("text/html;charset=utf-8");
  5. PrintWriterout=response.getWriter();
  6. JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
  7. Stringsql="select*fromstudentwhereid>?";
  8. List<Map<String,Object>>list=template.queryForList(sql,1);
  9. for(Map<String,Object>StringObjectMap:list){
  10. out.print("<p>"+StringObjectMap+"</p>");
  11. }
  12. }
  13. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  14. doPost(request,response);
  15. }}

將Map轉換成JSON格式:

[plain]view plaincopy
  1. Stringsql="select*fromstudentwhereid>?";
  2. List<Map<String,Object>>maps=jdbcTemplate.queryForList(sql,1);
  3. Map<String,Object>map=maps.get(2);
  4. JSONObjectjsonObject=newJSONObject(map);
  5. System.out.println(jsonObject.toJSONString());

query練習:

[plain]view plaincopy
  1. @WebServlet("/jdbcTemplateServletTest2")publicclassjdbcTemplateServletTest2extendsHttpServlet{
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  3. request.setCharacterEncoding("utf-8");
  4. response.setContentType("text/html;charset=utf-8");
  5. PrintWriterout=response.getWriter();
  6. JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
  7. Stringsql="select*fromstudent";
  8. List<Student>list=template.query(sql,newRowMapper<Student>(){
  9. @Override
  10. publicStudentmapRow(ResultSetrs,inti)throwsSQLException{
  11. Studentstudent=newStudent();
  12. intid=rs.getInt("id");
  13. Stringsequence=rs.getString("sequence");
  14. Stringname=rs.getString("name");
  15. Stringsex=rs.getString("sex");
  16. Datebirthday=rs.getDate("birthday");
  17. student.setId(id);
  18. student.setSequence(sequence);
  19. student.setName(name);
  20. student.setSex(sex);
  21. student.setBirthday(birthday);
  22. returnstudent;
  23. }
  24. });
  25. for(Studentstudent:list){
  26. out.print(student);
  27. }
  28. }
  29. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  30. doPost(request,response);
  31. }}

存在的問題:雖然我們用了Spring JDBC類,通過query練習但是我們並沒有實現簡化程式碼,跟以前差不多,那是因為我們自己去實現了 RowMapper介面, 其實JdbcTemplate已經幫我們實現了,我們直接使用就好了。

改進後:

[plain]view plaincopy
  1. @WebServlet("/JdbcTemplateServletTest3")publicclassJdbcTemplateServletTest3extendsHttpServlet{
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  3. request.setCharacterEncoding("utf-8");
  4. response.setContentType("text/html;charset=utf-8");
  5. PrintWriterout=response.getWriter();
  6. JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
  7. Stringsql="select*fromstudent";
  8. List<Student>list=template.query(sql,newBeanPropertyRowMapper<Student>(Student.class));
  9. for(Studentstudent:list){
  10. out.print(list);
  11. }
  12. }
  13. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  14. doPost(request,response);
  15. }}
[plain]view plaincopy
  1. @WebServlet("/JdbcTemplateServletTest3")publicclassJdbcTemplateServletTest3extendsHttpServlet{
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  3. request.setCharacterEncoding("utf-8");
  4. response.setContentType("text/html;charset=utf-8");
  5. PrintWriterout=response.getWriter();
  6. JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
  7. Stringsql="select*fromstudentwhereid=?";
  8. //將查詢結果封裝成了java物件
  9. List<Student>list=template.query(sql,newBeanPropertyRowMapper<Student>(Student.class),"1");
  10. out.print(list.get(0).getName());
  11. }
  12. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  13. doPost(request,response);
  14. }}

注意JavaBean類,如果屬性定義為基本型別,在查詢資料庫時,如果欄位為空,會報錯,可以將JavaBean屬性基本型別改為引用資料型別。

queryForObject練習:

[plain]view plaincopy
  1. @WebServlet("/JdbcTemplateServletTest3")publicclassJdbcTemplateServletTest3extendsHttpServlet{
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  3. request.setCharacterEncoding("utf-8");
  4. response.setContentType("text/html;charset=utf-8");
  5. PrintWriterout=response.getWriter();
  6. JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
  7. Stringsql="selectcount(id)fromstudent";
  8. Longtotal=template.queryForObject(sql,Long.class);
  9. out.print(total);
  10. }
  11. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  12. doPost(request,response);
  13. }}

【提出問題】
如果這裡不使用自定義工具類JdbcUtils得到連線池,而是直接獲取連線池,多次訪問後,則會出現too many connection情況。

[plain]view plaincopy
  1. JdbcTemplatetemplate=new
  2. JdbcTemplate(JdbcUtils.getDataSource());

06.登入案例

登入頁面:

[plain]view plaincopy
  1. <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
  2. pageEncoding="UTF-8"%><!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>Inserttitlehere</title><scriptsrc="../../case43/res/js/jquery.min.js"></script><styletype="text/css">
  3. p{
  4. color:red;
  5. }</style></head><body>
  6. <formclass="fm">
  7. <div>
  8. <label>賬號:</label>
  9. <inputtype="text"name="userName"id="userName">
  10. </div>
  11. <div>
  12. <label>密碼:</label>
  13. <inputtype="password"name="passWord"id="passWord">
  14. </div>
  15. <inputtype="button"id="btn"value="確認">
  16. </form>
  17. <pid="p"></p>
  18. <script>
  19. $(function(){
  20. $("#btn").click(function(){
  21. vardataFm=$(".fm").serialize();
  22. $.post(
  23. "/teaching/com/teaching/homeWork/Check1",
  24. dataFm,
  25. function(data){
  26. varjson=JSON.parse(data);
  27. if(json.success){
  28. window.location.href=json.url;
  29. }else{
  30. $("#p").html("賬號或密碼錯誤!");
  31. }
  32. }
  33. );
  34. });
  35. });
  36. </script></body></html>

工具類:

[plain]view plaincopy
  1. /**
  2. *Druid連線池的工具類
  3. */publicclassJdbcUtils{
  4. //1.定義成員變數DateaSource
  5. privatestaticDataSourceds;
  6. static{
  7. try{
  8. //1.載入配置檔案
  9. Propertiespro=newProperties();
  10. InputStreamis=JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
  11. pro.load(is);
  12. //2.獲取DataSource
  13. ds=DruidDataSourceFactory.createDataSource(pro);
  14. }catch(IOExceptione){
  15. e.printStackTrace();
  16. }catch(Exceptione){
  17. e.printStackTrace();
  18. }
  19. }
  20. /**
  21. *獲取連線
  22. */
  23. publicstaticConnectiongetConntion()throwsSQLException{
  24. returnds.getConnection();
  25. }
  26. /**
  27. *釋放資源
  28. */
  29. publicstaticvoidclose(Statementstmt,Connectionconn){
  30. close(null,stmt,conn);
  31. }
  32. /**
  33. *釋放資源
  34. */
  35. publicstaticvoidclose(ResultSetrs,Statementstmt,Connectionconn){
  36. if(rs!=null){
  37. try{
  38. rs.close();
  39. }catch(SQLExceptionthrowables){
  40. throwables.printStackTrace();
  41. }
  42. }
  43. if(stmt!=null){
  44. try{
  45. stmt.close();
  46. }catch(SQLExceptionthrowables){
  47. throwables.printStackTrace();
  48. }
  49. }
  50. if(conn!=null){//歸還連線
  51. try{
  52. stmt.close();
  53. }catch(SQLExceptionthrowables){
  54. throwables.printStackTrace();
  55. }
  56. }
  57. }
  58. /**
  59. *獲取連線池
  60. */
  61. publicstaticDataSourcegetDataSource(){
  62. returnds;
  63. }}

處理request:

[plain]view plaincopy
  1. @WebServlet("/com/teaching/homeWork/Check1")publicclassCheck1extendsHttpServlet{
  2. privatestaticfinallongserialVersionUID=1L;
  3. /**
  4. *@seeHttpServlet#HttpServlet()
  5. */
  6. publicCheck1(){
  7. super();
  8. //TODOAuto-generatedconstructorstub
  9. }
  10. /**
  11. *@seeHttpServlet#doGet(HttpServletRequestrequest,HttpServletResponse
  12. *response)
  13. */
  14. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
  15. throwsServletException,IOException{
  16. //TODOAuto-generatedmethodstub
  17. request.setCharacterEncoding("utf-8");
  18. response.setContentType("text/html;charset=utf-8");
  19. PrintWriterout=response.getWriter();
  20. StringuserName=request.getParameter("userName");
  21. StringpassWord=request.getParameter("passWord");
  22. JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
  23. //因為teaching表沒有賬號和密碼欄位,為了減少時間,預設將name作為賬號,sequence作為密碼
  24. Stringsql="select*fromstudentwherename=?andsequence=?";
  25. //將查詢結果封裝成了java物件,如果沒有執行成功會報異常(則會存在問題)
  26. Studentstudent=null;
  27. try{
  28. student=template.queryForObject(sql,newBeanPropertyRowMapper<Student>(Student.class),userName,passWord);
  29. }catch(EmptyResultDataAccessExceptione){
  30. e.printStackTrace();
  31. }
  32. //Studentstudent=template.queryForObject(sql,newBeanPropertyRowMapper<Student>(Student.class),userName,passWord);
  33. if(student!=null&&userName.equals(student.getName())&&passWord.equals(student.getSequence())){
  34. HttpSessionsession=request.getSession();
  35. session.setAttribute("userName",student.getName());
  36. session.setAttribute("passWord",student.getSequence());//密碼
  37. //設定session存活時間
  38. Cookieid=newCookie("JSESSIONID",session.getId());
  39. id.setMaxAge(60*60*24*10);//10天
  40. response.addCookie(id);//轉發
  41. Stringurl=request.getContextPath()+"/case631/homeWork/html/success.jsp";
  42. request.setAttribute("success",true);
  43. request.setAttribute("url",url);
  44. request.setAttribute("student",student);
  45. Stringurl1="/com/teaching/homeWork/Json";
  46. RequestDispatcherrd=request.getRequestDispatcher(url1);
  47. rd.forward(request,response);
  48. }else{//查詢失敗,轉發到登入頁面
  49. Studentstudent1=newStudent();
  50. student1.setName("null");
  51. student1.setSequence("null");
  52. request.setAttribute("success",false);
  53. request.setAttribute("url","null");
  54. request.setAttribute("student",student1);
  55. Stringurl1="/com/teaching/homeWork/Json";
  56. RequestDispatcherrd=request.getRequestDispatcher(url1);
  57. rd.forward(request,response);
  58. }
  59. }
  60. /**
  61. *@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponse
  62. *response)
  63. */
  64. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
  65. throwsServletException,IOException{
  66. //TODOAuto-generatedmethodstub
  67. doGet(request,response);
  68. }}

JavaBean類:

[plain]view plaincopy
  1. packagecom.teaching.homeWork;importjava.util.Date;/**
  2. *javaBean
  3. */publicclassStudent{
  4. privateIntegerid;//為防止資料庫欄位為空,定義為應用資料型別
  5. privateStringsequence;
  6. privateStringname;
  7. privateStringsex;
  8. privateDatebirthday;
  9. publicIntegergetId(){
  10. returnid;
  11. }
  12. publicvoidsetId(Integerid){
  13. this.id=id;
  14. }
  15. publicStringgetSequence(){
  16. returnsequence;
  17. }
  18. publicvoidsetSequence(Stringsequence){
  19. this.sequence=sequence;
  20. }
  21. publicStringgetName(){
  22. returnname;
  23. }
  24. publicvoidsetName(Stringname){
  25. this.name=name;
  26. }
  27. publicStringgetSex(){
  28. returnsex;
  29. }
  30. publicvoidsetSex(Stringsex){
  31. this.sex=sex;
  32. }
  33. publicDategetBirthday(){
  34. returnbirthday;
  35. }
  36. publicvoidsetBirthday(Datebirthday){
  37. this.birthday=birthday;
  38. }
  39. @Override
  40. publicStringtoString(){
  41. return"Student{"+
  42. "id="+id+
  43. ",sequence='"+sequence+'\''+
  44. ",name='"+name+'\''+
  45. ",sex='"+sex+'\''+
  46. ",birthday="+birthday+
  47. '}';
  48. }}

response類:

[plain]view plaincopy
  1. @WebServlet("/com/teaching/homeWork/Json")publicclassJsonextendsHttpServlet{
  2. privatestaticfinallongserialVersionUID=1L;
  3. /**
  4. *@seeHttpServlet#HttpServlet()
  5. */
  6. publicJson(){
  7. super();
  8. //TODOAuto-generatedconstructorstub
  9. }
  10. /**
  11. *@seeHttpServlet#doGet(HttpServletRequestrequest,HttpServletResponseresponse)
  12. */
  13. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  14. //TODOAuto-generatedmethodstub
  15. request.setCharacterEncoding("utf-8");
  16. response.setContentType("text/html;charset=utf-8");
  17. PrintWriterout=response.getWriter();
  18. booleansuccess=(boolean)request.getAttribute("success");
  19. Stringurl=(String)request.getAttribute("url");
  20. Studentstudent=(Student)request.getAttribute("student");
  21. Stringjson="{"+"\""+"success"+"\":"+success+","+"\""+"url"+"\":"+"\""+url+"\""+","+"\""+"userName"+"\":"+"\""+student.getName()+"\""+","+"\""+"userName"+"\":"+"\""+student.getSequence()+"\""+"}";
  22. System.out.print(json);
  23. out.print(json);
  24. }
  25. /**
  26. *@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponseresponse)
  27. */
  28. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  29. //TODOAuto-generatedmethodstub
  30. doGet(request,response);
  31. }}

登入成功頁面:

[plain]view plaincopy
  1. <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
  2. pageEncoding="UTF-8"%><!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>Inserttitlehere</title></head><body><p><%=request.getSession().getAttribute("userName")%>>歡迎你!</p></body></html>

練習:
1