[JAVA] The story that the request parameter from the iPhone application could not be obtained successfully with the Servlet

When I was creating an iPhone app myself, I didn't understand the difference between getAttribute () and getParameter (). I couldn't get the request from the app with the Servlet, so I'll leave it as a memo.

The event that occurred this time is like this.

Send a request from the iPhone app     ↓ Received by Servlet (The Servlet is reached, but the parameters in the request cannot be obtained.)

Cause

I wasn't trying to get the value with request.getAttribute. It seems that you have to get it with getParameter. .. ~~ (Jsp was completely blind because it could be obtained with getAttribute) ~~ 2020.05.22 postscript ↑ I couldn't get it. It seems that I was addicted to it because setAttribute and getAttribute were messed up in the first place. .. I studied again on this site. → getAttribute () method.

The detailed contents were described on this site. [Difference between getAttribute () and getParameter ()](https://www.it-swarm.dev/ja/java/difference between getattribute () and getparameter () / 971401730 / "Difference between getAttribute () and getParameter () the difference")

Verification

I tried to verify with a sample program to deepen the understanding. This is a sample program that displays the character string entered in the textField of the iPhone on the console.

・ IPhone screen

input.jpeg  result.png

result##

・ Console screen

コンソール結果.png After all it was not possible to get it with getAttribute

Source##

** ・ iPhone screen (input screen) **

ViewController


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var testField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    //Executed when the send button is pressed to Servlet
    @IBAction func goServlet(_ sender: Any) {
        self.performSegue(withIdentifier: "goResultView", sender: nil)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        print("prepare starts operation")
        //Set URL
        guard let req_url = URL(string: "http://localhost:8080/Test/TestServlet")
            else{return}
        print("url set complete")
        
        //Declare the information required for the request
        var req = URLRequest(url: req_url)
        print("Declaration of request")
        //Specify POST
        req.httpMethod = "POST"
        //Set POST data as BODY
        req.httpBody = "test=\(self.testField.text!)".data(using: .utf8)
        
        //Create session
        let session = URLSession(configuration: .default,delegate: nil, delegateQueue: OperationQueue.main)
        print("Create session")

                //Register request as a task
                let task = session.dataTask(with: req, completionHandler: {
                    (data, response ,error) in
        

                })
                //request send
                task.resume()
            }
   
}

** ・ iPhone screen (result screen) **

** ・ Java Servlet **

TestServlet


package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class testServlet
 */
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		System.out.println("Reaching the POST method of the Servlet");
		System.out.println("When received by getAttribute:" + "The character string sent from the iPhone app is" + request.getAttribute("test") + "is.");
		System.out.println("When received by getParameter:" + "The character string sent from the iPhone app is" + request.getParameter("test") + "is.");
	}

}

Recommended Posts

The story that the request parameter from the iPhone application could not be obtained successfully with the Servlet
The story that the Servlet could not be loaded in the Java Web application
The story that the forced update could not be implemented
Solved the problem that the test could not be executed from the command line with spring-boot-starter-test
The case that @Autowired could not be used in JUnit5
Note that Insert could not be done with Spring Data JDBC
The story of stopping because the rails test could not be done
Correspond to "error that basic authentication does not pass" in the test code "The story that could not be done"
About the problem that the server can not be started with rails s
[Java] The story that the expected array was not obtained by the String.split method.
After verifying the Monty Hall problem with Ruby, a story that I could understand well and did not understand well
A story that suffered from a space that does not disappear even if trimmed with Java The cause is BOM
Story when migration could not be done
About the case that ("b" .. "aa") could not be used in Ruby Range
The story that I could not build after installing multiple Java on Windows
[Spring Boot] The story that the bean of the class with ConfigurationProperties annotation was not found
The story that the variable initialization method called in the Java constructor should not be overridden