JavaWeb study notes arrangement (below)

Filter

**Function:**Intercept request

When a user requests a Servlet, the Filter deployed on the request will be executed first. If the Filter is "allowed", then the Servlet requested by the user will be inherited; if the Filter is not "released", the Servlet requested by the user will not be executed.

In fact, it can be understood that when a user requests a Servlet, Tomcat will execute the Filter registered on the request, and then whether to "release" is determined by the Filter. It can be understood that the Filter determines whether the Servlet can be called! When the Servlet code is executed, the code behind the Filter will also be executed.

use filter

  1. Write a class that implements the javax.servlet.Filter interface
  2. Configure the filter in the web.xml file or use annotations to configure the urls of which requests the filter intercepts

FilterChain filter chain

Among the parameters of the doFilter() method is a parameter of type FilterChain, which has only one method: doFilter(ServletRequest,ServletResponse).

Earlier we said that the release of the doFilter() method allows the request flow to access the target resource! But this is not strict. In fact, calling this method means that "I (current Filter)" has released it, but it does not mean that other people (other filters) have also released it.

That is to say, multiple filters may be deployed on a target resource, just like there are multiple robbers (filters) on your way to Beijing, and the first group of robbers let go, but it does not mean that the second gangster also let go, so calling the doFilter() method of the FilterChain class means executing the doFilter() method of the next filter, or executing the target resource !

If the current filter is the last filter, then calling the chain.doFilter() method means executing the target resource. If it is not the last filter, then chain.doFilter() means executing the doFilter() method of the next filter.

let go
filterChain.doFilter(servletRequest,servletResponse);

If the Filter does not display the above line of code, it means that the filter is not allowed

The order in which filters are executed:

Use the web.xml configuration file to configure the filter: the configuration file of the filter determines the filter execution order

Determined by the order of the filters <filter-mapper>, who <filter-mapper>comes first and who executes first

The configuration method of annotation @WebFilter is provided in web3.0:

Using annotations, the order in which filters are executed is determined by the name of the filters, and the ones in the front are executed first. When there are multiple filters, it is recommended to use web.xml configuration

Access control

Some resources must be logged in to access. For example: additions, deletions, and modifications must be logged in to access

Access interception when the case is not logged in

The intercepted url executes the doFilter method of the filter
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    
    
//        1.判断是否已经登录
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpSession session = request.getSession();
        if(session.getAttribute("admin")!=null){
    
    
//            已登录,放行
            chain.doFilter(req, resp);
            return;//不执行后续方法内代码
        }
//        2.未登录,拦截,跳转到登录界面
        String requestURI = request.getRequestURI();//用户想要访问的资源
        session.setAttribute("requestPage",requestURI);
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }
important point:
  1. The object req of ServletRequest has no request.getSession() method, so the object must be converted into its subclass HttpServletRequest

2. The basis for judging whether to release is whether the user has logged in, so if the login is successful when the LoginServlet processes it, the logged-in user should be saved in the domain as a basis

3. If it is released, be careful not to execute the code after the method (use return or else statement)

4. If the user is not logged in, intercept and jump to the login interface. It should be noted here that if the user logs in successfully, it should jump to the resource that the user wants to access instead of the home page (do not write the interface that jumps after successful login)

  1. When the user wants to access the resource and is blocked, save the resource the user wants to access to the domain (request.getRequestURI()), and jump to the saved resource after successful login
LoginServlet handles user login requests
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
//        1.设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html,charset=utf-8");

        String error ="";
        HttpSession session = request.getSession();
    
//        2.获取数据
        String username = request.getParameter("username");
        String psaaword = request.getParameter("password");
    
//        3.调用service
        AdminService adminService = BeanFactory.creatBean(AdminService.class);
        Admin admin = adminService.login(username, psaaword);

        //判断验证码是否正确
        String verifycode = request.getParameter("verifycode");
        String checkcode = session.getAttribute("CHECKCODE_SERVER").toString();
        if(!checkcode.equalsIgnoreCase(verifycode)){
    
     //不相等
            error="验证码输入错误";
            request.setAttribute("error",error);
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;//验证码出错。不执行后续代码
        }

       //判断用户是否存在
        if (admin != null) {
    
    
//5.把数据保存域中, admin保存到session域
            session.setAttribute("admin",admin);

            //用户是否勾选记住密码
            String remenberPassword = request.getParameter("remenberPassword");
            if ("rem".equals(remenberPassword)) {
    
     //勾选
                //创建用户名cookie, 密码cookie (加密)
                Cookie nameCookie = new Cookie("username", username);
                Cookie passwordCookie = new Cookie("password", psaaword);
                //默认7天有效
                nameCookie.setMaxAge(7 * 24 * 60 * 60);
                passwordCookie.setMaxAge(7 * 24 * 60 * 60);
                //保存到客户端浏览器
                response.addCookie(nameCookie);
                response.addCookie(passwordCookie);
            } else {
    
    //没有勾选, 判断之前是否保存账户密码的Cookie有就删除
                Cookie[] cookies = request.getCookies();
                if (cookies != null && cookies.length > 0) {
    
    
                    for (Cookie cookie : cookies) {
    
    
                        if (cookie.getName().equals("username") || cookie.getName().equals("password")) {
    
    
                            //删除
                            cookie.setMaxAge(0);
                            response.addCookie(cookie);
                        }
                    }
                }

            }
            //  登录成功 重定向
            //从session获取到想访问的资源
            Object requestPage = session.getAttribute("requestPage");
            if(requestPage == null){
    
    
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }else{
    
    
                response.sendRedirect(request.getContextPath()+requestPage);
                //把session域中requestPage属性删除
                session.removeAttribute("requestPage");
            }
        }else if(admin==null){
    
    //登录失败
            //5.把数据保存域中
            error = "用户名或者密码错误";
            request.setAttribute("error",error);
            //6.页面跳转 转发: 把数据存在request域
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }
important point:

If the user successfully logs in from the blocked login page, remember to delete the requestURI in the session after the login is successful, otherwise the session will always exist in this session, which may cause the next login to jump to this page

Files under WEB-INF cannot be accessed directly, but can only be accessed through forwarding, so the intercepted resource folder can be placed in WEB-INF

Four interception methods

REQUEST、FORWARD、INCLUDE、ERROR。

You can <filter-mapping>add 0~n <dispatcher>sub- elements in , to illustrate the interception method of the current access.

File Upload

The file upload here is a small file upload

Large file upload needs to write TCP for large file upload

Implementation : The client uploads a local file (picture, video, audio, text file...) to the server and saves it in the server

File upload requirements for the front end

  1. Forms must be used, not hyperlinks;
  2. The method of the form must be POST, not GET;
  3. The enctype of the form must be multipart/form-data;
  4. Using form elements: `
<form action="${pageContext.request.contextPath }/FileUploadServlet" method="post" enctype="multipart/form-data">
    	用户名:<input type="text" name="username"/><br/>
    	文件1:<input type="file" name="file1"/><br/>
    	文件2:<input type="file" name="file2"/><br/>
    	<input type="submit" value="提交"/>
    </form>

File upload requirements on the backend

When the submitted form is a file upload form, there are also requirements for the Servlet.

First of all, we must be sure that the data of the file upload form is also encapsulated into the request object.

  1. When the enctype value of the form is "multipart/form-data", the request.getParamter() method is invalid
  2. You can get the data through the ServletInputStream of the request object, or you can use the third-party jar package, commons-fileupload.jar provided by apache

The request.getParameter(String) method obtains the character content of the specified form field, but the file upload form is no longer a character content, but a byte content, so it is invalid.

At this time, you can use the getInputStream() method of the request to obtain the ServletInputStream object, which is a subclass of InputStream. This ServletInputStream object corresponds to the body part of the entire form (from the first dividing line to the end), which shows the data in the parsing stream we need. Of course, parsing it is a very troublesome thing, and Apache has provided us with a tool for parsing it**: commons-fileupload. **

Use the Commons-fileupload step

  1. import dependencies
  2. Create a DiskFileItemFactory factory class, FileItem: form items corresponding to the form (input, select, teaxarea)
  3. Create a Request object parser ServletFileUpload
  4. Parse the Request object ServletFileUploadList<FileItem> parseRequest(request)
  5. Traverse step 4 to get List<FileItem>one FileItem, and process it according to the FileItem type (ordinary form item, non-ordinary form item (file form))

File upload details

The files uploaded by the client are saved on the hard disk of the server, and the front-end cannot access them by default.

How to enable the client to access the files uploaded to the server? ,

Tomcat provides a virtual path,

Map an access url to a certain path of the hard disk of the server. When the client accesses this url, it indirectly accesses resources under the path corresponding to the hard disk on the server.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-4HpZ9Cc3-1667978787131) (D:\Feisi Training 3\6.JavaWeb\Notes\5_Filter and File Upload\assets\image-20221025160917060.png)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-23V1hNgI-1667978787132) (D:\Feisi Training 3\6.JavaWeb\Notes\5_Filter and file upload\assets\image-20221025160938768.png)]

Select hard disk address

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-s6zX7K3k-1667978787132) (D:\Feisi Training 3\6.JavaWeb\Notes\5_Filter and file upload\assets\image-20221025161105316.png)]

set url

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-v9uWdn4x-1667978787134) (D:\Feisi Training 3\6.JavaWeb\Notes\5_Filter and file upload\assets\image-20221025161236835.png)]

fileupload overview

fileupload is an upload component provided by apache's commons component. Its main job is to help us parse request.getInputStream().

The JAR packages required by the fileupload component are:

commons-fileupload.jar, core package;

commons-io.jar, dependent package

fileupload simple application

The core classes of fileupload are: DiskFileItemFactory, ServletFileUpload, FileItem.

The steps to use the fileupload component are as follows:

  1. Create a factory class DiskFileItemFactory object: DiskFileItemFactory factory = new DiskFileItemFactory()
  2. Create a resolver object using a factory: ServletFileUpload fileUpload = new ServletFileUpload(factory)
  3. Use a parser to parse the request object: List list = fileUpload.parseRequest(request)

Grandly introduce the FileItem class , which is the final result we want. A FileItem object corresponds to a form item (form field). There are file fields and ordinary fields in a form, you can use the isFormField() method of the FileItem class to determine whether the form field is an ordinary field, if it is not an ordinary field, then it is a file field.

  • String getName(): Get the file name of the file field;
  • String getString(): Get the content of the field, if it is a file field, then get the content of the file, of course the uploaded file must be a text file;
  • String getFieldName(): Get the field name, for example: username is returned;
  • String getContentType(): Get the type of the uploaded file, for example: text/plain.
  • int getSize(): Get the size of the uploaded file;
  • boolean isFormField(): Determine whether the current form field is an ordinary text field, if it returns false, it means it is a file field;
  • InputStream getInputStream(): Get the input stream corresponding to the uploaded file;
  • void write(File): Save the uploaded file to the specified file.

Case upload file

Handle file uploads UploadServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //借助于 commons-fileupload
        //1.创建DiskFileItemFactory对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        //2.创建一个解析Request对象解析器 ServletFileUpload
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        try {
    
    
            //3.解析Request对象
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            //4.遍历fileItems
            for (FileItem fileItem : fileItems) {
    
    
                //5.判断是否为普通表单
                if (fileItem.isFormField()) {
    
    //true 普通表单
                    String fieldName = fileItem.getFieldName();//获取name值
                    String value = fileItem.getString("UTF-8");//获取表单的value
                    System.out.println(fieldName + ":" + value);
                } else {
    
    //文件表单
                    //上传的文件保存到服务器的硬盘上
                    String savePath = "D:/upload/";
                    //得到上传的文件名 getName() 
                    String uploadFilename = fileItem.getName();
                    // 创建一个文件名  文件名称 + 后缀名(上传文件的后缀名)
                    String saveFile = FileUploadUtil.randomFileNameWithUUID() + FileUploadUtil.getFileSuffix(uploadFilename);
                    //保存 FileItem的write(File file)
                    fileItem.write(new File(savePath, saveFile));
                }
            }
        }catch (FileUploadException e) {
    
    
            e.printStackTrace();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
important point:

1. The file name saved in the server should be unique, and cannot be saved to the server with the file name uploaded by the user

2. The unique processing method of the file name (tool class can be encapsulated)

Use timestamp to splice other (such as username, etc.)

Use java's built-in UUID to get a randomly generated 32-digit hexadecimal string

3. The method of saving the file FileItem.write(File file)

4. Don’t forget the suffix name of the spliced ​​file when saving to the server, String uploadFilename = fileItem.getName(); (the tool class encapsulation method intercepts the suffix name)

Tool class FileUploadUtil
public class FileUploadUtil {
    
    
    /**
     * 得到文件名的后缀
     * @param fileName
     * @return
     */
    public static String getFileSuffix(String fileName){
    
    
        if(fileName==null||fileName.isEmpty()){
    
    
            throw new RuntimeException("找不到文件,filename:"+fileName);
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 使用UUID生成文件名
     */
    public static String randomFileNameWithUUID(){
    
    
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    /**
     * 基于时间戳生成文件名
     */
    public static String randomFileNameWithTime(){
    
    
        return System.currentTimeMillis()+"";
    }

    /**
     * 基于时间戳 + UUID生成文件名
     * @return
     */
    public static String randomFilenameWithUUIDandTime(){
    
    
        return System.currentTimeMillis()+randomFileNameWithUUID();
    }
}

ajax

Asynchronous JavaScript and XML

Two major features of AJax:

  • asynchronous communication
  • partial refresh

JSON

JSON syntax format:
  1. Data is stored in key/value pairs, key:value
  2. Use commas to separate data and data: k1:v1,k2:v2
  3. Use {}to represent an object{"id":1,"name":"张三"}
  4. Use []to represent an array{"id":1,"name":"张三","loves":["read","music"]}

stus:[{"id":1,"name":"张三"},{"id":2,"name":"李四",sex:null}]

Notice:

  1. The key must be enclosed in double quotes
  2. If value is a string, be sure to use double quotes
JSON value:
  • number (integer or float)
  • string (in double quotes)
  • logical value (true or false)
  • array (in square brackets [])
  • object (in curly braces {})
  • null

JSON class in ES5 syntax

JSON.parse(json string): convert JSON string to js object

JSON.stringify(js object): Convert js object to JSON format string

In JQuery:

$.parseJSON(json string): convert json string to js object, this method is deleted in jquery3.0 and later versions

Conversion of java objects to json

With the help of third-party jars: fastJson, jackson, json-lib…

Courseware: fastJson: Alibaba's

Core class: JSON

Core method:

Convert json string to java object: parseObject()

Convert the json string in the form of an object array to a Java List collection: parseArray()

Convert java object to json string: toJSONString()

@JSONField annotation
The Student class sets the non-serializable and JSON date format (using the fastjson jar package)
@JSONField(serialize=false)
private Integer age;
//format: 字符串转换格式
@JSONField(format="yyyy-MM-dd")
private Date birthday;  //在实体类中, Date类一定是java.util.Date

jackson, json-lib…

Courseware: fastJson: Alibaba's

Core class: JSON

Core method:

Convert json string to java object: parseObject()

Convert the json string in the form of an object array to a Java List collection: parseArray()

Convert java object to json string: toJSONString()

@JSONField annotation
The Student class sets the non-serializable and JSON date format (using the fastjson jar package)
@JSONField(serialize=false)
private Integer age;
//format: 字符串转换格式
@JSONField(format="yyyy-MM-dd")
private Date birthday;  //在实体类中, Date类一定是java.util.Date

Guess you like

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