JavaWeb study notes arrangement (middle)

Request

content
  1. request header
  2. Request parameter focus
  3. Domain Object Functional Highlights
  4. request forwarding focus
  5. Other methods, get client information, url-related information...

request as a function of a domain object

Only valid within the same request

How to get request headers

The methods related to the request header are:

  • String getHeader(String name): Get the request header of the specified name;
  • Enumeration getHeaderNames(): Get all request header names;
  • int getIntHeader(String name): Get the request header whose value is int type.

Other methods

  • int getContentLength(): Get the number of bytes in the request body, GET request has no request body, no request body returns -1;
  • String getContentType(): Get the request type, if the request is GET, then this method returns null; if it is a POST request, then the default is application/x-www-form-urlencoded, indicating that the content of the request body uses URL encoding;
  • String getMethod(): returns the request method, for example: GET
  • Locale getLocale(): Returns the Locale of the current client browser. java.util.Locale represents country and language, which is useful in internationalization;
  • String getCharacterEncoding(): Get the request encoding, if there is no setCharacterEncoding(), then return null, indicating that the ISO-8859-1 encoding is used;
  • void setCharacterEncoding(String code): Set the request encoding, only valid for the request body! Note that for GET there is no request body! ! ! So this method is only valid for the parameters in the POST request! focus
  • String getContextPath(): returns the context path, for example: /hello
  • String getQueryString(): Return the parameters in the request URL, for example: name=zhangSan
  • String getRequestURI(): Returns the request URI path, for example: /hello/oneServlet
  • StringBuffer getRequestURL(): Returns the request URL path, for example: http://localhost/hello/oneServlet, which returns path information except parameters;
  • String getServletPath(): returns the Servlet path, for example: /oneServlet
  • String getRemoteAddr(): returns the IP address of the current client;
  • String getRemoteHost(): returns the host name of the current client, but the implementation of this method still obtains the IP address;
  • String getScheme(): Returns the request protocol, for example: http;
  • String getServerName(): returns the host name, for example: localhost
  • int getServerPort(): returns the server port number, for example: 8080

request forwarding

Dynamic resources (Servlet) jump to other resources (Servlet, html, jsp...)

Forward wording

  1. RequestDispatcher getRequestDispatcher(String path) Get the forwarder object

  2. Call the forward(request,response) of the RequestDispatcher object

    RequestDispatcher.forward(request,response);

1 and 2 combined:

request.getRequestDispatcher(String path).forward(request,response);

Forwarding features:

  1. make only one request
  2. The client url will not change
  3. Server-side forwarding can only be forwarded to internal resources of the server
The request field is generally used in request forwarding

Get request parameters

Method 1: String getParamter(String name) Get a value corresponding to a request parameter name according to name

The first case: the front end passes the request parameter name, and passes the value

Result: passed value

The second case: the front end passes the request parameter name, without passing the value username=&email=111

result: ""

The third case: the front end does not pass the request parameter name

Result: null

Method 2: String[] getParameterValues(String name) A request parameter name corresponds to multiple values ​​For example, get the value of a check box
//一个请求参数名对应多个值
 String[] love = request.getParameterValues("hobbyArr");//获取爱好(复选框)
//数组转换为集合
 List<String> hobbyList = Arrays.asList(hobbyArr);
 System.out.println("love:"+loveList);
//数组转换集合 Arrays.asList(arr)
//asList()这个方法返回的ArrayList不是集合体系中的ArrayList,是一个内部类ArrayList ,是只读的
hobbyList.add("唱歌");//出错!!!!!!
The ArrayList returned by the Arrays.asList() method is not an ArrayList in the collection system, but an internal class ArrayList, which is read-only
Method 3: Map<String,String[]> getParameterMap() Get all the request parameters, get a map set, generally combine the third-party jar, convert the map into a java object
Map<String, String[]> parameterMap = request.getParameterMap();
Traverse the Map collection
1.先得到key集合 然后遍历key, 得到value  不推荐
2.得到EntrySet   Entry(key/value键值对)  推荐
Map<String, String[]> parameterMap = request.getParameterMap();
Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
for (Map.Entry<String, String[]> entry : entries) {
    
    
    System.out.println(entry.getKey() +"-->"+Arrays.asList(entry.getValue()));
}

Browser cache issues:

Modify the page, when you visit, the page has not changed, it may be a browser cache problem

chrome: ctrl + F5 underlying refresh

Response

content

  1. set response header
  2. send status code
  3. Set the response body: get the response output stream, the output is important
  4. redirection is important

set response header

  • void setIntHeader(String name, int value) Set the response header, the value of the response header is int type
  • void addIntHeader(String name, int value)
  • void addHeader(String name,String value) Set the response header, the value of the response header is String
  • void setHeader(String name,String value)
  • void setContentType(String) set the content-type response header

Important response headers:

content-type: “text/html;charset=UTF-8”:

Tell the browser, the content type of the server response, and the browser parses it according to the content type

charset: only valid for text files

value type

text/html: response html text

Image: Binary

  • image/gif: gif image format
  • image/jped: jpg image format
  • image/png: png image format

css:

text/css

js:

text/javascript

json:

application/json

setHearder()

Send status code to understand

  • response.setStatus(200): set the status code;
  • response.sendError(404, "The resource you are looking for does not exist"): When an error status code is sent, Tomcat will jump to a fixed error page, but it can display an error message.

200: success

304: Forward

404: Resource does not exist

405: Request method not supported

400: Failed request

500: internal server error, an exception occurred in the background

response body

output stream via response

Character response output stream: response.getWriter() output text, json data

Byte response output stream: response.getOutputStream() universal stream, text, file

Notice:

These two streams cannot coexist, and if they are used at the same time, an exception java.lang.IllegalStateException will be thrown

Case: server response image

response.setContentType("image/gif");
//使用字节响应输出流  网络IO
ServletOutputStream outputStream = response.getOutputStream();

//服务器响应一张图片  图片位于服务器硬盘

//1.使用本地输入IO流   读取服务器硬盘图片   到服务器内存
FileInputStream fis = new FileInputStream("D:\\图片\\nbagif.gif");
int content = -1;  //变量, 内存
while((content = fis.read()) != -1){
    
    
    //2.再使用网络输出IO流, 把服务器内存的资源写到客户端
    outputStream.write(content);
}

redirect

response.sendRedirect (redirected path)

characteristics;

  1. Two requests, the request field is invalid
  2. The client address bar changes
  3. The jump happens on the client side
  4. Jump resources: It can be internal resources of the server (resources that cannot jump to the WEB-INF directory), or external resources of the server

Redirection and forwarding resource path issues:

访问的项目名: /web
重定向到demo1.html
重定向的url写绝对路径:   直接写/ 表示忽略项目名
如果没有设置访问的项目名: 必须加 /项目名/资源路径
项目名 通过request.getContextPath()获取到
重定向的url: 统一的写: req.getContextPath()+"/资源路径"
resp.sendRedirect(req.getContextPath()+"/demo1.html");

 //转发
 // 转发的url, 有项目名,没有项目名, 都不需要加/项目名
 // 统一写法:  /资源路径req.getRequestDispatcher("/demo1.html").forward(req,resp);
redirected path
//req.getContextPath()+"/资源路径"
resp.sendRedirect(req.getContextPath()+"/demo1.html");

Garbled processing

The reason for the garbled characters: the encoding of the project is unified as UTF-8, and the encoding (post) of tomcat is ISO-8859-1

get request, via url

Processing method:

  1. Tomcat starts from 8, handles Get request encoding, default encoding: UTF-8
  2. Tomcat7 or before, did not handle Get request encoding encoding or ISO-8859-1

    1. Specify get request encoding in server.xml: UTF-8 (can be set before tomcat 7)
    <Connector URIEncoding= "UTF-8"  connectionTimeout= "20000"  port= "8888"  protocol= "HTTP/1.1"  redirectPort= "8443" />
    
    1. Valid for all web servers, handled by code
    //1.打散
    byte[] bytes = name.getBytes("UTF-8");
    //2.组装成字符串
    name = new String(bytes,"UTF-8");
    
When getting a request: byte[] bytes = name.getBytes("UTF-8"); The value depends on the version of tomcat. Tomcat7 was ISO-8859-1 before

post request, through the request body

request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");

Garbled code processing summary:

  1. Get request code: above tomcat8 has been processed, no need to manage
  2. post request encoding, call request.setCharacterEncoding("UTF-8");
  3. Response encoding setting: Response encoding (does not distinguish between get or post requests) response.setContentType("text/html;charset=UTF-8");
  4. 2,3 The code is the first two lines of code as the servlet before getting the parameters and responding to the data

An IP address of a certain resource can only be accessed once an hour

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        response.setContentType("text/html;charset=utf-8");
        ServletContext application  = this.getServletContext();
        Integer count = (Integer)application.getAttribute("count");
        HashMap<String,Long> map = (HashMap) application.getAttribute("map");
        if(map == null){
    
    
//            application.setAttribute("map",new HashMap<String,Long>()); 错误
            map = new HashMap<String,Long>();
        }
        if(count == null){
    
    
            count = 0;
        }
        String ip = request.getRemoteAddr();
        long visitTime = System.currentTimeMillis();
        if(!map.containsKey(ip)){
    
    
            map.put(ip,visitTime);
            count++;
        }else {
    
    
            if(System.currentTimeMillis()-map.get(ip)<3600000){
    
    
                response.getWriter().println("刚刚来过啦,过会再来吧~");
            }else {
    
    
                map.put(ip,System.currentTimeMillis());
                count++;
            }
        }
        response.getWriter().print("<h1>本页面一共被访问" + count + "次!</h1>");
        application.setAttribute("count", count);
        application.setAttribute("map",map);
}

JSP

JSP

Essentially a Servlet Java class

jsp is a dynamic resource containing Java script and html, which cannot be directly accessed by browsers

When the browser requests jsp, the web server needs to execute the jsp code, the result after execution is converted into static html, and the response is sent to the browser

JSP script

  • <%...%>: The code that can be written in the java method can be written in it
  • <%=…%>: expression, the result of the expression is displayed on the page
  • <%!..%>: Java defines class members; defines attributes, defines methods
jsp is essentially equivalent to a Servlet Java class

JSP directive

Nine built-in objects of jsp -- interview questions

Built-in objects: no need to create, can be used directly

Four domain objects: pageContext, request, session, application

Response object: response

Response stream object: out

Configuration object: config

Indicates this: page

exception object: exception

Session Tracking Technology Cookie Session

http is stateless, the server cannot distinguish whether the browser's request comes from the same browser

Cookie characteristics:

Created on the server, saved in the client browser, and after each request, the cookie stored in the client's browser on the server will be brought back to the server through the request header

Usage scenario: user name, password saved to cookie, (remember password)

Provide method: getName() getValue()

Case: remember password

When the user logs in to the page, check to remember the password, log in, and after the login is successful, log in again next time, and display the user name and password of the last login

Ideas:

LoginServlet:

  1. Determine whether the login is successful
  2. After successful login, determine whether to check "Remember me"
  3. If checked, save the username and password to the cookie,
  4. If not checked: Determine whether there is a cookie for the user name and password, and if so, delete it

login.jsp:

The form value of username and password gets the cookie value and displays it dynamically

<%= %> Output content to the page: Disadvantage: If the content is null, it will also be displayed on the page

Replace <%= %>, use EL expressions: ${域中的属性名}get data from the whole domain

${域中的属性名}Global search:

​ First search from the page domain, if found, return directly

​ If not found, search from request, if found, return directly

​ If not found, search from the session, if found, return directly

If not found, search from application, if found, return directly

If not found: return null directly

If the result of the el expression is null, it will not be displayed on the page

EL expressions support object navigation language:${对象.属性名..}

**Premise: **User objects are stored in the domain

java operation cookie:

On the server side: Create cookie: Construction method Cookie(String name,String value)

The method of saving to the client: the method of the response object: addCookie(Cookie)

If there is no addCookie(), the cookie will not be saved to the client

The server gets the cookie:

The cookie is passed to the server via the request header:

Cookie[] getCookies() of the request object

Cookie details

  1. Cookie max-age

    max-age: setMaxAge(int) of cookie maximum survival time of cookie

    ​ Default value: -1 Survive in the session, open the browser to close the browser, called a session

    > 0Cookie survival value (seconds) time, when the time is up, the browser will delete the cookie

    0: delete the cookie immediately

  2. cookie path

    Set the path of the cookie, restricting those resources to allow access

    Cookies under the parent directory of the resource can be accessed

    The cookie of the upper-level directory of the resource can be accessed

    Cookies under the / directory can be accessed.

    The path of the cookie is set to /, indicating that the cookie can be accessed by all resources of this project

  3. Modify the value of the cookie

    Call Cookie's setValue()

    Stealth modification:

    Cookie c2 = new Cookie(“name”,“wangwu”)

    If the client browser has a cookie with the key and the path is the same, modify the value of the cookie

    If the cookie of the key does not exist in the client browser, add

    If the cookie of the key exists in the client browser, but the path is different, add

Cookie storage Chinese:

It can be stored after tomcat7, no need to consider

For tomcat7 and before, cookies cannot store Chinese, and Chinese needs to be url-encoded

UTF-8: Chinese (accounting for 3 bytes): %two-digit hexadecimal%two-digit hexadecimal%two-digit hexadecimal

String str ="中国";  
//URL编码
String str1 = URLEncoder.encode(str, "UTF-8");
System.out.println(str1);//%E4%B8%AD%E5%9B%BD

//URL解码
String str2 = URLDecoder.decode(str1, "UTF-8");
System.out.println(str2);//中国
For Tomcat8 and later, cookies support Chinese, if there are special symbols, they cannot be stored, and url encoding is used

HttpSession

main effect:

Realize the sharing of data between multiple requests in one session

The scope of a session:

From opening the browser to access the server, to closing the browser

use session

1. Get the HttpSession object request.getSession(); request.getSession(boolean)

getSession(): If the current request has a session, return the object of the current request session, if not, create a new session object

getSession(boolean create):

true: Same as getSession(),

false: If the current request has a session, return the object of the current request session, if not, return null

2. Delete Session void invalidate()

Make the session invalid, the session is invalid, and the data stored in the session is invalid

3. Set the session maximum survival time void setMaxInactiveInterval(int interval) unit: second

Session default storage time:

30 minutes, more than 30 minutes from the last request to the next request, the session is deleted by the server ( Tomcat maintains a session pool )

Session characteristics

Created on server, saved on server

Session implementation principle interview questions

The server will create a Session object for the user, and save the sessionId in the form of a cookie on the client browser. Every time the user makes a request, the cookie (JSESSIONID) will be automatically brought back to the server. The server will match the corresponding session object in the session pool according to the sessionId. The server knows which session the current request is from (from which browser),

If the client’s cookie is deleted, the request will not include JSessionId, and the server will not know which Session belongs to this user (browser). The previous session created for this user cannot be accessed by anyone. It is garbage. The server deletes this session after 30 minutes by default.

If the server deletes the session, even if the client has a JSessionid cookie, the session cannot be obtained, the server will recreate the session for the browser, and save the new sessionId in the form of a cookie for the client

Case: logout

1. Click the logout button to send a request to LogoutServlet

2. Let the session fail

3. Redirect to login.jsp

Case: Realization of Verification Code

The servet that generates the verification code pre-stores the generated verification code in the session

request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);

1. The user fills in the verification code, clicks to log in, and sends a login request to LoginServlet

2. Determine whether the verification code is correct

3. Incorrect: Respond directly to "Verification code error" and forward to login.jsp

4. Correct: Redirect to index.jsp

Case: Click to refresh the verification code

<a href="javascript:;" onclick="refreshCode()" >
    <img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/>
</a>


另一种写法
<a href="javascript:refreshCode();">
    <img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/>
</a>
点击a标签后调用函数,点击a标签触发href里的地址,执行js
//切换验证码
function refreshCode(){
    
    
    //1.获取验证码图片对象
    var vcode = document.getElementById("vcode");

    //2.设置其src属性,加时间戳
    vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime();
}

Why time stamp

To prevent browser caching, if the address bar does not change, the server will think that no new request has been initiated, and the last resource will be displayed through the cache, and the verification code will not be updated

MVC

MVC is a **software architecture pattern,** this pattern divides the project into three major modules:

M : model model layer: pojo, dao

C : controller control layer: Servlet

V : view view layer: jsp,html

The view layer and model layer in java cannot be directly accessed

java web development

The classic three-tier model, the hierarchical concept of java classes

The role of receiving user requests: web layer

The role of processing business logic: service layer

The role of communicating with the database: dao layer

Layering Purpose: Technology Isolation

For example, the technology used in the dao layer can only exist in the dao layer and cannot be extended to other

Benefits: When the project expands, it is necessary to replace the technology of a certain layer, only this layer needs to be replaced, and other layers do not need to be changed

Precautions:
  1. Cross-layer call, call sequence: web layer call -> service layer call -> dao layer
  2. Only the upper layer can call the lower layer , the web can call the service, and the service can call the dao, and the lower layer cannot call the upper layer
  3. Layer and layer use interface isolation, service: provide interface, let web use, dao layer provide interface, let service use

JSTL tags (understand)

**Function: **Replace Java script, usually used together with EL expressions

Execute on the server side, and respond to the client browser with the result after jstl execution, and the JSTL tag is executed before the Html tag

Steps for usage:

1. Import dependencies that support JSTL

2. In the jsp page using the jstl tag, use the taglib command to import the tag library

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

prefix: prefix, arbitrary name, standard name: c (core tag library): For example: <c:div>use prefix to distinguish html tags

All tag names of core:<c:标签名>

uri: url corresponding to jstl tag, fixed writing method, import jstl tag library, choose jsp/jstl tag library

3. Use JSTL tags

Common JSTL tags

(1) <c:if test="condition"></c:if>>

(no else tags, no else if tags)

(2) choose label
<c:choose>
      <c:when test="${score >= 90}">
          <p>优秀</p>
      </c:when>
      <c:when test="${score >= 80}">
          <p>良好</p>
      </c:when>
      <c:when test="${score >= 60}">
          <p>及格</p>
      </c:when>
      <c:otherwise>
          <p>不及格</p>
      </c:otherwise>
  </c:choose>
(3) foreach tag: for loop

for i

<c:forEach var="i" begin="0" end="9" step="2">
      <h1>${i}</h1>
 </c:forEach>

Enhanced for loop:

<c:forEach var="admin" items="${admins}">
    <tr>
        <th>${admin.id}</th>
        <th>${admin.username}</th>
        <th>${admin.password}</th>
    </tr>
</c:forEach>
The forEach loop has a varStatus="variable" to get the loop status object of the for loop

The forEach tag also has an attribute: varStatus, which is used to specify the variable name that receives the "loop status" , for example: <forEach varStatus="vs" .../>, then you can use the variable vs to get the status of the loop.

The value of vs can be:

  • count: int type, the number of elements (serial number) that have been traversed currently; the number of cycles, starting from 1
  • index: int type, the subscript of the current element; starting from 0
  • first: boolean type, whether it is the first element;
  • last: boolean type, whether it is the last element;

Guess you like

Origin blog.csdn.net/m0_48895748/article/details/127728805