Servlet -- ServletContext, filter, JSP

Servlet (III) -- ServletContext, filter, JSP

1, ServletContext

1. ServletContext overview

2. Get ServletContext object

3. ServletContext function

a. Get the real path of the project

b. Get project context path

c. Global container

4. ServletContext features

5. Above code

6. Small case - ServletContext counts the number of visits to the current project

7. Scope summary

2, Filter

1. Filter concept

2. Filter function

If a filter is set, all requests sent by the browser will be intercepted by the filter and some rules will be processed in it; Many filters can be set. Finally, they arrive at the Servlet, process the request, and then return to the client.

3. Write a Filter -- implement the Filter interface


To write a Filter, you need to implement the Filter interface first, and then rewrite three methods:


4. Small case - write a filter to deal with request garbled code

In the previous case of writing a Servlet, the coding format is often handled. You can write a filter, and call the filter every time you want to handle the coding format.

/**
 * Define a filter that can handle request body garbled code
 */
public class EncodingFilter implements Filter {
    //Coding format
    private String encoding = null;
    /**
     * This is the initialization method of the filter
     *
     * The initialization method is executed only once
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Read the filter configuration and the encoding format here
        //Read the configuration parameters in init param
        encoding = filterConfig.getInitParameter("encoding");
        if (encoding == null) {
            //Explain that the user is on the web Initialization parameters are not configured in XML
            encoding = "UTF-8";
        }
    }
    /**
     * The core filtering method will execute all intercepted requests
     * @param servletRequest  This parameter is the current request
     * @param servletResponse Current response object
     * @param filterChain Filter chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Set the encoding format for all filter requests
        servletRequest.setCharacterEncoding(encoding);  //  You can also write dead utf-8 here, so you don't have to write those above.

        //Let the request continue down. If you don't execute the following line of code, the request will be stuck here. (meaning release)
        //Only when you continue to go down can you reach the Servlet. If you don't continue to go down, you won't reach the Servlet
        filterChain.doFilter(servletRequest, servletResponse);
    }

5. Filter configuration

Like servlets, there are xml configuration and annotation configuration

a. xml file configuration

b. Annotation configuration


6. Filter path

7. Small case - login verification by filter

Two files, one for login and one for filtering:

Sign in:

@WebServlet(urlPatterns = "/doLogin")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Processing login requests in doPost
        //Extract the login parameters passed by the user
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if ("zhangsan".equals(username) && "123".equals(password)) {
            //Login succeeded
            //Save the user name with successful login to the session
            req.getSession().setAttribute("loginUser", username);
            //Jump to index HTML page
            resp.sendRedirect("/pf/index.html");
        } else {
            //Login failed
            //Return to the login page
            resp.sendRedirect("/pf/login.html");
        }
    }
}

filter:

/**
 * Define a permission filter
 */
@WebFilter(urlPatterns = "/*")
public class PermissFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * The logic of this method:
     * <p>
     * Judge whether the current request has been logged in. If it has been logged in, let the request continue to execute; If the request is not logged in, go back to the login page
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Force the current request to HttpServletRequest, which is a subclass of ServletRequest
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //Get current session object
        HttpSession session = req.getSession();
        //Gets the url address of the current request
        String requestURI = req.getRequestURI();
        if (requestURI.contains("/login.html") || requestURI.contains("/doLogin")) {
            //These addresses don't need to be intercepted
            //So ask to go straight down
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //These addresses are the addresses that need to be intercepted and judged
            //Get the currently logged in user name
            Object loginUser = session.getAttribute("loginUser");
            if (loginUser == null) {
                //Indicates that the user is not logged in
                resp.sendRedirect("/pf/login.html");
            } else {
                //It indicates that the user has logged in and requests to continue down
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}

8. The difference between getRequestURI and getRequestURL

9. Filter chain and priority

a. Filter chain


b. Filter priority

3, JSP

1. Introduction

java development method:

Existing problems:

2. Concept and function of JSP (Java Server Pages)

Simplified Servlet design, nesting Java code in HTML tags to efficiently develop dynamic Web pages of Web applications.

Function: replace the servlet that displays the page part (replace xxjsp. Java with *. jsp file).

3. Using jsp

Use the <% =% > tag to write Java code and print the current system time in the page.

jsp is used in the same way as Servlet:

4. View the code decompiled by jsp


In essence, it is to write Java and HTML code together.

5. Difference and implementation principle between jsp and Servlet

difference:

Implementation principle:

6. jsp template development script (tag language)

Since you can write Java and HTML code together, there must be a way to distinguish them:

a. <%...% > - normal script

Ordinary scripts can use all Java syntax, except custom methods (because after the jsp page is compiled, the contents will appear in _jspService; methods cannot be defined in methods). (Note: scripts and scripts cannot be nested, and scripts and HTML tags cannot be nested.)

b,<%! … %>—— Declaration script


be careful:
1. The variables declared by the declaration script are global variables.
2, the contents of the declaration script must be invoked in the normal script%% >.
3. If the function in the declaration script has a return value, you can use the output script to call <% =% >.

c. <% =...% > -- output script


Note: the output script can output functions with return values, and semicolons cannot be added in the output script;

7. Small case - 99 multiplication table

Write a page of 99 multiplication table using jsp:

<table border="1">
    <%
    //You can write Java code here
        for (int i = 1; i <= 9; i++) {
            //The following tag means to end the writing of Java code and enter the writing of HTML tag
            %>
        <tr>
            <%
                for (int j = 1; j <= i; j++) {
                    %>
                <td>
                    <%=i%>*<%=j%>=<%=i*j%>
                </td>
            <%
                }
            %>
        </tr>
    <%
        }
    %>
</table>

8. jsp annotation

JSP annotation has two main functions: Annotation for script code and HTML content annotation.

example:

Then view the web page source code:

Check the decompiled code again:

9. jsp instruction

a. page instruction

b. include instruction (static introduction, not recommended)


Variable conflict. For example, page A has A num variable. When page B is introduced, page B also has A num variable. This is variable conflict.

c. taglib instruction

10. Action label

a. Include (jsp: include -- Dynamic introduction: suggestion)


b. useBean (not normally used)


c,setProperty

d,getProperty

e,forward



f,param

Keywords: Java JSP servlet filter

Added by mella on Thu, 16 Dec 2021 22:13:17 +0200