I'm making calls to the Java backend through servlets and for each call to the API im using i need to supply password and username. Can I save the users password/username in a variable so I can use it every time the user makes a call to the API?
Or will the variable be overwritten if there are multiple users?
The overall question perhaps is: Does every user get new "fresh" servlets or is the data saved from the users before?
Servlets are shared for performance reasons, so they should be stateless (or thread-safe, but then you'd just be reinventing the wheel). If you need to keep state with a user, put it into HttpSession.
If you use static variables then the variables got shared across the users. Also, it's a concurrency issue and you need to handle it. If the variables are not static then each user would have an excluded instance.
Anyway, If you want to store some information and you want to retrieve them in the future when a specific user call the servlet then it's common to use HttpSession. Also, consider that you need to grab the http cookie in your client and send it to the server for the further calls.
Also, it's a common scenario that server provides an API key for each client. Then whenever the client wants to call an API; it's necessary to send the key through a specific http header.
The above scenario would have some security issues if you don't use a secure connection like HTTPS between server and clients.
Does every user get new "fresh" servlets or is the data saved from the
users before?
Servlet instance will be created only once (unless you are doing something differently like using SingleThreadModel) & maintained by the container (like Tomcat, etc..), i.e., one single servlet instance is going to be used/shared by all requests.
So, don't use the servlet's instance variables to store any data.
Can I save the users password/username in a variable so I can use it
every time the user makes a call to the API?
You shouldn't be saving userids and passwords into JVM (RAM) memory because you will loose all of the data when the JVM shuts down, so you need to use some persistent store like a database (prefer this) or file system.
Related
I have a requirement to hold user list inmemory. The state of user list should maintain across different REST api calls. Like there is an api to save user, so whenever i call save, user saved in variable and will be available in anothee REST api get call.
How can i achieve this? I am thinking of some singleton class to hold data as singleton scope is at JVM level
REST architecture which means Representational State transfer which means you do not store the state of the object (or resource) in REST terms.
Every API hit is (and should be) considered a new resource manipulation call. For e.g. You may be Creating a resource (POST) , deleting a resource (DELETE) , updating a resource (PUT) and so on...
You may still want to access a resource's state i.e. in your case userlist which you may somehow update and get from database or file or temporary storage. Database would be preferred.
Your question inclines more towards maintaining sessions which is in contrary to REST API principles
I'd suggest you to go through basic principles of REST API architecture ( Precisely 6 of them)
https://restfulapi.net/
we have a JavaEE Web application that runs on Tomcat5 server (jsp, java and extjs are used on development of this tool).
We observe sometimes, particularly when the application is highly used, that some session variables or interface fields are mixed up in servlets.
This means that : when one user connects, his parameters are kept in the sessions.
After an update or insertion of data in the database ORACLE,the system returns the name of another user who was probably connected at the same time on a different navigator or a different computer.
Others times the request.getparameter gets a values from different clients or user interfaces.
Thank you to help me fix this problem.
The only way for this to happen is if you have a singleton somewhere that keeps track of the session and for some reason this singleton is mixing up the variables between sessions.
You can try this: Instead of differentiating a user only by its credentials (assuming you are not using Federation), return a token, unique amongst all sessions to the user logging in, and make the user send that unique id with every request. This way you will be able to differentiate the request/responses even if the user logs in using many different browsers.
But again, this will only happen when you do something like having a singleton connecting the session, by itself the session would not exchange variables amongst them.
I've finally understood how servlet.java works.
I works like main process that create a thread for any call
thus, all attributes of such class are common to all thread and we are not sure of the result that we get when accessing them.
If we want any client to use those variables in a private context, we must put them in the function "doGet" or "doPost" as local variables.
My problem have them been solved
We are designing a RESTFUL API that needs to support several login services.
Custom login: ptgapi/v1/clients/{clientId}/users?mode=custom
FB login: ptgapi/v1/clients/{clientId}/users?mode=facebook
Twitter login: ptgapi/v1/clients/{clientId}/users?mode=twitter
LinkedIn login: ptgapi/v1/clients/{clientId}/users?mode=linkedin
Create user: ptgapi/v1/clients/{clientId}/users
We have an Spring Integration layer in top of the services, so in based of the provided path, one of the services will need to be activated.
The idea would be to have a router that catches the inbound-gateway input and redirect the flow based on the payload value.
<int-http:inbound-gateway id="v1.login.inbound.gateway" path="/ptgapi/{apiVersion}/clients/{clientId}/users" .../>
But here 'create user' has the same routing process than the other ones...and I think this is a bad smell.
Is a better approach to obtain it with a better separation of concerns?
Thanks!
Services may have the same path/route but they are identified by the operation. In REST you will have same path for services but depending on the kind of operation you are doing the HTTP method will be different. You can differentiate your login and create services by using POST and PUT HTTP methods.
Personally speaking, I believe PUT is a better choice because PUT gives more control such as :
Do you name your URL objects you create explicitly, or let the server decide? If you name them then use PUT. If you let the server decide then use POST.
PUT is idempotent, so if you PUT an object twice, it has no effect. This is a nice property, so I would use PUT when possible.
You can update or create a resource with PUT with the same object URL
More on PUT versus POST
PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!
POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent.
For the user CRUD you should have a route like ptgapi/v1/clients/{clientId}/users and use the HTTP methods as they are supposed to: GET for returning the user, PUT for creating the user, POST for updating the user and DELETE to remove it.
The login operation is not a user entity operation per se. You should have another route, just like ptgapi/v1/clients/login and pass the login parameters via POST (encrypted preferably).
Create user is an action so maybe you can define a new route like
Create user: ptgapi/v1/clients/{clientId}/users/new
or something like this.
I want to create a Servlet that processes input to a serial device and for that reason I want to make sure that exactly one instance of Servlet exists in the container at a time (irrespective of whether the container makes only one instance I have to make sure of it) and also the access to the serial port is either synchronised or serialised.
Any suggestions?
You don't need the servlet to be a singleton, you only need to be able to control access to the serial port. In fact even if you could enforce a single instance of the servlet class, the spec enables multiple users to access the servlet concurrently.
You could instead write a class that handles access to the port, encapsulating control by only allowing a single thread to access at a time. You'd then need to decide how you wanted concurrent requests to the servlet to behave (block, return some sort of 'serial port in use' error message, etc).
Suggestion: don't do that. Leave servlet management to the container, and use your own singleton for serial port processing.
Solution: you cannot, as you have no control over constructor. What you can do, though, (and what is a Very Bad Thing—don't tell anyone I said that) is to have a static field in a servlet, keeping a reference to the first instantiated instance. This way, all the instances of the servlet will be able to delegate the processing to this very first instance.
Again, just separating request processing from serial port processing will make things much more easier for both you and the container.
I have a servlet, and that servlet uses a .net web service to perform some function. To do this, I created the webservice client in Netbeans using the "jax-rpc" style client.
Let's say that my service name is "Tester". Then two of the generated classes are called "Tester", and "TesterSoap".
To get a reference to the web service, I need to do this:
Tester t = new Tester_Impl();
TesterSoap tsoap = t.getTesterSoap();
To use the webservice, I can then do this:
tsoap.runTest();
My question is, since this is a servlet which gets executed many times, should I store the first two lines in static variables (so they only ever get executed once), or store them locally so that they execute everytime the servlet is executed?
Another way of asking the same question: is there a performance hit everytime the first two lines are called? (I'm testing everything locally so it's hard to measure).
Thanks...
If the default constructor and any of the initialization blocks of the Tester_Impl() class and the method getTesterSoap() doesn't do anything expensive (e.g. reading file from disk, loading data from DB, connecting a socket, etc, I however suppose it doesn't) then you don't need to worry about it.
You can consider declaring them as an instance variable of the class extending from HttpServlet. But, a big but, it is going to be shared among all HTTP requests, because there will be only one instance of the particular servlet class during whole application's lifetime. So if the Tester_Impl class is supposed to have a state, then it is a very bad idea to declare it as an instance variable. It would then be shared among all requests. With other words, it's not threadsafe. If you want to ensure threadsafety in servlets, then declare everything in the very same method block.
I would not optimize prematurely here. Test this out in as close to a production environment as you can (i. e. not on your local box) and see what the performance hit is. What I've done in the past is write a small shell script that hits my server with wget n times with a delay of k milliseconds and then measured the latency, possibly instrumenting the code with some timing or profiling myself (or with jvisualvm or some other profiling tool).
If you want to protect your design from a possible performance hit without doing the testing, you could use a factory to provide instances of the service client and then you could swap out singleton service clients for many of them whenever you feel like it.