A small web example of idea connecting to database

Posted by brainstem on Sat, 15 Jan 2022 22:51:44 +0100

preface

Before the implementation of the addition, deletion, modification, query and login functions, and then this time optimize the java code in jsp and realize the upload function!
To optimize the previous source code, optimize the code on this basis

1, Import jar package

This is a jar package to write and upload image code

2, Rewrite upload picture code

1. Modify the jsp code for adding pictures


Find bookadd to make room for uploading code

2. Modify the code of bookadd in the servlet (add the file upload code)

The code is as follows:

    //File upload
        //1. Create a file upload object
        SmartUpload smartUpload=new SmartUpload();
        //2. Initialization
        smartUpload.initialize(super.getServletConfig(),req,resp);
        //3. Limit the file type, size, etc. What I write here is the common end of the picture
        smartUpload.setAllowedFilesList("jpg,JPG,jpeg,JPEG,png,PNG,gif,GIF");
        //Here is the definition of the picture name. The database stores the picture name
        String images="";
        try {
            //4. Upload files
            smartUpload.upload();
            System.out.println("File upload succeeded!");
            //5. Get file object
            File file = smartUpload.getFiles().getFile(0);
            if(file.isMissing()){

            }else{
                //Get the path where the upload folder is located
                String path = req.getServletContext().getRealPath("upload");
                String name=path+"/"+file.getFileName();
                System.out.println("Path is"+name);
                //6. Save the file to the upload directory
                file.saveAs(name);
                images=file.getFileName();//Give the file name to images and store it in the database

            }
        
        } catch (SmartUploadException e) {
            System.out.println("File upload failed!");
            e.printStackTrace();
        }


	be careful:Here is the name of the folder you want to save
  	//Get the path where the upload folder is located
	req.getServletContext().getRealPath("upload");

3. Modify the downlink code of bookadd in the servlet

Original appearance, req

Modified code

  		req.setCharacterEncoding("utf-8");
        Request request=smartUpload.getRequest();//Upload and download the request object of the component
        String bookname=request.getParameter("bookname");
        String author=request.getParameter("author");

        String press=request.getParameter("press");
        //Convert the price to int type
        String pricestr=request.getParameter("price");
        int price=Integer.parseInt(pricestr);
        String pubtime=request.getParameter("pubtime");

        //What is called here is the full parameter function defined by books..
        Books books = new Books(0,bookname,author,images,press,price,pubtime);

3, Display picture

(4) . modify bug s


There was a bug when uploading. After looking for it for a long time, I found that I forgot to add a sentence to the form

5, Testing


6, Upload code of modification page

The modification in update is the same as that in add
Pay attention to this

Add a hidden field to hide the image name. Uploading a new name will overwrite the database, and then take out the image corresponding to the database name in the folder. (the picture will not be displayed when it was modified before. If it is not found, it is not hidden in the part.).

The code here is a little different from adding
(if the request is not used, a 500 null error will appear.)

package com.zy.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.zy.Dao.BooksDao;
import com.zy.bean.Books;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * Class name: bookupdate
 * Reading breaks thousands of volumes, and writing is like God
 * The code goes backwards and the algorithm is in mind
 * Author: Rob love Li
 * Date: 20:57, July 8, 2021
 * Version: V1.0 0
 */
@WebServlet("/booksupdate")
public class booksupdate extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String images="";

        //File upload
        SmartUpload smartUpload=new SmartUpload();
        //Initialize the initialize method
        smartUpload.initialize(super.getServletConfig(),req,resp);//getServletConfig get configuration

        //Limit file type, size, etc!! setAllowedFilesList
        smartUpload.setAllowedFilesList("jpg,JPG,png,PNG,ICON,icon,jpeg,JEPG,gif,GIF");


        //Upload pictures
        try {
            smartUpload.upload();

            System.out.println("File upload succeeded!!");
            //Get file object
            File file = smartUpload.getFiles().getFile(0);
            if (file.isMissing()){
                //Modify: give the original image name to images
                images=smartUpload.getRequest().getParameter("images");
            }else {
                //Get the path where the upload folder is located!
                String upload = req.getServletContext().getRealPath("upload");//
                String name= upload+"/"+file.getFileName();
                System.out.println("What is the path!+"+upload);
                //Save file as upload directory
                file.saveAs(name);

                images=file.getFileName();//Give the file name to images and store it in the database
            }
        } catch (SmartUploadException e) {
            System.out.println("File upload failed!!");
            e.printStackTrace();
        }

        req.setCharacterEncoding("utf-8");
        Request request=smartUpload.getRequest();//Upload and download the request object of the component
        String bidStr=request.getParameter("bid");
        int bid=Integer.parseInt(bidStr);
        String bookname=request.getParameter("bookname");
        String author=request.getParameter("author");

        String press=request.getParameter("press");
        //Convert the price to int type
        String pricestr=request.getParameter("price");
        int price=Integer.parseInt(pricestr);
        String pubtime=request.getParameter("pubtime");

        //Here is the modified data
        Books books = new Books(bid,bookname,author,images,press,price,pubtime);

        BooksDao booksDao = new BooksDao();
        try {
            //Call the modify method to modify the data
            booksDao.update(books);
            resp.sendRedirect("BooksAll");
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
}

test

After modification

7, Optimizing jsp java code

1. Import jar package

1. Write c tag header file


Before optimization:

After optimization:

<center>
    <h2><a href="booksadd.jsp">Add books</a></h2>
    <%--Title No-Book name-author-picture-press-Price-Release time-operation--%>
    <table border="1" width="80%">
        <tr>
            <th width="10%">Title No</th>
            <th width="10%">Book name</th>
            <th width="10%">author</th>
            <th width="20%" >picture</th>
            <th width="10%">press</th>
            <th width="10%">Price</th>
            <th width="20%">Release time</th>
            <th width="10%">operation</th>
        </tr>
        <c:forEach items="${requestScope.booksList}" var="u">
            <tr>
                <td>${u.bid}</td>
                <td>${u.bookname}</td>
                <td>${u.author}</td>
                <td style="text-align: center">
                    <img src="upload/${u.images}" width="80px" height="60px" >
                </td>
                <td>${u.press}</td>
                <td>${u.price}</td>
                <td>${u.pubtime}</td>
                <td>
                    <a href="BooksGoupdate?bid=${u.bid}">modify</a>
                    <a href="BooksDel?bid=${u.bid}" onclick="return window.confirm('Are you sure to delete?')">delete</a>
                </td>
            </tr>
        </c:forEach>
    </table>

</center>

No style, mainly to optimize the java code in jsp

8, Add filter

1. Why add filters?

This is a small example. You need to specify utf-8 for adding and modifying. If there are too many tables, there will be problems (if you forget to write, it will be garbled)

2. Implement filter

Create filter class

servle. Filter (don't use the wrong filter)

web. Required configuration in XML

 <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>com.zy.filter.MyFilter</filter-class>
        <init-param>
            <param-name>encode</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

java code implementation filtering

public class MyFilter implements Filter {

    String enconding=null;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Get web The value of encond parameter in XML, such as utf-8
        enconding=filterConfig.getInitParameter("encode");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Strong rotation
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        //Incoming type
        request.setCharacterEncoding(this.enconding);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

You can delete this sentence. It's not necessary

2. Test effect


No garbled code, the filter is successful!

summary

This time realized the upload of pictures! There is also the optimization of page jsp, adding a filter
For JSTL used in optimization, you can search EL expression and use of JSTL to see the specific use methods.

Source download address

Topics: Java