I'm making a Java Web Application but I'm newbie in Java.
I have a Servlet (/locatemodules) that try to find other servlets in the server (/modules/*), currently the servlet find the name of the other servlets (/modules/logout, /modules/invoice, etc), but I need to get some properties and call methods to the discovered servlets, the properties and methods are the same in all servlets.
Calling like: discoveredServlet.getMenuItem();
getMenuItem returns some values, menuName, menuUrl, sideMenu[], sideUrl[], etc... to make a menu item in the web application dinamically, the discovered servlets has the post and get for when is called on the main menu.
I'm find Inter Servlet Communication articles, but unfourtunally doesn't work with API 2.2 and later.
How can get a solution like this?
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Loaded extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
ServletContext context = getServletContext();
Enumeration names = context.getServletNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
Servlet servlet = context.getServlet(name);
out.println("Servlet name: " + name);
out.println("Servlet class: " + servlet.getClass().getName());
out.println("Servlet info: " + servlet.getServletInfo());
out.println();
}
}
}
Servlets are the classes that are supposed to accept requests on servers and respond them.
As you are making an HTTPServlet so it is supposed to accept an http request via http methods like get and post (so you get methods doGet() and doPost() in servlets), and then servlet processes the request and sends the http response.
If you want to communicate between servers then you should set some attributes using setAttribute() method and then redirect (using response.sendRedirect()) or forward your request to another servlet and use getAttribute() method to receive values.
Servlets are not meant to be used like normal classes, that you make objects of servlet class and call its methods.
As a design principle, Servlets should only be used to receive requests from the container, invoke classes that contain business logic, and redirect to a JSP that shows the response (MVC pattern). All the business logic should be on clases that are decoupled from the HTTP protocol.
So, I think the best thing you could do, is to remove these menu related methods from your servlets, put them on POJOs, and invoke this POJOs from your servlets.
Also, remember that normally, Servlets are Singletons.
Related
I am trying to make an API with Jetty Server, and I have this simple GET request:
#GET
public String helloWorld(){
return "Hello world";
}
In order to make a POST request, I assume that one must save the input to the Jetty server. I have tried to research for quite a while, but found nothing.
I imagine something like this:
#POST
public void Save(String stringToSave) {
// Save to DB?
}
You could likely google this but let me give you a quick overview. A Servlet is a chunk of code that is normally run during an HTTP action - GET, POST, etc. It is the original technology of the JavaEE world, having been released in the late 1990's.
A simple Java servlet, using modern annotations, would look something like:
#WebServlet(name = "SampleServlet", urlPatterns = "/sampleServlet")
public class SampleServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// called when an HTTP POST is sent
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// called when an HTTP GET is sent
}
}
The important parts to note are that the class extends HttpServlet and that you have to write code to pull data out of the request and push it into the response. This isn't bad to do but it does have to be done.
JAX-RS is a newer standard, aimed simplifying the creation of REST services. It too is a chunk of code that runs during an HTTP interaction.
A simple example of this would be:
#Path("/sampleService")
public class SampleService{
#Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#POST
#Path("/v1/hello")
public Response sayHello( SomeObject someobject ) {
The code here is both simpler and a bit more complex. The use of annotations helps determine the path that the service exists on a URL (in this case /sampleService/v1/hello), the HTTP method, and the Content-Type for both the request and response. Additionally, if the SomeObject object is defined correctly, the JAX-RS framework will automatically deserialize the incoming JSON or XML payload into an object for you.
The Response object contains the HTTP response code (perhaps a teapot) and a response body. In this example, the body will be automatically serialized back to the requestor in a way that matches the Accept header of the HTTP request (i.e., JSON for an application/json Accept header and XML for application/xml).
Note that while not directly related the JAX-RS framework takes advantage of the Servlet framework. Indeed in JAX-RS you can access the HttpServletRequest and HttpServletResponse object in your methods.
Which way is "better"? In general I would recommend using JAX-RS where possible as it is the newer standard and is a bit easier to implement. However, if you do any work in the JavaEE world you're very likely to run into Servlet code so it's important to understand it too.
Note that both Servlets and JAX-RS require an application server of some sort. Jetty is one of those. Another very common one is Tomcat. The application server sets up the environment for your code and listens for incoming HTTP messages. When it gets one it looks to see if it knows how to handle the URL and routes to the appropriate place. In the servlet world the server routes solely on the URL. In the JAX-RS world the server routes on the URL and, if specified by the #Consumes annotation, the HTTP Content-Type header too.
There is much more but let's start there and see if it answers what you're after.
I am currently doing an internship where I have an existing java project that essentially processes strings and gives you an output with informations about it. I am now told to do an web interface for it, with an input field, a button to send a request, and a field for displaying the output. I was given the advice to look into REST web services. Since I have never done anything web related before, I read tons of materials, and am now a bit confused. Please tell me if I got the following points correctly.
For the webservice, I can use JAX-RS, so I will use a class like that:
#Path( "result/{input}" )
public class ResultResource
{
#GET
#Produces( MediaType.TEXT_PLAIN )
public String message(#PathParam("input") String input)
{
return myApplication.processInput(input);
}
}
Now I am unsure: Can I create the web interface (button, input fields) with a jsp file or a html file? So that when the button is clicked, the url "..result/input" is called and I somehow have to read the result from the page and display it in my results field.
To make it runnable on a server, I have to deploy my REST-servlet above on tomcat / jetty.
Would be pleased to get some answers, because I am a bit lost.
You can do this in a jsp file, you just use normal html for your form and button etc.
In your form do action="/yourServlet?param=yourInput" method="post".
And then in your servlet you can make a doPost method which will get your parameter like:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String input = request.getParameter("yourInput");
doSomething(input);
}
and then do whatever you want it to. You can then send it back to the desired page with
request.getRequestDispatcher("/yourPage.jsp").forward(request, response);
This should also be in your doPost. Your response here can be what you did to your input and you can then make a result field in yourPage.
To make it runnable you can indeed put in on a tomcat server.
I'm new to Java server-side programming, my question is basically to get to a starting point using Servlets (low level without using spring mvc etc.) and then build my way up from there, coming from node.js background where a route definition would start with a function (app.get(request, response) {}, app.post(request, response) {} etc.), and the function would receive request and response in parameters for one of http methods (GET, POST, PUT, DELETE).
If someone can please help on the starting point of how do I define methods against a route (let's say /users) inside a servlet class that'd map to http methods while providing request and response in it's parameters.
My attempt
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException , IOException {
}
I believe what you want are Servlet mappings. You can also find a bit more info here
But basically this is the way you tell the webserver (e.g. Tomcat) what servlet to use to answer requests sent to a given url pattern. Thus you map the pattern with the servlet you want to use to serve it.
You can also find more info on the inner workings here.
Edit: If you want to handle all verbs you can use a service. From the first link:
You may have seen other servlet examples implement the doPost() and/or doGet() methods. These methods reply only to POST or GET requests; if you want to handle all request types from a single method, your servlet can simply implement the service() method. (However, if you choose to implement the service() method, you cannot implement the doPost() or doGet() methods, unless you call super.service() at the beginning of the service() method.) The HTTP servlet specification describes other methods used to handle other request types, but all of these methods are collectively referred to as service methods.
All the service methods take the same parameter arguments. An
HttpServletRequest provides information about the request, and your
servlet uses an HttpServletResponse to reply to the HTTP client. The
service method looks like the following:
public void service(HttpServletRequest req,
HttpServletResponse res) throws IOException { ... }
I have 2 java classes and I want to transfer data between them.
I take user id as parameter in a previous jsp form, and in a java class, using setAttribute I create a atribute named st_id.
then in another java clas I want to retrieve this data, but I get null.pointer exception.
first java file;
public class Signin implements Action {
public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
Student stu = new StDAO().getUser(request.getParameter("st_id").toString());
request.setAttribute("st_id", request.getParameter("st_id").toString());
...
second;
public class addCourseStu implements Action{
#Override
public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
TakeCourseDAO pf = new TakeCourseDAO();
String s= (String) request.getAttribute("st_id");
So s is null, it's not my intention.
A request exists from the time the web browser sends it to the web server until the web server (via the servlet) has made its response.Every request for a servlet has its own accessibilty scope. From a servlet, you can:
add new attributes to the request's scope
obtain exisiting attributes from the request's scope
remove exisiting attributes from the request's scope
As you are getting null it is quite obvious that the attribute is not accessed within the scope.
You can try alternatives like Session scope or Application scopes which ever suits you
It is not entirely clear what you want to do but I gather that you want to maintain some state on the server between two requests right?
Look into sessions & cookies for this.
What you do here is weird as it seems you are setting an attribute on an incoming request in the first file.
I have a HashMap of custom objects being passed to a JSP using RequestDispatcher and I am able to access the object and its properties using JSTL.
However the code fails in case the parameter is sent using response.sendRedirect() .
I am not sure what the reason is and how to make it work?
The response.sendRedirect() basically instructs the client (the webbrowser) to send a new request on the given URL. You'll also see this being reflected by a change in the browser address bar.
A new request does of course not contain the attribtues of the previous (or any other) request. That would otherwise have broken the whole concept of "request scope".
To preprocess a GET request, you need to do the job in doGet() method of a servlet and then redirect to the URL of that servlet instead.
E.g.
response.sendRedirect(request.getContextPath() + "/foo");
and
#WebServlet("/foo")
public class FooServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, Foo> foos = fooService.map();
request.setAttribute("foos", foos);
request.getRequestDispatcher("/WEB-INF/foo.jsp").forward(request, response);
}
}
Note that this problem is in no way related to having a hashmap of custom objects in the request scope.
See also:
Our servlets wiki page
You can not share a request attribute in response.sendRedirect as it creates a new request.
But, if you want that HashMap, in response.sendRedirect, you can put that in session like
request.getSession().setAttribute("myMap", [HashMap object]);
and can share between the servlet and JSP. This works in both RequestDispatcher and sendRedirect.