JAVA study notes 19-conversation technology, MVC, three-tier architecture

Conversational technology

There are multiple requests and responses in one session. A session refers to the first time that the browser sends a request to the server resource, the session is established, until one party disconnects
Function: share data within the scope of a session
Client session technology: Cookie
Server session technology: Session

1. Cookie

1.1 Basic concepts

Client session technology, save data to the client

1.2 Quick start

Use steps:
1. Create Cookie object, bind data
new Cookie(String name, String value)
2. Send Cookie object
response.addCookie(Cookie cookie)
3. Get Cookie, get data
Cookie[] request.getCookies()

@WebServlet("/cookieDemo1")
public class CookieDemo1 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //创建Cookie对象
        Cookie c=new Cookie("msg","hello");
        //发送Cookie
        response.addCookie(c);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doPost(request,response);
    }
}
@WebServlet("/cookieDemo2")
public class CookieDemo2 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取Cookie
        Cookie[] cs=request.getCookies();
        if (cs!=null){
    
    
            for (Cookie c : cs) {
    
    
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name+":"+value);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doPost(request,response);
    }
}

1.3 Principle analysis

Implementation based on response header set-cookie and request header cookie

1.4 Features and functions

Features
1.cookie data stored in the client browser
2. The browser is limited to a single size of a cookie, and the cookie in the total number of the same domain is also limited
effect
1.cookie generally less sensitive for storing small amounts of data
2 .Complete the server's identification of the client without logging in

1.5 Access case

@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        response.setContentType("text/html;charset=utf-8");
        //获取所有Cookie
        boolean flag = false;
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
    
    
            for (Cookie cookie : cookies) {
    
    
                //获取cookie名称
                String name = cookie.getName();
                if ("lastTime".equals(name)){
    
    
                    flag = true;
                    //有该cookie,不是第一次访问
                    //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);
                    str_date = URLEncoder.encode(str_date, "utf-8");
                    cookie.setValue(str_date);
                    response.addCookie(cookie);
                    //响应数据
                    String value = cookie.getValue();
                    value = URLDecoder.decode(value,"utf-8");
                    response.getWriter().write("欢迎回来,您上次访问时间为" + value);
                    break;
                }
            }
        }
        if (cookies == null || cookies.length == 0 || flag == false){
    
    

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            str_date = URLEncoder.encode(str_date, "utf-8");
            Cookie cookie = new Cookie("lastTime", str_date);
            response.addCookie(cookie);
            response.getWriter().write("欢迎您第一次访问!");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doPost(request, response);
    }
}

2. Session

1.1 Basic concepts

Server-side session technology, sharing data between multiple requests in a session, and saving the data in server-side objects

1.2 Quick start

HttpSession对象:
Object getAttribute(String name)
void setAttritube(String name,Object value)
void removeAttritube(String name)

@WebServlet("/sessionDemo1")
public class SessionDemo1 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取session
        HttpSession session = request.getSession();
        //存储数据
        session.setAttribute("msg","hello session");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doPost(request,response);
    }
}
@WebServlet("/sessionDemo2")
public class SessionDemo2 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取session
        HttpSession session = request.getSession();
        //获取数据
        Object msg = session.getAttribute("msg");
        System.out.println(msg);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doPost(request,response);
    }
}

1.3 Principle analysis

Session depends on Cookie. The first time you get the Session, without Cookie, a new Session will be created in memory.

1.4 Features and functions

Features
1. The session is used to store the data of multiple requests for a session, and it is stored on the server side.
2. The session can store any type and size of data
. The difference between session and cookie 1. Session data is
stored on the server side, and cookie data is stored on the server side. Client
2. Session has no data size limit, cookie has data size limit
3. Session stored data is more secure

3. JSP

3.1 Basic concepts

Java Server Pages: Java server-side pages

3.2 JSP script

The way JSP is used to define Java code
<% code%>: The defined Java code is in the service method. What can be defined in the service method can be defined in the script.
<%! Code%>: The defined Java code, in the member position of the Java class after JSP conversion.
<%=Code%>: The defined Java code will be output to the page. What can be defined in the output statement, what can be defined in the script

3.3 Instructions

Function: Used to configure JSP pages and import resource files
Format: <%@ instruction name attribute name=attribute value%>

3.3.1 page command

Configure the
contentType of the JSP page : equivalent to response.setContentType()
1. Set the MIME type and character set of the response body
2. Set the current JSP page encoding
import : import package

3.3.2 include directive

Import the resource file of the page
<%@include file=“top.jsp”%>

3.3.3 taglib instruction

Import resources

3.4 Built-in objects

Objects that do not need to be acquired and created in JSP objects, and can be used directly

pageContext: PageContext type, current page sharing data
request: HttpServletRequest type, one request to access multiple resources
session: HttpSession type, sharing data between multiple requests in one session
application: ServletContext type, sharing data between multiple users
response: HttpServletResponse type, Response object
page: Object type, object of the current page
out: Jspwriter type, output object, data to the page
config: ServletConfig type, Servlet configuration object
exception: Throwable type, exception object

4. EL expression

4.1 Basic concepts

Expression Language
can be used to simplify the writing of Java code in JSP pages.
Basic syntax: ${}
ignore EL expressions: set isIgnored="true" in the page command in JSP to ignore all EL expressions

4.2 Basic usage

4.2.1 Operation

Arithmetic operator: +-* /%
Comparison operator:> <>= <= == !=
Logical operator: && ||!
Empty operator: empty is used to determine whether a string, collection, or array object is null and the length is 0

4.2.2 Get value

Syntax: ${domain name city.key name} get the value of the specified key from the specified domain domain
name city:
pageScope —>pageContext
requestScope —>request
sessionScope —>session
applicationScope —>application

Get object value:

    <%
        Person p=new Person("Kobe",24);
        request.setAttribute("p",p);
    %>
    ${
    
    p.name}
    ${
    
    p.num}

Get list collection
${domain name.key name[index]}

Get map collection
${domain name.key name.key name}

    <%
        Person p=new Person("Kobe",24);
        request.setAttribute("p",p);
        List list=new ArrayList();
        list.add(24);
        list.add(23);
        request.setAttribute("list",list);
        Map map=new HashMap();
        map.put("name","Kobe");
        map.put("num",24);
        request.setAttribute("map",map);
    %>
    ${
    
    p.name}<br>
    ${
    
    p.num}<br>
    ${
    
    list[0]}<br>
    ${
    
    list[1]}<br>
    ${
    
    map.name}<br>
    ${
    
    map["num"]}<br>

MVC

1. JSP evolution history

1. In the early days, there was only servlet and only response to output tag data, which was very troublesome.
2. JSP simplifies the development of servlet. If JSP is used excessively, a large amount of Java code and HTML are written in JSP, which makes it difficult to divide and cooperate with maintenance and cooperation
3. Java Web development, drawing on the MVC development model, makes the design of the program more reasonable

2.MVC

2.1 Model

JavaBean, complete specific business operations

2.2 View

JSP, display data

2.3 Controller

Servlet, get user input, call the model, and hand the data to the view for display

3. Advantages and disadvantages

3.1 Advantages

Low coupling, easy to maintain, can facilitate division of labor and collaboration
, high reusability

3.2 Disadvantages

The project structure is complex and requires high developers

Three-tier architecture

1. Interface layer (presentation layer)

The interface that the user can see. Users can interact with the server through components on the interface

2. Business logic layer

Processing business logic

3. Data access layer

Operating data storage file

Guess you like

Origin blog.csdn.net/qq_44708714/article/details/107523330