2020年北京某企Java校招真題
01.為什麼要資料庫連線池
為了避免頻繁的建立資料庫連線,資料庫連線池應運而生。資料庫連線池負責分配、管理和釋放資料庫連線。它允許應用程式重複使用現有的資料庫連線,而不是重新建立。
資料庫連線池在初始化的時候建立一定數量的資料庫連線放到資料庫連線池中,當應用程式訪問時向連線池申請一個Connection。如果有空閒的Connection,則將其返回,否則建立新的Connection。使用完畢後,連線池會將該Connection收回,交付給其它執行緒使用,以減少建立資料庫連線的次數,提高資料庫訪問的效率。
資料庫連線池
概念:其實就是一個容器(集合),存放資料庫連線的容器。
特點:節約了資源,使用者訪問高效。
02.資料庫連線池的實現
標準介面:DataSource介面
在javax.sql包下。
為了獲取資料庫連線物件,JDBC提供了javax.sql。DataSource介面,他負責與資料庫建立連線,並定義了返回值為Connection物件的方法。
1.方法:
- 獲取連線:
- ConnectiongetConnection()
- ConnectiongetConnection(Stringusername,Stringpassword)
- 歸還連線:如果連線物件Connection時是從連線池中獲取的,
- 那麼呼叫Connection.close()方法,則不會再關閉連線了。
- 而是歸還連線
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- @WebServlet("/C3p0ServletTest1")publicclassC3p0ServletTest1extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- //1.建立資料庫連線池物件
- DataSourceds=newComboPooledDataSource();
- Connectionconn=null;
- PreparedStatementpstat=null;
- ResultSetrs=null;
- try{
- //2.獲取連線物件
- conn=ds.getConnection();
- //3.定義sql
- Stringsql="select*fromstudentwheresex=?";
- //4.獲取執行sql的物件
- pstat=conn.prepareStatement(sql);
- pstat.setString(1,"男");
- //5.執行sql
- rs=pstat.executeQuery();
- while(rs.next()){
- Stringsequence=rs.getString("sequence");
- Stringname=rs.getString("name");
- Stringsex=rs.getString("sex");
- out.println("<p>"+sequence+""+name+""+sex+"<p>");
- }
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }finally{
- try{
- if(rs!=null){
- rs.close();
- }
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- if(pstat!=null){
- try{
- pstat.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- if(conn!=null){
- try{
- conn.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- }
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throws
- ServletException,IOException{
- doPost(request,response);
- }}
04.Druid:資料庫連線池實現技術
Druid由阿里巴巴提供。
步驟:
1.匯入jar包:druid-1.0.9.jar。
2.定義配置檔案:
是proporties形式。
名稱:可以交任意名稱,可以放在任意目錄下(需要手動載入)
3.獲取資料庫連線池物件:通過工廠類來獲取
DruidDataSourceFactory
4.獲取連線
5.其他的步驟相同
[plain]view plaincopy- @WebServlet("/DruidServletTest1")publicclassDruidServletTest1extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- DataSourceds=null;
- Connectionconn=null;
- PreparedStatementpstat=null;
- //1.載入配置檔案
- Propertiespro=newProperties();
- InputStreamis=DruidServletTest1.class.getClassLoader().getResourceAsStream("druid.properties");
- pro.load(is);
- //2.獲取連線池物件
- try{
- ds=DruidDataSourceFactory.createDataSource(pro);
- }catch(Exceptione){
- e.printStackTrace();
- }
- try{
- //5.獲取連線
- conn=ds.getConnection();
- //3.定義sql
- Stringsql="updatestudentsetname=?wherebirthday=?";
- //4.獲取執行sql的物件
- pstat=conn.prepareStatement(sql);
- pstat.setString(1,"夢陽辰");
- pstat.setString(2,"1999-10-18");
- //5.執行sql
- intcount=pstat.executeUpdate();
- if(count>0){
- out.print("修改成功!");
- }else{
- out.print("修改失敗!");
- }
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }finally{
- if(pstat!=null){
- try{
- pstat.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- if(conn!=null){
- try{
- conn.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- }
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- doPost(request,response);
- }}
2.定義工具類,簡化開發
定義一個JDBCUtils類。
提供方法:
1.獲取連線的方法:通過資料庫連線池獲取。
2.釋放資源
3.獲取連線池的方法。
[plain]view plaincopy- /**
- *Druid連線池的工具類
- */publicclassJdbcUtils{
- //1.定義成員變數DateaSource
- privatestaticDataSourceds;
- static{
- try{
- //1.載入配置檔案
- Propertiespro=newProperties();
- InputStreamis=JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
- pro.load(is);
- //2.獲取DataSource
- ds=DruidDataSourceFactory.createDataSource(pro);
- }catch(IOExceptione){
- e.printStackTrace();
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- /**
- *獲取連線
- */
- publicstaticConnectiongetConntion()throwsSQLException{
- returnds.getConnection();
- }
- /**
- *釋放資源
- */
- publicstaticvoidclose(Statementstmt,Connectionconn){
- /*if(stmt!=null){
- try{
- stmt.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- if(conn!=null){//歸還連線
- try{
- stmt.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }*/
- close(null,stmt,conn);
- }
- /**
- *釋放資源
- */
- publicstaticvoidclose(ResultSetrs,Statementstmt,Connectionconn){
- if(rs!=null){
- try{
- rs.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- if(stmt!=null){
- try{
- stmt.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- if(conn!=null){//歸還連線
- try{
- stmt.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- }
- /**
- *獲取連線池
- */
- publicstaticDataSourcegetDataSource(){
- returnds;
- }}
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- update():執行DML語句(insert,update,delete)。
- queryForMap():查詢結果將結果封裝為map集合。結果只能為1條,
- 列名為key,值為value
- queryForList():查詢結果將結果集封裝為list集合。
- 先將資料封裝為一個Map集合,再將Map集合轉載到List集合中
- query():查詢結果,將結果封裝為JavaBean物件。(重點)
- 一般我們使用BeanPropertyRowMapper實現類。
- 可以完成到JavaBean的自動封裝。
- newBeanPropertyRowMapper<型別>(型別.class)
- queryForObject:查詢結果,將結果封裝為物件。
- 一般用於聚合函式的查詢
update()練習:
[plain]view plaincopy- @WebServlet("/jdbcTemplateServletTest1")publicclassjdbcTemplateServletTest1extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- //1.匯入jar包
- //2.建立JdbcTemplate物件
- JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
- //定義sql
- Stringsql="insertintostudent(sequence,sex,name,birthday)values(?,?,?,?)";
- //呼叫方法
- intcount=template.update(sql,"101000","男","張三","2020-11-19");
- out.print(count);
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- doPost(request,response);
- }}
queryForMap()練習:
[plain]view plaincopy- @WebServlet("/jdbcTemplateServletTestl2")publicclassjdbcTemp
- 8000
- lateServletTestl2extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
- Stringsql="select*fromstudentwhereid=?";
- //只能封裝1條
- Map<String,Object>map=template.queryForMap(sql,1);
- out.print(map);
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- doPost(request,response);
- }}
queryForList()練習:
[plain]view plaincopy- @WebServlet("/jdbcTemplateServletTestl2")publicclassjdbcTemplateServletTestl2extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
- Stringsql="select*fromstudentwhereid>?";
- List<Map<String,Object>>list=template.queryForList(sql,1);
- for(Map<String,Object>StringObjectMap:list){
- out.print("<p>"+StringObjectMap+"</p>");
- }
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- doPost(request,response);
- }}
將Map轉換成JSON格式:
[plain]view plaincopy- Stringsql="select*fromstudentwhereid>?";
- List<Map<String,Object>>maps=jdbcTemplate.queryForList(sql,1);
- Map<String,Object>map=maps.get(2);
- JSONObjectjsonObject=newJSONObject(map);
- System.out.println(jsonObject.toJSONString());
query練習:
[plain]view plaincopy- @WebServlet("/jdbcTemplateServletTest2")publicclassjdbcTemplateServletTest2extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
- Stringsql="select*fromstudent";
- List<Student>list=template.query(sql,newRowMapper<Student>(){
- @Override
- publicStudentmapRow(ResultSetrs,inti)throwsSQLException{
- Studentstudent=newStudent();
- intid=rs.getInt("id");
- Stringsequence=rs.getString("sequence");
- Stringname=rs.getString("name");
- Stringsex=rs.getString("sex");
- Datebirthday=rs.getDate("birthday");
- student.setId(id);
- student.setSequence(sequence);
- student.setName(name);
- student.setSex(sex);
- student.setBirthday(birthday);
- returnstudent;
- }
- });
- for(Studentstudent:list){
- out.print(student);
- }
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- doPost(request,response);
- }}
存在的問題:雖然我們用了Spring JDBC類,通過query練習但是我們並沒有實現簡化程式碼,跟以前差不多,那是因為我們自己去實現了 RowMapper介面, 其實JdbcTemplate已經幫我們實現了,我們直接使用就好了。
改進後:
[plain]view plaincopy- @WebServlet("/JdbcTemplateServletTest3")publicclassJdbcTemplateServletTest3extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
- Stringsql="select*fromstudent";
- List<Student>list=template.query(sql,newBeanPropertyRowMapper<Student>(Student.class));
- for(Studentstudent:list){
- out.print(list);
- }
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- doPost(request,response);
- }}
- @WebServlet("/JdbcTemplateServletTest3")publicclassJdbcTemplateServletTest3extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
- Stringsql="select*fromstudentwhereid=?";
- //將查詢結果封裝成了java物件
- List<Student>list=template.query(sql,newBeanPropertyRowMapper<Student>(Student.class),"1");
- out.print(list.get(0).getName());
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- doPost(request,response);
- }}
注意JavaBean類,如果屬性定義為基本型別,在查詢資料庫時,如果欄位為空,會報錯,可以將JavaBean屬性基本型別改為引用資料型別。
queryForObject練習:
[plain]view plaincopy- @WebServlet("/JdbcTemplateServletTest3")publicclassJdbcTemplateServletTest3extendsHttpServlet{
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
- Stringsql="selectcount(id)fromstudent";
- Longtotal=template.queryForObject(sql,Long.class);
- out.print(total);
- }
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- doPost(request,response);
- }}
【提出問題】
如果這裡不使用自定義工具類JdbcUtils得到連線池,而是直接獲取連線池,多次訪問後,則會出現too many connection情況。
- JdbcTemplatetemplate=new
- JdbcTemplate(JdbcUtils.getDataSource());
06.登入案例
登入頁面:
[plain]view plaincopy- <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
- pageEncoding="UTF-8"%><!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>Inserttitlehere</title><scriptsrc="../../case43/res/js/jquery.min.js"></script><styletype="text/css">
- p{
- color:red;
- }</style></head><body>
- <formclass="fm">
- <div>
- <label>賬號:</label>
- <inputtype="text"name="userName"id="userName">
- </div>
- <div>
- <label>密碼:</label>
- <inputtype="password"name="passWord"id="passWord">
- </div>
- <inputtype="button"id="btn"value="確認">
- </form>
- <pid="p"></p>
- <script>
- $(function(){
- $("#btn").click(function(){
- vardataFm=$(".fm").serialize();
- $.post(
- "/teaching/com/teaching/homeWork/Check1",
- dataFm,
- function(data){
- varjson=JSON.parse(data);
- if(json.success){
- window.location.href=json.url;
- }else{
- $("#p").html("賬號或密碼錯誤!");
- }
- }
- );
- });
- });
- </script></body></html>
工具類:
[plain]view plaincopy- /**
- *Druid連線池的工具類
- */publicclassJdbcUtils{
- //1.定義成員變數DateaSource
- privatestaticDataSourceds;
- static{
- try{
- //1.載入配置檔案
- Propertiespro=newProperties();
- InputStreamis=JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
- pro.load(is);
- //2.獲取DataSource
- ds=DruidDataSourceFactory.createDataSource(pro);
- }catch(IOExceptione){
- e.printStackTrace();
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- /**
- *獲取連線
- */
- publicstaticConnectiongetConntion()throwsSQLException{
- returnds.getConnection();
- }
- /**
- *釋放資源
- */
- publicstaticvoidclose(Statementstmt,Connectionconn){
- close(null,stmt,conn);
- }
- /**
- *釋放資源
- */
- publicstaticvoidclose(ResultSetrs,Statementstmt,Connectionconn){
- if(rs!=null){
- try{
- rs.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- if(stmt!=null){
- try{
- stmt.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- if(conn!=null){//歸還連線
- try{
- stmt.close();
- }catch(SQLExceptionthrowables){
- throwables.printStackTrace();
- }
- }
- }
- /**
- *獲取連線池
- */
- publicstaticDataSourcegetDataSource(){
- returnds;
- }}
處理request:
[plain]view plaincopy- @WebServlet("/com/teaching/homeWork/Check1")publicclassCheck1extendsHttpServlet{
- privatestaticfinallongserialVersionUID=1L;
- /**
- *@seeHttpServlet#HttpServlet()
- */
- publicCheck1(){
- super();
- //TODOAuto-generatedconstructorstub
- }
- /**
- *@seeHttpServlet#doGet(HttpServletRequestrequest,HttpServletResponse
- *response)
- */
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
- throwsServletException,IOException{
- //TODOAuto-generatedmethodstub
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- StringuserName=request.getParameter("userName");
- StringpassWord=request.getParameter("passWord");
- JdbcTemplatetemplate=newJdbcTemplate(JdbcUtils.getDataSource());
- //因為teaching表沒有賬號和密碼欄位,為了減少時間,預設將name作為賬號,sequence作為密碼
- Stringsql="select*fromstudentwherename=?andsequence=?";
- //將查詢結果封裝成了java物件,如果沒有執行成功會報異常(則會存在問題)
- Studentstudent=null;
- try{
- student=template.queryForObject(sql,newBeanPropertyRowMapper<Student>(Student.class),userName,passWord);
- }catch(EmptyResultDataAccessExceptione){
- e.printStackTrace();
- }
- //Studentstudent=template.queryForObject(sql,newBeanPropertyRowMapper<Student>(Student.class),userName,passWord);
- if(student!=null&&userName.equals(student.getName())&&passWord.equals(student.getSequence())){
- HttpSessionsession=request.getSession();
- session.setAttribute("userName",student.getName());
- session.setAttribute("passWord",student.getSequence());//密碼
- //設定session存活時間
- Cookieid=newCookie("JSESSIONID",session.getId());
- id.setMaxAge(60*60*24*10);//10天
- response.addCookie(id);//轉發
- Stringurl=request.getContextPath()+"/case631/homeWork/html/success.jsp";
- request.setAttribute("success",true);
- request.setAttribute("url",url);
- request.setAttribute("student",student);
- Stringurl1="/com/teaching/homeWork/Json";
- RequestDispatcherrd=request.getRequestDispatcher(url1);
- rd.forward(request,response);
- }else{//查詢失敗,轉發到登入頁面
- Studentstudent1=newStudent();
- student1.setName("null");
- student1.setSequence("null");
- request.setAttribute("success",false);
- request.setAttribute("url","null");
- request.setAttribute("student",student1);
- Stringurl1="/com/teaching/homeWork/Json";
- RequestDispatcherrd=request.getRequestDispatcher(url1);
- rd.forward(request,response);
- }
- }
- /**
- *@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponse
- *response)
- */
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
- throwsServletException,IOException{
- //TODOAuto-generatedmethodstub
- doGet(request,response);
- }}
JavaBean類:
[plain]view plaincopy- packagecom.teaching.homeWork;importjava.util.Date;/**
- *javaBean
- */publicclassStudent{
- privateIntegerid;//為防止資料庫欄位為空,定義為應用資料型別
- privateStringsequence;
- privateStringname;
- privateStringsex;
- privateDatebirthday;
- publicIntegergetId(){
- returnid;
- }
- publicvoidsetId(Integerid){
- this.id=id;
- }
- publicStringgetSequence(){
- returnsequence;
- }
- publicvoidsetSequence(Stringsequence){
- this.sequence=sequence;
- }
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicStringgetSex(){
- returnsex;
- }
- publicvoidsetSex(Stringsex){
- this.sex=sex;
- }
- publicDategetBirthday(){
- returnbirthday;
- }
- publicvoidsetBirthday(Datebirthday){
- this.birthday=birthday;
- }
- @Override
- publicStringtoString(){
- return"Student{"+
- "id="+id+
- ",sequence='"+sequence+'\''+
- ",name='"+name+'\''+
- ",sex='"+sex+'\''+
- ",birthday="+birthday+
- '}';
- }}
response類:
[plain]view plaincopy- @WebServlet("/com/teaching/homeWork/Json")publicclassJsonextendsHttpServlet{
- privatestaticfinallongserialVersionUID=1L;
- /**
- *@seeHttpServlet#HttpServlet()
- */
- publicJson(){
- super();
- //TODOAuto-generatedconstructorstub
- }
- /**
- *@seeHttpServlet#doGet(HttpServletRequestrequest,HttpServletResponseresponse)
- */
- protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- //TODOAuto-generatedmethodstub
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
- PrintWriterout=response.getWriter();
- booleansuccess=(boolean)request.getAttribute("success");
- Stringurl=(String)request.getAttribute("url");
- Studentstudent=(Student)request.getAttribute("student");
- Stringjson="{"+"\""+"success"+"\":"+success+","+"\""+"url"+"\":"+"\""+url+"\""+","+"\""+"userName"+"\":"+"\""+student.getName()+"\""+","+"\""+"userName"+"\":"+"\""+student.getSequence()+"\""+"}";
- System.out.print(json);
- out.print(json);
- }
- /**
- *@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponseresponse)
- */
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
- //TODOAuto-generatedmethodstub
- doGet(request,response);
- }}
登入成功頁面:
[plain]view plaincopy- <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
- pageEncoding="UTF-8"%><!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>Inserttitlehere</title></head><body><p><%=request.getSession().getAttribute("userName")%>>歡迎你!</p></body></html>
練習:
1