How to add a new endpoint to my servlet? - java

I want to add a new endpoint call say 'getAll', how can I add it ?
say I want a URL to target: www.localhost:8080/Alpha/getAll ?
Do I need to create any annotation ?
#WebServlet("/Alpha")
public class Alpha extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Alpha() {
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
doGet(request, response);
}
}

Yes, I'd declare a new servlet with an #WebServlet annotation.
#WebServlet("/Alpha")
public class Alpha extends HttpServlet {
private static final long serialVersionUID = 1L;
...
No, this would NOT necessarily be available from the URL http://localhost:8080/Alpha"'.
The first level is your Context root. This is determined by your Servlet container (here, Tomcat); not anywhere in your Java code, your web.xml, or any possible annotations.
If your ContextRoot happened to be "/", then yes: http://localhost:8080/Alpha would work. But ordinarily, your endpoint would instead be something like http://localhost:8080/mywebapp/Alpha.
Here are several examples for setting a context root in the Eclipse IDE. The specifics may vary from Tomcat, JBoss, WebSphere/Liberty, etc.
Eclipse – How to change web project context root

Related

Mapping error (I guess) while running a servlet on STS(eclipse) through Tomcat

I've just installed "Spring Tool Suite 4" and "Apache Tomcat 10" to learn about Web Application. Following some instructions, I created a new Dynamic Web Project(named 'hello') and a new servlet(named 'HelloServlet').
HelloServlet goes like
package practice;
/**
* Servlet implementation class HelloServlet
*/
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloServlet() {
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.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<h1>Hello Servlet</h1>");
}
}
When HelloServlet is run on server, it is directed to "http://localhost:8080/hello/WEB-INF/classes/practice/HelloServlet.java", not "http://localhost:8080/hello/HelloServlet" and 404 error is returned.
I found out '#WebServlet' is not automatically added when creating new servlet unlike instructoin I followed. I added #WebServlet("/HelloServlet") and then Tomcat Server returned error while starting the server.
Some additional STS and Tomcat configurations are needed?
When I try to access "http://localhost:8080/hello/HelloServlet", it works well. I am wondering why STS doesn't automatically direct to "http://localhost:8080/hello/HelloServlet"!
This is bug 577703, which is fixed in the upcoming March release.

How to make tomcat server use the right URL for a java ee servlet? [duplicate]

I've just installed "Spring Tool Suite 4" and "Apache Tomcat 10" to learn about Web Application. Following some instructions, I created a new Dynamic Web Project(named 'hello') and a new servlet(named 'HelloServlet').
HelloServlet goes like
package practice;
/**
* Servlet implementation class HelloServlet
*/
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloServlet() {
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.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<h1>Hello Servlet</h1>");
}
}
When HelloServlet is run on server, it is directed to "http://localhost:8080/hello/WEB-INF/classes/practice/HelloServlet.java", not "http://localhost:8080/hello/HelloServlet" and 404 error is returned.
I found out '#WebServlet' is not automatically added when creating new servlet unlike instructoin I followed. I added #WebServlet("/HelloServlet") and then Tomcat Server returned error while starting the server.
Some additional STS and Tomcat configurations are needed?
When I try to access "http://localhost:8080/hello/HelloServlet", it works well. I am wondering why STS doesn't automatically direct to "http://localhost:8080/hello/HelloServlet"!
This is bug 577703, which is fixed in the upcoming March release.

Junit Test of servlet with eclipse

I'm not familiar with Junit testing. For example, how can I write a Unit test for this servlet?
I really don't know where to start, please!!!
Obviously he accesses the database and I don't know how to do the test to check if the credentials entered are present in the db. Could you give me an example about this servlet please?
/**
* Servlet implementation class LoginPatient
*/
#WebServlet("/LoginPatient")
public class LoginPatient extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginPatient() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fiscal_code=request.getParameter("fiscal_code");
String user_password= request.getParameter("user_password");
PrintWriter out=response.getWriter();
ProfileManager pM=new ProfileManager();
UserBean patient= pM.ReturnPatientByKey(fiscal_code, user_password);
if(patient != null) {
HttpSession session= request.getSession();
session.setAttribute( "user" , patient);
session.setMaxInactiveInterval(-1);
out.println("1");
}
else {
out.println("0");
}
}
}
A unit test for this servlet should not actually access the DB. It should test that the servlet behaves correctly given the various results ProfileManager may return.
You need to use dependency injection so that you can mock ProfileManager in your unit test.
How you do this depends on your framework. In spring you would say:
#Component
public class LoginPatient extends HttpServlet {
...
#Autowired
public LoginPatient(ProfileManager profileManager) { ... }
...
}
Then in your test use Mockito (this is a sketch not compilable code)
public void testPresent() {
// mock the request and response, and the session
HttpServletRequest req = mock(HttpServletRequest.class);
Session session = mock(HttpSession.class);
when(req.getSession()).thenReturn(session);
...
// you might want to mock the UserBean instance too
ProfileManager pm = mock(ProfileManager.class);
when(pm.ReturnPatientByKey("aCode", "aPassword")).thenReturn(new UserBean(...));
LoginPatient servlet = new LoginPatient(pm);
servlet.doPost(req, res);
// verify that the session had the right things done to it
}

Java Servlet in Eclipse with Tomcat

I test tomcat v8 in Eclipse Mars version. I create a Dynamic Web Project, and create a servlet. However, when I visit HelloWorld servlet, the web page is Error 404. Please how fix it
HelloWorld Servlet
package com.test.servlets;
/**
* Servlet implementation class HelloWorld
*/
#WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloWorld() {
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.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.println("<h1>Hello Friends!</h1>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Firstly, narrow down the problem.
Has the app started correctly? Is it deployed at context path /TomcatTest? You can check both of these things by using Tomcat's Manager UI. To access the Manager UI you must first enable it: expand the Tomcat 8 Server node in Eclipse and look for the file /conf/tomcat-users.xml. Add the following line:
<user username="tomcat" password="password" roles="standard,manager-script, manager-ui" />
See the following for more info:
https://tomcat.apache.org/tomcat-8.0-doc/manager-howto.html#Configuring_Manager_Application_Access
Restart the server and hit the following:
http://localhost:808/manager/html
You should see you app listed as running. If it is listed but not running you will then need to look at Tomcat's log files to see what has prevented the app from starting.
If the application is listed and is running. Check that you can hit http://localhost:8080/TomcatTest/index.jsp. If so, then application is deployed correctly and problem would appear to lie with the servlet mapping.

Servlet doGet Method getting called multiple times for the same HTTP request

I have run into a weird problem. My servlet's doGet method is getting called multiple times for a single HTTP request. The rerun happens every 10-12 seconds till the initial process completes.
Below is my servlet code
private static final long serialVersionUID = WebServiceServlet.class.getCanonicalName().hashCode();
private ServletContext servletContext;
/**
* #see HttpServlet#HttpServlet()
*/
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
servletContext = servletConfig.getServletContext();
}
/*public WebServiceServlet() {
super();
}*/
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String output = null;
/*
* Calling the Operation Manager which will decide the operation type
* and call the corresponding operation binder and set the return
* response generated in http response.
*/
// Request Processing
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(output);
out.close();
}
#Override
public void destroy() {
super.destroy();
}
Below is the mapping in the web.xml
<servlet>
<description></description>
<display-name>WebServiceServlet</display-name>
<servlet-name>WebServiceServlet</servlet-name>
<servlet-class>com.servlet.WebServiceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WebServiceServlet</servlet-name>
<url-pattern>/web.do</url-pattern>
</servlet-mapping>
I am using SEAM and JSF but this is a standalone servlet. There is no exception in the logs. I have also verified that the INIT method is being called only once. It is the service method which is being repeated. The identity hash code comes same for all the reruns (System.identityHashCode(this)).
The call is being made from a REST API tester. There are no multiple calls happening from the caller. The reruns are happening over the tomcat container.
I am at my wit's end. Has anyone else faced this issue?
I had faced the same issue.
Just keep the #post method in your servlet class. Comment out #get and #put if you have.
Thanks

Categories

Resources