Spring MVC JSP Form not Updating with Values from Session
I was having some problem when trying to set the value from session into input for Spring MVC project. In my SessionFilter class, I am generating authentication token:
public static final String CSRFTOKEN = "CSRFToken";
session.setAttribute(Constants.CSRFTOKEN, "test123"); // to be put into jsp hidden field
In my JSP, I am fetching the value from session in this way:
<input type="hidden" name="csrfToken" value="${CSRFToken}" />
However, the problem is, the JSP form does not update the value from session. For instance, in first click, the token value is test123, then it is set to the form already, then I will run the SessionFilter class again to regenerate the token, in this case, it generates test456. When I go to my JSP again, the token shown is still test123.
Is there any way to force update the JSP form with value from session?
Thanks!
See also questions close to this topic
-
Matcher doesn't contain all matched groups
I have a RegEx that will match a pattern as follows:
@Mike Hello Mike, how are you doing today?
Hello, I'm Mike.
My RegEx looks as follows:
^(?:@(\w|-|_|)*)?\s*(.*)$
However in my Code the
Matcher
somehow only recognizesHello Mike ......
.@Mike
isn't recognized.Code:
public static void main(String[] args) { String withAt = "@Mike Hello Mike, how are you doing today?"; String withoutAt = "Hello, I'm Mike."; matchString(withAt); matchString(withoutAt); } private static void matchString(String messageString) { System.out.println("Maching String: " + messageString); Pattern messagePattern = Pattern.compile( "^(?:@(\\w|-|_|)*)?\\s*(.*)$" ); Matcher matcher = messagePattern.matcher(messageString); if (matcher.find()) { System.out.println("@: " + matcher.group(1)); System.out.println("Message: " + matcher.group(2)); } }
Running this peace of code will result in the following output:
Maching String: @Mike Hello Mike, how are you doing today? @: Message: Hello Mike, how are you doing today? Maching String: Hello, I'm Mike. @: null Message: Hello, I'm Mike.
Question:
Why does the
withAt
-String not print an@: Mike
to the console? Where is this peace of information? -
Java 8 library for HTTP/2 requests?
Is there a Java 8 library that supports HTTP/2 requests? I've tried using OkHttp, but as far as I'm aware there's no way to specifically force it to use HTTP/2, and the server I'm using doesn't support ALPN or HTTP/1.1. I know there's the HttpClient class in Java 9, but I'm not able to upgrade.
I'm using nghttp2 for context.
-
How to make my own CyclicBarrier without use CyclicBarrier from Java Library
I am working in PacMan game for the University and basically I have to make my own CyclicBarrier, because I can't use the CyclicBarrier library from Java. This Barrier will be used to retain ghosts when they arrive to a specific position (GhostGoal) and they must wait for more ghosts until a maximum of ghosts that is given in the constructor of my CyclicBarrier. Ghosts objects implements runnable (Threads).
I was constructing my CyclicBarrier in this way:
public class Barreira { private int num_threads; private int count; public Barreira(int num_threads) { this.num_threads=num_threads; } public synchronized void await() { while(count < num_threads) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } notifyAll(); } public synchronized void adiciona() { count+=1; } public int getNumThreadsNaBarreira() { return count; } public synchronized void reset() { count=0; } }
And the code where I call the barrier (after initialize it with the name barreira) is in this void in this way:
public synchronized void arrivePosition(){ ... if((Object)floor[y][x] instanceof GhostGoal && entity instanceof Ghost ) { barreira.adiciona(); barreira.await(); } }
However when a ghost arrive to the position, all ghosts stop moving and not only the ghost that is in the position... Basically everything freeze, because of the wait in my Barrier called barreira.
Anyone can help?
Thank you very much.
-
Apache POI docs encryption by adding a password
I want to add a password to the docs created in Apache POI. I am unable to open the file. It said it is corrupted.
Here is the error:
Here is my encrption code:
static boolean encryptOne(String documentPath, String password) { try { POIFSFileSystem fs = new POIFSFileSystem(); EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard); Encryptor encryptor = info.getEncryptor(); encryptor.confirmPassword(password); OPCPackage opc = OPCPackage.open(new File(documentPath), PackageAccess.READ_WRITE); OutputStream os = encryptor.getDataStream(fs); opc.save(os); opc.close(); FileOutputStream fos = new FileOutputStream(documentPath); fs.writeFilesystem(fos); fos.close(); System.out.println("Document successfully encrypted"); return true; } catch (IOException | GeneralSecurityException | InvalidFormatException e) { e.printStackTrace(); return false; } }
-
In Junit 5, Testing not fetching data from database in intellij
When Making request from postman, data is comming but in case of junit 5 testing, api returing empty list.
package com.skc.task.controller; import com.skc.task.repository.UserRepository; import com.skc.task.service.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
@ExtendWith(SpringExtension.class) @WebMvcTest(UserController.class) class UserControllerTest { @Autowired MockMvc mockMvc; @Autowired WebApplicationContext webApplicationContext; @MockBean private UserService userService; @MockBean private UserRepository userRepositstrong textory; @BeforeEach void setUp() { mockMvc = webAppContextSetup(webApplicationContext).build(); } strong text @Test void getAllData() throws Exception { //RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/getAllData"); MvcResult result = mockMvc.perform(get("/getAllData")) .andExpect(status().isOk()) .andReturn(); System.out.println("My Result" + result.getResponse().getContentAsString()); } }</code>
-
How to set value of related entities(objects)
I have two entity that have a relation,The relationship works fine, but how can I set value from one object to another in controller.
@Entity @Table(name = "material_manu_calculator") public class MaterialManuCalcu { @Id @GeneratedValue @Column(name = "no") private int no; @ManyToOne @JoinColumn(name = "order_id") private OrderProductManu orderProductManu; //.....getters and setters and constructors}
Below is the second Entity
@Entity @Table(name = "orders_products_manu") public class OrderProductManu { @Id @GeneratedValue @Column(name = "order_id") private int orderManuId; @OneToMany(cascade = CascadeType.ALL,mappedBy = "orderProductManu") private List<MaterialManuCalcu> materialCalcu = new ArrayList<>(); //.....getters and setters and constructors}
below is the Repository
@Repository @Transactional public interface OrderProductManuRepository extends JpaRepository <OrderProductManu, Integer> { @Query(value ="SELECT *FROM orders_products_manu WHERE orders_products_manu.order_id =?", nativeQuery = true) public OrderProductManu getOrderProductById(int id); }
I want to set the value of MaterilaManuCalcu in controller as below
@Controller public class ProductsController { @Autowired private OrderProductManuRepository orderRepo; OrderProductManu orderProduct = orderRepo.getOrderProductById(1); MaterialManuCalcu manCalc = new MaterialManuCalcu(); manCalc.setOrderProductManu(orderProduct.getOrderManuId()); // I get the error says: // The method setOrderProductManu(OrderProductManu) in // the type MaterialManuCalcu is not applicable for the arguments (int)
Update: Constructors
public MaterialManuCalcu(int no, int amountOrdered, int amountAvailable, int amountWillRemain, MaterialManu materialmanu, OrderProductManu orderProductManu) { this.no = no; this.amountOrdered = amountOrdered; this.amountAvailable = amountAvailable; this.amountWillRemain = amountWillRemain; this.materialmanu = materialmanu; this.orderProductManu = orderProductManu; }
Another one
public OrderProductManu(int orderManuId, String customerName, int amountOrderedManu, String dateOrdered, Users users, ProductsManu productsManu) { this.orderManuId = orderManuId; this.customerName = customerName; this.amountOrderedManu = amountOrderedManu; this.dateOrdered = dateOrdered; this.users = users; this.productsManu = productsManu; }
Update:Showing how both entities are created
For : OrderProductManu
OrderProductManu orderProduct = new OrderProductManu(); orderProduct.setDateOrdered("2021-04-14"); orderProduct.setAmountOrderedManu(platenum); orderProduct.setCustomerName("Wapili Mteja"); orderProduct.setUsers(userMoja.get(0)); orderProduct.setProductsManu(typeofProduct); orderProductManus.setOrderManuId(007);//this is the value that I want to set inside //MateriaManCalcu entity for property setOrderProductManu //You can check the relationship above
For: MaterialManuCalcu
MaterialManuCalcu manCalc = new MaterialManuCalcu(); manCalc.setAmountAvailable(availableSheets); manCalc.setAmountOrdered(sheetsNum); manCalc.setAmountWillRemain(sheetWillRemain); manCalc.setMaterialmanu(materialSheet); manCalc.setOrderProductManu(orderProduct);//doing this the whole object of //orderProduct entity goes inside a one column in our MatrialManuCalcuof entity
Table:material_manu_calculator
How should I do this correctly. Thanks in advance.
-
cart.js How to remove a row if qty == 0?
I would like to update the quantities of items in my shopping cart. For this, I am using javascript. This is the code I have; right now this code only updates the cart when an item is added, but it does not update the cart when I remove the item. I need to remove the row if qty == 0.
(function() { 'use strict'; $(function () { $('.update-qty-form').submit(function(event){ event.preventDefault(); var row = $(event.target).closest("tr"); var itemId = row.attr("itemId"); var qty = row.find(".qty-input").val(); $.post( "updateqty",{ id: itemId, qty: qty, url: "/cart/delete/" + productId }); }) })
});
-
Read response after URL redirection in jsp
I have a new requirement to call a third party jsp page from my application and read the success or failure response from the third party URL. So what I am doing is calling the third party jsp from my application's index.jsp using the following code
<%@ page import = "java.io.*,java.util.*" %> <html> <head> <title>Page Redirection</title> </head> <body> <center> <h1>Page Redirection</h1> </center> <% // New location to be redirected String site = new String("http://www.tfa.com"); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); %> </body> </html>
Once this pages is opened the user enters the inputs here and clicks on submit. Post submitting the page returns the following response based on success or failure
<return> <authenticationSuccessful>true</authenticationSuccessful> <respCode>1</respCode> <respMessage>User passed token authentication</respMessage> </return> </ns2:performTokenAuthResponse> </S:Body> </S:Envelope>
Now can someone let me know how can I read this response from the third party URL in my index.jsp code and format it in the below format
'{" Errorcode":"1", " Errormsg":"User passed token authentication", " Token":""}';
- error: package net.sf.jasperreports.engine.design does not exist JAVA
-
Clear Event ID and call a new one without refreshing the page
I'm parsing array of events from mysql and list them into a landing page. The user can click a button to send a message to the event organizer. The user should login before sending the email so I sent the event ID with the http request and return it back when session is sent than call via ajax to populate the modal and send the message. Everything is going fine until now however the user should reload the page to clear the last event id and call a new one all over again.
Below is the code where I set
data-jid="<?= $jid; ?>"
where it set the event id attached to the button and send it via http request once redirected to the login page<?php if ($this->session->userdata('is_user_login')) : ?> <button type="button" class="btn btn-secondary btn-block rounded contactBiz" data-toggle="modal" data-jid="<?= $jid; ?>" data-target="#modalApply"><?=trans('apply')?></button> <?php else: $last_request_page = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $this->session->set_userdata('last_request_page', $last_request_page); ?> <a href="<?= base_url(); ?>auth/login?id=<?= $jid; ?>" data-jid="<?= $jid; ?>" class="btn btn-secondary btn-block rounded preapply"><?=trans('apply')?></a> <?php endif; ?>
In the login page I've set the session of the event id as following:
<?php if(isset($_GET['id'])) { $this->session->set_userdata('event_id', $_GET['id']); } ?>
Now after the user redirects back the last clicked button will be populated to send the message using below javascript call.
<?php if (!empty($this->session->userdata('event_id'))) { $sID = $this->session->userdata('event_id'); ?> $(document).ready(function(){ $(".contactBiz").trigger("click"); }); <?php } ?> <?php if ($this->session->userdata('is_user_login')) : ?> $('.contactBiz').click(function(e){ e.preventDefault(); var id; var csrfName = '<?php echo $this->security->get_csrf_token_name();?>'; var csrfHash = '<?php echo $this->security->get_csrf_hash();?>'; var data = { <?php if (!empty($this->session->userdata('event_id'))) { ?> id: <?= $sID; ?>, <?php } else { ?> id: $(this).attr('data-jid'), <?php } ?> uid: <?= $this->session->userdata('user_id'); ?>, }; data[csrfName] = csrfHash; $.ajax({ cache: false, url: base_url + 'job-data', dataType: 'json', type: 'POST', data: data, error: function(jqXHR, textStatus, errorThrown) { alert('Something is wrong'); }, success: function(data) { console.log(data); $("#subject").val(data[0].title); $(".messageTitle").empty().append( " <?= trans('message'); ?> " + data[0].name + " about " + data[0].title ); p1 = data[0].business_id; p2 = data[0].email; <?php $this->session->unset_userdata('event_id'); ?> } }); }); <?php endif; ?>
Now everything as said is fine, the last clicked button is populated using the event id
data-jid="<?= $jid; ?>"
but what happens next the user got stuck with the same event id repeated for all buttons.The solution I used in the ajax call to define the id as below:
<?php if (!empty($this->session->userdata('event_id'))) { ?> id: <?= $sID; ?>, <?php } else { ?> id: $(this).attr('data-jid'), <?php } ?>
And after the successful ajax response I'm clearing the session as set below:
<?php $this->session->unset_userdata('event_id'); ?>
I think my mistake is here however I couldn't find any better solution, your advice is highly appreciated thank you!
-
Laravel - Implement a Custom Guard for login with third parties API
this is my scenario:
I have a Laravel 8 application that needs to communicate with a third party API to send credentials and retrieve the related user to implement my login workflow. I need to do not store the user in a database but only in a session temporary store. After that I would like to use the Auth facade as usual but using my user provider.
This is what I implemented.
MyUserProvider.php
<?php namespace App\Providers; use App\Models\User; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Support\Facades\Log; class MyUserProvider implements UserProvider { public function retrieveById($identifier) { return aUser($identifier); } public function retrieveByToken($identifier, $token) { return aUserByToken($identifier,$token); } public function updateRememberToken(Authenticatable $user, $token) { Log::debug("update by tkn"); } public function retrieveByCredentials(array $credentials) { return aUserByCred($credentials); } public function validateCredentials(Authenticatable $user, array $credentials) { return areCredValid($user,$credentials); } }
MyGuard.php
<?php // app/Services/Auth/JsonGuard.php namespace App\Services; use Illuminate\Http\Request; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\UserProvider; use GuzzleHttp\json_decode; use phpDocumentor\Reflection\Types\Array_; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Support\Facades\Log; class MyGuard implements Guard { protected $request; protected $provider; protected $user; public function __construct(UserProvider $provider, Request $request) { $this->request = $request; $this->provider = $provider; $this->user = NULL; } public function check() { return !is_null($this->user()); } public function guest() { return !$this->check(); } public function user() { if (!is_null($this->user)) { return $this->user; } } public function id() { if ($user = $this->user()) { return $this->user()->getAuthIdentifier(); } } public function validate(array $credentials = []) { $user = $this->provider->retrieveByCredentials($credentials); if (!is_null($user) && $this->provider->validateCredentials($user, $credentials)) { $this->setUser($user); return true; } else { return false; } } public function setUser(Authenticatable $user) { $this->user = $user; return $this; } }
AuthServiceProvider
<?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Auth; class AuthServiceProvider extends ServiceProvider { protected $policies = []; public function boot() { $this->registerPolicies(); Auth::provider('mine', function ($app, array $config) { // Return an instance of Illuminate\Contracts\Auth\UserProvider... return new MyUserProvider(); }); Auth::extend('mine', function ($app, $name, array $config) { return new MyGuard(Auth::createUserProvider($config['provider']), $app->make('request')); }); } }
In the auth.php
'defaults' => [ 'guard' => 'mine', 'passwords' => 'users', ], 'providers' => [ 'mine' => [ 'driver' => 'mine' ], ],
After that I've used the default Breeze login flow that invoke this method on the controller:
public function store(LoginRequest $request) { $request->authenticate(); $request->session()->regenerate(); return redirect()->intended(RouteServiceProvider::HOME); }
The user is valid, it is retrieved by credentials but it looks like it is not persisted, because after the "redirect" the check method of "MyGuard" returns false.
How to persist the user during the session to be able to maintain him logged in?
-
Rails API multiple databases with session middleware not working
The error I am getting is
undefined method `[]=' for nil:NilClass - actionpack (6.1.3.1) lib/action_dispatch/request/session.rb:235:in `load!' - actionpack (6.1.3.1) lib/action_dispatch/request/session.rb:230:in `load_for_write!' - actionpack (6.1.3.1) lib/action_dispatch/request/session.rb:216:in `merge!' - actionpack (6.1.3.1) lib/action_dispatch/request/session.rb:19:in `create' - actionpack (6.1.3.1) lib/action_dispatch/middleware/session/abstract_store.rb:71:in `prepare_session' - rack (2.2.3) lib/rack/session/abstract/id.rb:265:in `context' - rack (2.2.3) lib/rack/session/abstract/id.rb:260:in `call' - actionpack (6.1.3.1) lib/action_dispatch/middleware/cookies.rb:689:in `call' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector.rb:53:in `block in call' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector/resolver.rb:63:in `block (2 levels) in read_from_replica' - activesupport (6.1.3.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector/resolver.rb:62:in `block in read_from_replica' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:383:in `block (2 levels) in with_role_and_shard' - activerecord (6.1.3.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:1025:in `while_preventing_writes' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:381:in `block in with_role_and_shard' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:398:in `swap_connection_handler' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:373:in `with_handler' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:380:in `with_role_and_shard' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:175:in `connected_to' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector/resolver.rb:61:in `read_from_replica' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector/resolver.rb:39:in `read' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector.rb:63:in `select_database' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector.rb:52:in `call' - rack (2.2.3) lib/rack/etag.rb:27:in `call' - rack (2.2.3) lib/rack/conditional_get.rb:27:in `call' - rack (2.2.3) lib/rack/head.rb:12:in `call'
or
undefined method `id' for {}:Hash - rack (2.2.3) lib/rack/session/abstract/id.rb:329:in `current_session_id' - rack (2.2.3) lib/rack/session/abstract/id.rb:313:in `load_session' - actionpack (6.1.3.1) lib/action_dispatch/middleware/session/abstract_store.rb:45:in `block in load_session' - actionpack (6.1.3.1) lib/action_dispatch/middleware/session/abstract_store.rb:53:in `stale_session_check!' - actionpack (6.1.3.1) lib/action_dispatch/middleware/session/abstract_store.rb:45:in `load_session' - actionpack (6.1.3.1) lib/action_dispatch/request/session.rb:234:in `load!' - actionpack (6.1.3.1) lib/action_dispatch/request/session.rb:230:in `load_for_write!' - actionpack (6.1.3.1) lib/action_dispatch/request/session.rb:216:in `merge!' - actionpack (6.1.3.1) lib/action_dispatch/request/session.rb:19:in `create' - actionpack (6.1.3.1) lib/action_dispatch/middleware/session/abstract_store.rb:71:in `prepare_session' - rack (2.2.3) lib/rack/session/abstract/id.rb:265:in `context' - rack (2.2.3) lib/rack/session/abstract/id.rb:260:in `call' - actionpack (6.1.3.1) lib/action_dispatch/middleware/cookies.rb:689:in `call' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector.rb:53:in `block in call' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector/resolver.rb:63:in `block (2 levels) in read_from_replica' - activesupport (6.1.3.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector/resolver.rb:62:in `block in read_from_replica' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:383:in `block (2 levels) in with_role_and_shard' - activerecord (6.1.3.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:1025:in `while_preventing_writes' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:381:in `block in with_role_and_shard' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:398:in `swap_connection_handler' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:373:in `with_handler' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:380:in `with_role_and_shard' - activerecord (6.1.3.1) lib/active_record/connection_handling.rb:175:in `connected_to' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector/resolver.rb:61:in `read_from_replica' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector/resolver.rb:39:in `read' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector.rb:63:in `select_database' - activerecord (6.1.3.1) lib/active_record/middleware/database_selector.rb:52:in `call'
I created a new rails api only app with
rails new my_api --api --database=postgresql
I set up multiple database functionality as per the docs say.
I add session middleware back into my api so I followed the docs
The following are the only changes I have made to a fresh app
require_relative "boot" require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "active_storage/engine" require "action_controller/railtie" require "action_mailer/railtie" require "action_mailbox/engine" require "action_text/engine" require "action_view/railtie" require "action_cable/engine" # require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module MyApi class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.1 # Only loads a smaller set of middleware suitable for API only apps. # Middleware like session, flash, cookies can be added back manually. # Skip views, helpers and assets when generating a new resource. config.api_only = true # This also configures session_options for use below config.session_store :cache_store, key: '_app_session_key' # Required for all session management (regardless of session_store) config.middleware.use ActionDispatch::Cookies config.middleware.use config.session_store, config.session_options config.active_record.database_selector = { delay: 2.seconds } config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end end