- Create a new rails project named GetVsPost.
- Generate a Rails controller named ClientServer with two views named
client and server.
- Replace the ERB code in the client view client.html.erb
with this source code:
<%= form_tag 'server', :method => 'get' do %>
<p>Information to be sent to server:</p>
<p>Name:<br />
<%= text_field_tag :name, "" %></p>
<p>Gender:<br />
<%= text_field_tag :gender, "" %></p>
<p>Age:<br />
<%= text_field_tag :age, "" %></p>
<p><%= submit_tag "Submit Info to Server" %></p>
<% end %>
- Replace the ERB code in the server view server.html.erb with this
source code:
<p>Information received from client:</p>
<p>Name: <%= @name %><br />
Gender: <%= @gender %><br />
Age: <%= @age %></p>
- Replace the ERB code in the layout page application.html.erb with this code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ClientServer Example</title>
<%= stylesheet_link_tag "application", :media => "all" %>
</head>
<body>
<h2>ClientServer Example</h2>
<h3><%= @location %> View</h3>
<%= yield %>
</body>
</html>
- Replace the Ruby code in the ClientServer controller with this code:
class ClientServerController < ApplicationController
def client
@location = "Client"
end
def server
@location = "Server"
@name = params[:name]
@gender = params[:gender]
@age = params[:age]
end
end
- Display the client view in local host with this URL:
http://localhost:3000/client_server/client
- Enter values for Name, Gender, and Age in the text fields, then
click the Submit Info to Server button.
- Observe the URL (split over two lines) for the server view
http://localhost:3000/client_server/server?utf8=%E2%9C%93
&name=Alice&gender=F&age=14&commit=Submit+Info+to+Server
Notice how the information is sent to the server in the URL.
- Now replace this line in the client view
<%= form_tag 'server', :method => 'get' do %>
with this:
<%= form_tag 'server', :method => 'post' do %>
and resubmit the information to the server.
- When the information is submitted to the server using the POST method,
this error message is obtained:
No route matches [POST] "/client_server/server"
Add this line to the app/config/routes.rb file:
post "client_server/server"
then resubmit the information to the server.
- Observe the server view with
http://localhost:3000/client_server/server
Notice that the information is not sent to the server in the URL; it is sent
in the HTTP header, which is more secure.
- The POST method for sending information to the server is the default;
in the client view, defining the form with
<%= form_tag 'server', :method => 'post' do %>
produces the same result as defining the form with
<%= form_tag 'server' do %>