JavaWeb Final Exam--Review

Javaweb final review questions

1

Single choice

2

Multiple choice

3

Q&A

4

program fill in the blanks

5

Programming (none in this part)

If you need the word version of the information, please see the end of the article. You can pick it up for free.

0. Review of semester knowledge points

1. Annotations and annotations

1. Three types of comments in Java: single line, multi-line and documentation comments .

2. Commonly used meta-annotations:

(1) When @Retention is applied to an annotation, it explains the survival time of the annotation. The values ​​are as follows:

  1. The RetentionPolicy. SOURCE annotation is only retained at the source code stage and will be discarded and ignored by the compiler when compiling.
  2. RetentionPolicy. CLASS annotation is only retained until compilation is in progress , it will not be loaded into the JVM.
  3. RetentionPolicy. RUNTIME annotations can be retained until the program is running , and they will be loaded into the JVM, so they can be obtained when the program is running.

(2) @Target specifies the place where the annotation is used .

2. Introduction to Java Web Development

1. 3 versions of Java

(1) Java SE: used for the development of desktop application software

(2) Java EE: used to develop websites with high traffic, large data volume, and high concurrency

(3) Java ME: used for the development of embedded systems and mobile platforms

2. B/S architecture

(1) Advantages: The client does not need to be installed , as long as it has a Web browser; the B/S architecture does not require upgrading multiple clients, just upgrade the Web server.

(2) Disadvantages: In terms of cross-browser, the B/S architecture is not satisfactory; it takes a lot of effort to achieve the performance of a C/S program; it requires a large design cost in terms of speed and security .

3. Common Java web servers

        Tomcat server, Resin server , JBoss server, WebSphere server, WebLogic server

4. Common Java IDEs

        Jcreator、netbeans、IDEA、Eclipse 、MyEclipse

5. Two methods of HTTP requests: GET and POST.

        There is only one situation in which a POST request can be sent: <form method="POST">; in the rest of the situations, it is a GET request.

6. The difference between GET and POST

(1) GET submits data in the request line, and the sent data will be displayed in the address bar ; POST submits data in the request body, and the sent data will not be displayed in the address bar.

(2) GET cannot send large amounts of data; POST can send large amounts of data , and there is no limit in theory.

(3) GET can only send string data; POST can send any type of data , including strings, videos, sounds, pictures, etc.

(4) W3C recommendations: GET requests are suitable for obtaining data from the server; POST requests are suitable for transmitting data to the server .

7. How to choose between GET request and POST request?

(1) If you are obtaining resources from the server, such as searching, it is recommended to use GET; if you are submitting data to the server, it is recommended to use POST.

(2) If there is sensitive data , such as login, use POST .

(3) The transmitted data is not a string, such as file upload, which must be POST.

(4) If there is a lot of data to be transmitted, use POST.                 

3. Servlet

1. Servlet runs in the Servlet container (Web application server/Tomcat) and is responsible for communicating with the client.

2. Static page development technology: HTML, css, javascrpit

3. Dynamic page development technology: JSP/Servlet, ASPX, PHP

4. Srevlet configuration

(1) XML file-based method: configured in web.xml

(2) Annotation-based approach: @WebServlet

5. Servlet life cycle methods

(1) Parameterless constructor: When the servlet is accessed for the first time, the constructor is called to create the object. Only called once .

(2) init: Called only once (called once when accessing the Servlet for the first time) to initialize the object.

(3) Service: Call N times to execute the business logic method. This method will be called every time the servlet is accessed.

(4) destroy: Called only once , before the servlet object is destroyed, to complete work such as cleaning up resources .

4. JSP basic syntax

1. The main function of JSP (Java Server Pages): to replace the Servlet program and return html pages.

2. The essence of JSP is a Servlet. When the jsp page is accessed for the first time, the Tomcat server will translate the jsp page into a java source file and compile it into a .class file.

3. JSP embeds Java code into static HTML to produce dynamic output; the Java code in the JSP page cannot be seen in the client's HTM source code.

4. There are three ways to embed Java programs in JSP: JSP program segments, JSP statements, and JSP expressions

5. JSP program segment

(1) Function: Execute Java logic code

(2) Format: <% Java code %>     

(3) Features: After the JSP program segment is translated, it is in the _jspService () method.

6. JSP declaration

(1) Function: Define methods and attributes for java classes translated from jsp.

(2) Format: <%! Declaration of java code%>

(3) Features: JSP declarations will be placed in Java classes after translation.

7. JSP expression

(1) Function: Output data on the jsp page.

(2) Format: <%= expression%>

(3) Features: JSP expressions will be translated into the _jspService() method; JSP expressions will be translated into out.print() and output to the page; JSP expressions cannot end with a semicolon.

8、out.print()和out.write()

(1) print() is defined in the subclass JspWriter, and write() is a method of the Writer class.

(2) print() can convert various types of data into string output, while write() can only output character-related data such as characters, character arrays, and strings.

(3) Both print() and write() can be used to output strings . However, if the value of the string object is null , the print method will output a string with the content of "null" , while the write method will throw NullPointerException exception.

6. JSP built-in objects (1)

1. request is of HttpServletRequest type, common methods:

(1) String getContextPath (): Get the context path of the current web application , such as /web6

(2) String getMethod (): Returns the client request method , usually GET/POST

(3) String[] getParameterValues ​​(String key): Get value through key

(4) String getParameter(String key): Get the first element in the value one-dimensional array through key .

(5) void setCharacterEncoding (String charset): Set to setCharacterEncoding("utf-8"), used to solve Chinese garbled characters in post requests.

(6) void setAttribute (String key,Object value): Save data in the form of key-value pairs.

(7) Object getAttribute (String key): Get value through key .

(8) RequestDispatcher getRequestDispatcher (String path): Returns a RequestDispatcher object whose forward method is used for request forwarding.

2. response is the HttpServletResponse type. Commonly used methods:

(1) void setCharacterEncoding (String charset): Specify the encoding that the server responds to the browser.

        The data sent by the server to the browser is encoded according to ISO-8859-1 by default. After the browser receives the data, it is decoded according to the default character set (usually GBK) and displayed.

(2) void setContentType (String type): Specifies the encoding of the server response to the browser. At the same time, the browser also re-encodes (or decodes) the data it receives based on this parameter . Common usage is setContentType("text/html;charset=UTF-8"); 

(3) PrintWriter getWriter (): Get the character stream leading to the browser

(4) ServletOutputStream getOutputStream (): Get the byte stream leading to the browser . For example, ImageIO.write(image, "jpg", response.getOutputStream()) is used to output the image on the browser.

(5) void sendRedirect (String path): Redirect page
(6) void addCookie (Cookie cookie): Add Cookie

3. Resource jumps in the Web include two methods: forwarding and redirection.

     (1)转发: request.getRequestDispatcher("/b").forward(request, response);

      Forwarding is a resource jump within the server, using the server-side path.

     (2) Redirect: response. sendRedirect ( request.getContextPath() + "/b");

     The redirection uses the client path.

4. The difference between forwarding and redirection:

(1) Forwarding is triggered by request ; redirection is triggered by response

(2) Forwarding is one request , and the browser address remains unchanged ; redirection is two requests , and the browser's address changes .

(3) Forwarding can only complete resource jumps on the server side ; redirection can also realize cross-app resource jumps .

5. When to use forwarding and when to use redirection?

(1) If you want to realize cross-app resource jump, you must use redirection .

(2) If values ​​need to be passed through requests between two pages, forwarding must be used .

(3) Redirection can prevent the problem of "browser refresh , causing users to submit forms repeatedly ".

6. Form

(1) The most basic tag of the form is <input>, and its attribute type determines the type of the form element.

text: text box; password: password box; radio: radio button; checkbox: check box; reset: reset button; button: normal button; submit: submit button

(2) <textarea>: multi-line text box

(3) <select>: drop-down menu

7. JSP built-in objects (2)

1. The session object is of type HttpSession, which represents the process of a session between the server and the client. The session object is stored in the server and is used to save the data required for a specific user session. Within a session, variables stored in the session object will not be lost when the user jumps between Web pages.

2. The session object is usually used to save cross-request data: verification code, logged-in user information, shopping cart

3. The server uses a " timeout mechanism " to determine whether the client's session has ended.

4. Forced invalidation of session : call the invalidate() method of the HttpSession object

5. Customize the session expiration time

(1) Manually set the session expiration time in the program

session.setMaxInactiveInterval(30 * 60); //Expiration time unit is seconds

(2) Configure the session expiration time in the project's web.xml file

<!—Expiration time unit: minutes-->

<session-config>

      <session-timeout>30 </session-timeout> 

  </session-config>

(3) Configure the session expiration time in the <Tomcat installation directory>\conf\web.xml file

6. The four major domain objects of JSP

(1) Page scope: The built-in object is pageContext, type is PageContext, and is only used in the current jsp page.

(2) Request scope: The built-in object is request, type is HttpServletRequest, and is valid within one request .

(3) Session scope: The built-in object is session, type is HttpSession, and is valid within a session.

(4) Application scope: The built-in object is application, type is ServletContext, corresponds to the entire web application, and is shared by all sessions.

8. Cookies

1. Cookie is not a built-in object of JSP.

2. The difference between session and cookie

(1) Session : Server-side session technology , data is saved on the server ; the saved data is Object ; it is destroyed with the end of the session

(2) Cookie : client session technology , data is saved on the client ; the saved data is String ; it can be stored in the client's computer for a long time

3. Cookie life refers to the validity time of the cookie on the client.

(1) setMaxAge(-1): The default value of the cookie's maxAge attribute is -1, which means it only survives in the browser memory. The cookie disappears once you close your browser.

(2) setMaxAge(60*60) : Indicates that the cookie object can survive for 1 hour. When the life is greater than 0 , the browser will save the cookie to the hard disk . Even if the browser is closed or the client computer is restarted, the cookie will survive for 1 hour ;

(3) setMaxAge(0) : If the browser has saved the cookie, you can delete the cookie through the cookie's setMaxAge(0). This cookie will be deleted whether in the browser memory or on the client's hard drive.

4. Special characters and Chinese cookie processing

(1) Use the URLEncodor.encode() method to store Chinese in Cookie.

        String name = URLEncoder.encode("姓名", "UTF-8");

        String value = URLEncoder.encode("张三", "UTF-8");

        Cookie c = new Cookie(name, value);

        response.addCookie(c);

(2) When obtaining Cookie, you need to use the URLDecoder.decode() method to decode it first.

Cookie[] cookies = request.getCookies();

if (cookies != null) {

                 for (Cookie cookie : cookies) {

                        String name = URLDecoder.decode(cookie.getName(), "UTF-8");

                        String value = URLDecoder.decode(cookie.getValue(), "UTF-8");

                        out.print(name + ": " + value + "<br/>");

             }

}

5. The role of the cookie path is to determine which cookies saved on the browser side need to be brought to the server when the browser accesses a resource on the server .

★★★ 6. If the cookie path is not set, the default is the path of the current resource . For example, the path of http://localhost:8084/web8/a/AServlet is: web8/a

    In this way, when accessing the following resources, only those under the path web8/a will bring the cookies saved by AServlet:

        http://localhost:8084/web8/a/AServlet (same path)

        http://localhost:8084/web8/a/xxxxx (same directory)

        http://localhost:8084/web8/a/xxxxx/xxxx (subdirectory)

★★★  7. Set the cookie path through void setPath(String uri).

      1), cookie.setPath("/");//Set the cookie path to the current server 

           For example: http://localhost:8084/web8/a/AServlet, this path, as long as it is at http://localhost:8084

The cookies saved by ASerlet will be included in the path .  

          http://localhost:8084/web8/a/AServlet (same path)

          http://localhost:8084/web8/a/xxxxx (same directory)

          http://localhost:8084/web8/a/xxxxx/xxxx (subdirectory)

          http://localhost:8084/web8/b/xxxxx/ (different directory)

          http://localhost:8084/web9/a/xxxxx (different path)

      2), cookie.setPath(request.getContextPath());//Set the cookie path to the current web application

            For example: http://localhost:8084/web8/a/AServlet, this path, as long as it is under the web8 path, will bring the cookie saved by ASerlet.    

          http://localhost:8084/web8/a/AServlet (same path)

          http://localhost:8084/web8/a/xxxxx (same directory)

          http://localhost:8084/web8/a/xxxxx/xxxx (subdirectory)

          http://localhost:8084/web8/b/xxxxx/ (different directory)

9. JDBC connection to mysql

1. There are two problems with using Statement for development:

(1) String strings need to be spliced ​​frequently, and the error rate is high.

(2) There is a risk of SQL injection.

2. PreparedStatement (preprocessing) is a subclass of Statement and provides the function of SQL placeholder. PreparedStatement uses the "?" placeholder to improve the readability and maintainability of the code, and this method of binding parameters can effectively prevent SQL injection attacks.

1. Multiple choice questions

        1.  ( Single-choice question ) Which of the following Java versions is used to develop websites with high traffic, large data volume, and high concurrency (   )

                A. J2SE        B. J2EE        C. J2ME              D. J2WE

        2.  ( Single-choice question ) There is the following code:

        The annotation statement equivalent to the above code is ( )

                A. @WebServlet("/t")              B. @WebServlet("/test")

               C. @WebService("/t")              D. @WebService("/test")

        3.  ( Single choice question ) In order to retain the annotation when the program is running, the value of @Retention should be set to (   )

                A. RetentionPolicy.SOURCE               B. RetentionPolicy.CLASS

                C. RetentionPolicy.RUNTIME             D. RetentionPolicy.JVM

        4.  ( Single choice question ) The meta-annotation used to specify where the annotation is used is (      )

                A. @Target                              B. @Retention

                C. @Documented                    D. @Inherited

        5.  ( Single choice question ) Which statement about JSP is wrong (    )

                A. After the JSP program segment is translated, it is in the _jspService () method

                B. The JSP declaration will be placed in the Java class after translation

                C. The JSP expression is translated in the _jspService() method

                D. <%=msg%>The translated code is: out.write(msg)

        6. (Single choice question) The output result of the following code is

                A. str=                                      B. str=null

                C. An exception is thrown during runtime. D.  Compilation error occurs and cannot be run.

        7.  ( Single choice question ) The data type of the JSP built-in object application is (     )

                A. Appliction                                   B. ServletConfig

                C. ServletContext                            D. ServletAppliction

        8.  ( Single choice question ) The JSP page is converted to ( ) by the JSP engine when it is run for the first time.   

                A. CSS file B. HTML file

                C. Java file                              D. Javascript file

                9.  ( Single choice question ) JSP is essentially a (    )

                A. HTML     B. Servlet     C. Filter        D. Javascript

        10.  ( Single choice question ) The output result of the following code is (        )

<% 
     String str = null;   
     out.write(str);  
%>

                A. Output in the browser: null B. Blank display in the browser

                C. A null pointer exception is thrown during runtime.            D.  A compilation error occurs and cannot be run.

        11.  ( Single choice question ) When the data sent to the server is not a string, the method attribute of the <form> tag needs to be set to

                A. hidden            B. post          C. get           D. submit

        12.  ( Single choice question ) The code that defines the JSP program segment is (      )

                A. <%= JSP program segment%>                B. <% JSP program segment %>

                C. <%! JSP program segment%> D. <% -- JSP program segment %>

        13. (Single choice question) In the Servlet life cycle method, the method used to execute business logic is ( )

                A. Parameterless constructor B. init()

                C. service()                                      D. destroy()

        14. (Single choice question) The JSP code equivalent to out.print(msg) is ( )

                A. <%=msg%>                                B. <%msg%>

                C. <%--msg%>                                D. <% msg%>

        15. (Single choice question) Store the value of the count variable in the application object with the attribute name "count". The code used is:

                A. application.setAttribute("count", count)

                B. application.setAttribute(count,"count")

                C. application.getAttribute(count,"count")

                D. application.getAttribute("count", count)

        16. (Single choice question) The execution result of the following program is:

                A. 99

                    The value of a is: 99

                B.
                    The value of c a is: 99

                C. 99

                     The value of a is: c

                D.c

                   The value of a is: c

        17. (Single choice question) The <select> tag in the form means ( )

                A. Radio button B. Check box

                C. Drop-down menu                         D. Multi-line text box

        18. (Single choice question) The <input type="radio"> tag in the form represents ( )

                A. Reset button B. Submit button

                C. Check box                             D. Radio button

        19. (Single choice question) The @Override annotation is only retained in the source code stage, and its @Retention value is ( )

                A. RetentionPolicy.SOURCE            B. RetentionPolicy.CLASS

                C. RetentionPolicy.RUNTIME          D. RetentionPolicy.JVM

        20. (Single choice question) To hide the parameters transmitted to the server in the browser's address bar, you need to set the method attribute of the <form> tag to

                A. hide         B. get    C. post   D. submit

        21. (Single choice question) Regarding POST and GET, which statement is wrong ( )

                A. POST submits data in the request body

                B. GET submits data in the request line

                C. The transmitted data is not a string, GET should be used

                D. The transmitted data contains sensitive data and POST should be used.

        22. (Single choice question) Click the "Submit" button, and the server resource edit can obtain the parameter "index=<%=index%>", then the code that should be filled in underlined is ( )

                A. method = "post"                          B. method = "get"

                C. method = "hide"                          D. method = "submit"

        23.  ( Single choice question ) In JSP , the code that defines JSP expression is (    )

                A. <%=JSP expression%>                   B. <% JSP expression %>

                C. <%! JSP expression%> D. <%--JSP expression %>

        24. (Single choice question) The <textarea> tag in the form represents ( )

                A. Single-line text box                                B. Multi-line text box

                C. Radio button D. Check box

        25. (Single choice question) It is known that the context path of the website is "/demo", and the code should be used to redirect to welcome.jsp under the current website.

                A. response.sendRedirect(request.getContextPath() + "/welcome.jsp");

                B. request.getRequestDispatcher("/welcome.jsp").forward(request, response);

                C. response.sendRedirect("/welcome.jsp");

                D. response.sendRedirect("welcome.jsp");

        26. (Single choice question) The function of the statement response.setCharacterEncoding("utf-8") is ( )

                A. Set the encoding scheme of the request body to utf-8

                B. Set the encoding of the server response to the browser to utf-8

                C. Set the browser's decoding scheme for the data it receives to utf-8

                D. Set the encoding of the server response to the browser and the browser's decoding scheme to utf-8

        27. (Single choice question) When the post request data contains Chinese, the code ( ) should be used before obtaining the Chinese data.

                A. request.setCharacterEncoding("utf-8")

                B. response.setCharacterEncoding("utf-8")

                C. request.setContentType("text/html;charset=utf-8")

                D. response.setContentType("text/html;charset=utf-8")

        28. (Single choice question) In order to make the session expiration time effective for all web applications of the Tomcat server, the configuration file that should be modified is:

                A. <Tomcat installation directory>\conf\server.xml

                B. <Tomcat installation directory>\conf\tomcat-users.xml

                C. <Tomcat installation directory>\conf\context.xml

                D. <Tomcat installation directory>\conf\web.xml

        29. (Single choice question) The main function of JSP is ( )

                A. Design web page special effects                     B. Replace the Servlet program to return the html page

                C. Beautify web pages D. Filter HTML , Servlet and other web resources

        30. (Single choice question ) The mechanism used by the web server to determine whether the client's session has ended is ( )

                A. Autonomous storage mechanism              B. Timeout mechanism

                C. Encryption mechanism D. Deadlock mechanism

        31. (Single choice question) The correct code to define the session expiration time as 30 minutes is ( )

                A. session.setMaxInactiveInterval(30*60)

                B. session.setMaxInactiveInterval(30)

                C. session.setMaxAge(30*60)

                D. session.setMaxAge(30)

        32. The character encoding scheme for Emoji expressions is (    )

                A.utf-8                               B.gbk

                C.big5                                D.iso8859-1

        33. [ Single-choice question ] There is the following code, page1.jsp :

        page2.jsp:

When the user opens page1.jsp and directly clicks the " Submit " button without performing any operations on the page , the output result of page2.jsp is

                A.

                        Name is:

                        Gender: male

                        The first interest is: sport

                B.

                        Name is: null

                        Gender is: null

                        The first interest is: sport

                C.

                        Name is: null

                        Gender is: null

                        The first interest is: null

                D.

                        Name is:

                        Gender is:

                        The first interest is: sport

        34. Click " I want to register " and jump to register.jsp under the current website . The code that should be filled in underlined is ( ).      

                <a href="<%=_______________%>/register.jsp" >I want to register</a>

                A.request.getContextPath() ;                  B.request.getContextPath() 

                C.response.getContextPath() ;               D.response.getContextPath() 

        35. The complete function of the statement response.setContentType("text/html;charset=utf-8") is expressed as (          )        

                A. Set the encoding scheme of the request body to utf-8

                B. Set the encoding of the server response to the browser to utf-8

                C. Set the browser’s decoding scheme for the data it receives to utf-8

                D. Set the encoding of the server response to the browser and the browser's decoding scheme to utf-8

36. Set the source of the image to /checkCodeServlet         under the current website , then the code that should be filled in underlined is

                 <img id="vCode" src="_______________________/checkCodeServlet">

                A.<%=request.getContextPath() ; %>    B.<%=request.getContextPath()%>

                C.<%=response.getContextPath() ; %>  D.<%=response.getContextPath()%>

        37. To output the image image to the browser page, the code that should be used is (     )

                A.ImageIO.write(image, "jpg", request.getOutputStream());

                B.ImageIO.write(image, "jpg", request.getWriter());

                C.ImageIO.write(image, "jpg", response.getWriter());

                D.ImageIO.write(image, "jpg", response.getOutputStream());

        To store the verification code text when the user logs in, the JSP built-in object that should be used is (       )

                A.pageContext                                B.request

                C.session                                          D.appliction

        38. The method to customize the session expiration time in the program is (      )

                A.session.setMaxInactiveInterval()        B.session.setMaxAge()

                C.session.setMaxLife()                           D.session.setMaxTime()

        39.The correct statement about cookies is ( )         

                A.The data saved by the cookie is stored on the server

                B. Close the browser and the data saved by the cookie will be lost.

                C.Cookie is called the client's session technology

                D.The data saved in the cookie is Object

        40 [ Single choice question ] The correct code to delete cookies is ( )           

                A.cookie.setMaxAge(0);  request.addCookie(cookie);

                B.cookie.setMaxAge(0);  response.addCookie(cookie);

                C.cookie.setMaxAge(-1);  request.addCookie(cookie);

                D.cookie.setMaxAge(-1);  response.addCookie(cookie);

        41. The following code is provided:

Then when the sname parameter value is ( ), the above code will delete all records in the student table.

               A.' or '1'='1   B.' or '1'='1'       C.' and '1'='1       D.' and '1'='1'

2. Multiple choice questions

        1. (Multiple choice question) Dynamic page development technologies include ( )

                A. JSP  B. Servlet  C. HTML  D. CSS  E. ASPX

        2. (Multiple choice question) The life cycle methods of Servlet include ( )

                A. Parameterless constructor B. init() C. destroy() D. service()   E. doFilter()

        3. (Multiple choice question) Software belonging to java IDE includes ( )

                A. netbeans   B. eclipse  C. idea   D. mysql  E. sql server

        4. (Multiple choice question) Among the following situations, the situation of sending a get request to the server is ( )

                A. Directly enter the URL in the browser address bar and press Enter

                B. Click on the hyperlink on the browser

                C. When using the form to submit data, the method attribute is not written in the form tag.

                D. In the form tag, specify the method attribute as: method="get"

                E. In the form tag, specify the method attribute as: method="post"

        5. (Multiple choice question) Static page development technologies include ( )

                A. JSP          B. Servlet     C. HTML            D. CSS         E. Javascript

        6. (Multiple choice question) In the life of a Servlet, methods that are only executed once include ( )        

                A. Parameterless constructor B. init() C. destroy()    D. service()    E. servlet()

        7. (Multiple choice question) It is known that the sage field is defined as int type in the student table. The following code is used to query the student's student number sno and name sname based on the age entered by the user.

        When the input age is ( ), the sno and sname of all records in the student table will be output.

                A. 1 or 1=1   B. ' or '1'='1   C. 1 or true   D. 12 or 2=2   E. 2 or true

        8. The correct statement about request forwarding and redirection is (      ).

                A. Request forwarding uses the client path

                B. The redirection uses the server-side path

                C. If you want to realize cross-app resource jump, you must use redirection.

                D. If values ​​need to be passed through request between two pages, forwarding must be used

                E. Redirection can prevent the problem of " browser refresh, causing users to submit forms repeatedly "

9. JSP built-in objects         called domain objects include (       )

                A.application  B.session  C.response  D.request  E.pageContext

        10. Which statement about session is wrong ( )

                A.session object is stored in the server

                B. When the browser is closed, the sessionID stored in the browser disappears, and the session object in the server also disappears.

                C. If Servlet is the first resource accessed by the browser, the server will create a session object for this session by default.

                The function of D.session.setMaxInactiveInterval(60) is to set the session expiration time to 60 minutes

                The data in the E.session object can only be used within one request and cannot be shared by different requests.

        11. What is the correct statement about session and cookie ( )   

                A.session and cookies are both session technologies

                B.session data is stored on the server side, and cookie data is stored on the client side.

                The data saved by C.session is String

                D.session is destroyed when the session ends, and cookies can be stored in the client computer for a long time.

                E.The data saved by cookie is Object

        12. The known cookie- related code in AServlet is:

     Cookie c = new Cookie(“name”,”lucy”);
     cookie.setPath("/");
     request.addCookie(c);

        Among them, the context path of the website corresponding to AServlet is: /web8 , and the path for the browser to access AServlet is: http://localhost:8084/web8/a/AServlet . Then, the resource of data name=lucy saved in AServlet can be obtained. The path is ( )  

                A.http://localhost:8084/web8/a/AServlet

                B.http://localhost:8084/web8/a/BServlet

                C.http://localhost:8084/web8/a/bbb/CServlet

                 D.http://localhost:8084/web8/b/DServlet

                E.http://localhost:8084/web9/EServlet

3. Questions and answers and analysis questions

[Example 1] Why does "request forwarding" cause form information to be repeatedly submitted through refresh, but redirection does not? Please briefly describe the reasons.

Answer: (1) Request forwarding will not change the address in the browser . Even if many other resource paths pass through, the browser will still maintain the original access path. Once the browser is refreshed, the browser will send the address now in the browser to the server again. This is no different than clicking the "Submit" button of a form. Therefore, request forwarding will cause the user to submit the form repeatedly.

(2) Redirection will change the address in the browser. Each redirection will change the browser address to the path to the last accessed resource. Therefore, even if the browser keeps refreshing, it is only constantly accessing the final resource , instead of constantly sending the initial access path like the refresh request forwarding. Therefore, the redirect will not cause a duplicate submission of the form


[Example 2] Why does closing the browser end the session? Please briefly describe the reasons.

Answer: Close the browser and the sessionID in the cache in the browser will disappear . When the browser sends a request to the server again, the server cannot find the corresponding session object because there is no sessionID . The session object cannot be found, which is equivalent to the end of the session.


[Example 3] The first resource that the browser accesses from the server is a JSP file. Will the server immediately create an HttpSession object?

Answer: Not necessarily . If the current JSP is the first resource accessed by the client, but the session attribute value of the JSP's page directive is false , the server will not create an HttpSession object for the JSP.


[Example 4] Why can preparestatement prevent SQL injection attacks?

Answer: Because prepareStatement uses a precompilation mechanism . When creating the prepareStatement object, the SQL statement is precompiled, and then the parameters are passed in. The parameter passed at this time is only considered to be the value of a certain field and will not be recognized as a SQL instruction . For example, a parameter like ' or '1'='1 will not be regarded as an or instruction, but only the value of a certain field.


[Example 5] In a mall, you put several items into the shopping cart without logging in. After closing the browser, when I open the browser again to visit the mall, the items in the shopping cart are still there. How do I do this?

Answer: Put the item number in the shopping cart into a cookie , and the cookie is saved in the client's hard drive file . This happens even if the browser is closed. The cookie is still on the hard drive. When you open the mall again and view the shopping cart, the server reads the cookie stored in the client's hard drive , gets the product number, and dynamically displays the products in the shopping cart.


[Example 6] The function of the cookie.jsp file is to output the names and values ​​of all cookies stored by the browser on the page. Please briefly describe possible problems with the following code and provide solutions.

 cookie.jsp代码:
  <%
     Cookie[] cookies = request.getCookies();
     for (Cookie cookie : cookies) {
        out.println(cookie.getName() + ":" + cookie.getValue() + "<br/>");
      }           

   %>

Answer: (1) Question: When no cookies are stored in the browser , the statement for (Cookie cookie : cookies) {} will report a null pointer exception .

        (2) Solution: Make a null pointer judgment before traversing the cookies array

if (cookies != null) {
  for (Cookie cookie : cookies) {
                    …
          }
  }

 [Example 7] In login.jsp, a check box is defined, the code is as follows:

                 <input type="checkbox" name="reb" id="reb" value="y">记住我

                In LoginServlet.java, the Java code to determine whether the check box is selected is:

String reb = request.getParameter("reb");

if (reb.equals("y")) {

    System.out.println("用户选择了记住我!") ;  

else {

    System.out.println("用户没有选择记住我!");

}

Please briefly describe the runtime problems of the LoginServlet.java code and the corresponding solutions.

Answer: (1) Question: When the user does not select the "Remember Me" checkbox, reb.equals("y") will report a null pointer exception.

       (2) Solution: Change reb.equals("y") to "y".equals(reb)


[Example 8] There are two pieces of code as follows:

page1.jsp:

       <form action="page2.jsp" method="post">

            用户名:<input type="text" name="username"><br>

            密码:<input type="password" name="userpass"><br>

            <input type="checkbox" name="remember" value="yes">记住我<br>                                    

            <input type="submit" value="登录">                     

        </form>
page2.jsp:

<%

        String username = request.getParameter("username");

        String userpass= request.getParameter("userPass");

        String remember = request.getParameter("remember");

%>

If you do not enter the username and password, and "Remember me" is not selected, and you click the "Login" button, what are the values ​​of username, userpass, and remember respectively?

答:""、null、null   

[Analysis] If you do not enter the username and password, and "Remember Me" is not selected, the parameters passed to page2.jsp are: username=&userpass=

        therefore:

                  String username = request.getParameter("username");  // 返回 ""

                String userpass= request.getParameter(" userPass "); //The parameter name is in wrong case, there is no data corresponding to userPass, and null is returned.

                String remember = request.getParameter("remember"); //If the check box is not selected, there is no remember in the parameter, so null is also returned.


[Example 9] Set the following code.

page1.jsp:

      <form action="page2.jsp" method="post">

            用户名:<input type="text" name="username"><br>

            密码:<input type="password" name="userpass"><br>

            性别:<input type="radio" name="gender" value="male">男

                 <input type="radio" name="gender" value="female">女<br>

            爱好:<input type="checkbox" name="interests" value="sport" checked>体育

                <input type="checkbox" name="interests" value="music">音乐<br>

            <input type="submit" value="提交">                     

        </form>                    

 page2.jsp:

        <% // 以下代码的getParameter()中填写的参数名均正确

            out.println("用户名为:"+request.getParameter("username")+"<br>");

            out.println("密码为:"+request.getParameter("userpass")+"<br>");

            out.println("性别为:"+request.getParameter("gender")+"<br>");

            out.println("第一项爱好为:"+request.getParameter("interests"));

        %>

When the user opens page1.jsp and directly clicks the "Submit" button without performing any operations on the page, what is the output of page2.jsp?

answer:

Username:
Password:
Gender: null   

The first hobby is: sport


[Example 10] The code to create the users table in the mysql database and the data in the users table are as follows

create table users

(user_id int primary key auto_increment,

username varchar(20) unique,

userpass varchar(20),

salary decimal(18,2)

);

Now use the following java code to obtain the username and password transmitted by the front end; after successful verification, the user's salary will be displayed. Please explain the SQL injection attacks that appear in the code and give methods to solve the injection attacks.

Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/my_db";
String user = "root";  String password = "123456";
Connection connection = DriverManager.getConnection(url, user, password);

//接收前端数据:用户名username和密码userpass
String username = req.getParameter("username");
String userpass = req.getParameter("userpass");
String sql = " select salary from users where username='" + username + "'"
                                        +" and userpass='"+userpass+"'" ;
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
resp.setContentType("text/html;charset=utf-8");
if (resultSet.next()) {
    BigDecimal salary = resultSet.getBigDecimal("salary");

//salary在mysql为decimal类型,在java中对应的数据类型为BigDecimal
    resp.getWriter().println("您的薪水为:"+salary);
}else{
    resp.getWriter().println("用户名或密码不正确!无权查看薪水");
}

Answer: (1) SQL injection example: Enter the username: lisa '# through the front end , and fill in the password userpass as you like, and you can view the salary of user lisa.

(The following is an explanation, there is no need to fill it in when answering the question:

       # is the comment symbol of mysql, so when the username is: lisa '# , all the codes after # are invalid, then the executed sql statement is:

                select salary from users where username=' lisa'

        That is, the operation of finding records based on user names is implemented. In the same way, to check susan's salary, you only need to enter the username on the front end: susan'# . Password verification is successfully bypassed through the username in the above form, so this username is also called a "universal password".

        Interested students can build the front-end interface by themselves and add exception handling and other codes based on the back-end code provided above to verify the "universal password" in this example)

        (2) Solution: Use PreparedStatement instead of Statement.

                Replace lines 7-10 with:

String sql = "select username,salary from users where username=? and userpass=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,username);
preparedStatement.setString(2,userpass);
ResultSet resultSet = preparedStatement.executeQuery();

4. Program fill in the blanks

★★★

1.  ( Fill in the blank ) The display result of the first visit to product.jsp is shown in Figure 1. Each hyperlink represents a product category. When any hyperlink is clicked, the corresponding product category will be stored in the cookie . The next time you access product.jsp within 7 days , the product category you visited last time will be displayed on the page, as shown in Figure 2 .

        

         (1) request.getCookies()                      (2) cookie.getName()

         (3) cookie.getValue()                             (4) request

         (5) !item.contains(item)                          (6) URLEncoder.encode(item, "utf-8")

          (7) response.addCookie(c)


★★★ 

2. (Fill in the blank) Dbutils is a general class for accessing databases.

(1) this                        (2) conn               (3) sql                         (4) pstmt

(5) i + 1                      (6) params[i]         (7) executeUpdate()   (8) null


★★★

3. (Fill in the blank) Use Dbutils defined in the previous question to realize user login.

Note: When registering, the password is md5 encrypted and stored in the database. The characteristic of the md5 algorithm is that under the same environment, the same string encryption results will be the same.


        (1) new Dbutils()                             (2) stringToMD5(userpass)

        (3) executeQuery(sql, params)        (4) resultSet.next()

        (5) resp                                            (6) req


 4.LoginServlet is used to implement the login function. When the username and password are correct, the username is stored in the session and jumps to the welcome.jsp page; otherwise, the error message is forwarded to the login.jsp page. Please fill in the correct code where underlined.

1st empty req _

2nd empty HttpSession _

3 getSession() getSession(true) getSession(false)

4th empty username _

No. 5 / welcome.jsp

No. 6 empty req,resp


★★★

5. In a JSP or Servlet, count the number of website visits.

        Notice:

                (1) In JSP, access the ServletContext object directly through application.

                (2) In doGet() / doPost() of the HttpServlet subclass, the code to obtain the ServletContext object is:

public class CountServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, 
          HttpServletResponse resp) throws ServletException, IOException {
   ServletContext application = getServletContext();
  //或者:ServletContext application = req.getServletContext();
    }
}

★★★  6. Record the last login time

import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat; 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  
@WebServlet("/LastAccessServlet")
public class LastAccessServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//指定服务器输出内容编码方式为UTF-8
   		response.setContentType("text/html;charset=utf-8");
   		String LastAccessTime = null;   		
   		//获取所有的cookie,并将这些cookie存放在数组中
   		Cookie[] cookies = request.getCookies();   		
   		//遍历cookie数组
   		for(int i=0;cookies!=null && i<cookies.length;i++) {
   			//如果cookie的名称为lastAccess,则获取该cookie的值
   			if("lastAccess".equals(cookies[i].getName())) {
   				LastAccessTime = cookies[i].getValue();
   				break;
   			}
   		}
   		if(LastAccessTime==null) {
   			response.getWriter().print("您是首次访问本站!!!!");
   		}else {
   			response.getWriter().print("您上次的访问时间是"+LastAccessTime);
   		}		
   		//创建cookie,将当前时间作为cookie的值发送给客户端
   		String currentTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
   		Cookie cookie = new Cookie("lastAccess", currentTime);   		
   		//发送cookie
   		response.addCookie(cookie);
	} 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	} 
}

★★★

7. Use the general database access class Dbutils to achieve pseudo-deletion of data.

     (1) What is pseudo-deletion?

          In the database, records deleted through the delete statement cannot be "retrieved with one click". In order to allow website users to quickly "retrieve" accidentally deleted data, pseudo-deletion of data needs to be implemented.

        Pseudo deletion means that the data is not actually deleted in the database, but the data is marked as deleted through a mark. This is useful in situations where a history of data needs to be preserved. Implementation ideas of pseudo deletion:

        Add a field to the table: is_deleted (boolean type), and set the default value of is_deleted to 0 (logical false)

        Once a record is deleted, set the record's is_deleted value to 1 (logical true)

           update student set is_deleted=1 where sno='99001' and is_deleted=0 # Delete the student record of 99001

        When selecting records, add the restriction condition is_deleted =0

              select * from student where is_deleted = 0 #Browse all records in the student table

        (2) Mysql database code (for students to use when doing their own operations, just read it)

create table student

(sno char(5) primary key,

sname varchar(50),

sage int,

is_deleted boolean default 0);

insert into student(sno,sname,sage) 
values('99001','lisa',20),('99002','mary',21);

(3) Core code of Servlet

Dbutils dbutils = new Dbutils();
String sql = "update student set is_deleted=1 where sno=? and is_deleted=0";
String sno = req.getParameter("sno"); 
Object [] params = {sno};//将前端输入的学号作为sql参数
int i =dbutils.executeUpdate(sql,params);
resp.setContentType("text/html;charset=utf-8");
if (1==i) {
    resp.getWriter().println("成功删除学号为:"+sno+" 学生的记录");
}else {
    resp.getWriter().println("该生不存在,删除失败");
}

5. Self-pickup of information (if expired, please leave a message)

Link: https://pan.baidu.com/s/1Fpi28ZTNnZD1LRNXvem--Q?pwd=ugn2 
Extraction code: ugn2 

Guess you like

Origin blog.csdn.net/qq_52495761/article/details/135424420