Vahid Abdi
Vahid Abdi

Reputation: 1

null value in Map<String,String>

I have a problem with setting the map according to the following code. In this way, the value of the parameters is received from the user, but after entering the value in the map according to the relevant key, null is printed. please guide me

public class ImportBatchCardRespServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private FileOutputStream out;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // Path path = Paths.get("F:\\");
            System.out.println("ImportBatchCardRespServlet-AccessFilesPath: " + getInitParameter("AccessFilesPath")); // vahid-log
            Path path = Paths.get(getInitParameter("AccessFilesPath"));

            // List<FileItem> items = new ServletFileUpload(new
            // DiskFileItemFactory()).parseRequest(request);
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                    .parseRequest(new ServletRequestContext(req));
            Map<String,String> formFields = new HashMap<>();
            
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select,
                    // etc).
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    System.out.println("req-fieldName: "+fieldName+",req-fieldValue: "+fieldValue); //vahid-log
                    formFields.put(fieldName,fieldValue);
                    System.out.println("map-fieldName: "+formFields.get(fieldName)+",map-fieldValue: "+formFields.get(fieldValue)); //vahid-log
            

Upvotes: 0

Views: 1138

Answers (1)

Michael Stiefler
Michael Stiefler

Reputation: 126

formFields.put(fieldName,fieldValue);

adds a value/key pair to your Hashmap, with "fieldName" being the key and "fieldValue" the value. In the following line...

System.out.println("map-fieldName: "+formFields.get(fieldName)+",map-fieldValue: "+formFields.get(fieldValue)); //vahid-log

... it seems you want to test-print the key/value pair. However, HashMap's "get" method parameter is the key of the key/value pair, therefore

formFields.get(fieldName)

will return the value of the key/value pair (i.e. fieldValue) and

formFields.get(fieldValue)

will likely return null as there is no key with the same name like the value. The correct output should be available using this check line instead:

System.out.println("map-fieldName: "+fieldName+",map-fieldValue: "+formFields.get(fieldName)); //vahid-log

Cheers!

Upvotes: 1

Related Questions