How to convert given below URL into query parameter using Servlet - java

I am new to servlet concept. My requirement is like converting restful given URL into query parameter in the body.
Given URL :
http://anydomain:8080/ServletBasics/HelloForm/India/Andhrapradesh
Required Output URL:
http://anydomain:8080/ServletBasics/HelloForm?Country=India&State=Andhrapradesh
URL fetching has been done by using given servlet code. Could anybody help me out to convert given URL into query based URL. Thanks
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
String vid = request.getRequestURI();
out.println("</body></html>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
modified code: sdfd.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String url = request.getRequestURI();
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
if(url.equals("/servletTest/v1/code")) {
String[] words = url.split("/");
String newURI = url.replace(url, "/ws/simple/Apicode?"+"first_name="+words[2]+"&"+"last_name="+words[3]);
RequestDispatcher rd = request.getRequestDispatcher(newURI);
rd.forward(request, response);
out.println(newURI);
}
else
{
out.println("bad");
}
out.println("</html>");
out.println("</body>");
out.close();
}
web.xml
<servlet>
<servlet-name>sdfd</servlet-name>
<servlet-class>sdfd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sdfd</servlet-name>
<url-pattern>/v1/code</url-pattern>
</servlet-mapping>
I am trying to convert
http://localhost:8080/servletTest/v1/code
to
http://localhost:8080/servletTest/ws/simple/Apicode?first_name=v1&last_name=code
but i am getting below error.
HTTP Status 404 - /servletTest/ws/simple/Apicode
type Status report
message /servletTest/ws/simple/Apicode
description The requested resource is not available.
Apache Tomcat/7.0.42
Kindly help me where exactly i am going wrong?
thanks

use URLRewrite
You can find the documentation in following url : http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/4.0/index.html
for example :
<rule>
<from>^/HelloForm/([a-z]+)/([a-z]+)$</from>
<to>/HelloForm?Country=$1&State=$2</to>
</rule>
To configure UrlRewrite, read manual http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/4.0/index.html

Related

How to mock RequestDispatcher so that it goes to the .jsp file?

I am trying to write the JUnit test case for the code:
In SearchController class
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<AlbumSimplified> items = spotifyService.searchAlbum(searchName);
request.setAttribute("items", items);
request.getRequestDispatcher("searchResult.jsp").forward(request, response);
}
as
public void SearchControllerTesting() throws ServletException, IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
//mocked myalbums
when(searchServiceMock.searchAlbum(anyString())).thenReturn(myalbums); when(request.getRequestDispatcher(anyString())).thenReturn(request.getRequestDispatcher("searchResult.jsp"));
searchController.doGet(request, response);
}
The error I am facing is:
java.lang.NullPointerException: Cannot invoke "jakarta.servlet.RequestDispatcher.forward(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse)" because the return value of "jakarta.servlet.http.HttpServletRequest.getRequestDispatcher(String)" is null
I believe that it is due to the fact that the uri is not identified for the request and so, it is not able to find the "searchResult.jsp" located at "/app/src/main/webapp/searchResult.jsp" where app is the root of the project directory.
Hence I tried to set the
when(request.getRequestedURI()).thenReturn("app/search"), which is the URL of the request in the browser for non-testing usage.
However, I am not able to move ahead and solve the issue.
I want the items in the request to go to the searchResult.jsp, and return me a response of type "text/html".
Thanks.

how to call a html page from spring boot application

I have tried using servlet , but it is not working.
web.xml :
<display-name>Password</display-name>
<servlet>
<servlet-name>SetPassword</servlet-name>
<servlet-class>com.cx.view.SetPassword</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetPassword</servlet-name>
<url-pattern>/view/setPassword</url-pattern>
</servlet-mapping>
I have a HTML page in [email_templates/setPassword.html]
java code :
public class SetPassword extends HttpServlet {
private static final long serialVersionUID = 7514856921920494774L;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("email_templates/setPassword.html");
requestDispatcher.forward(request, response);
}
//tried for both get and post request
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("email_templates/setPassword.html");
requestDispatcher.forward(request, response);
}
}
Url trying to access: http://localhost:8080/view/setPassword
Spring boot serves automatically static resources from one of these directories:
/META-INF/resources/
/resources/
/static/
/public/
So try to save your page in one of these folders (I would suggest /static/ or /public/)

A href link is empty but the servlet is redirecting itself to home page.how it is done ?

//inboxservlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("uname");
PrintWriter out=response.getWriter();
out.println("welcome "+name);
out.println("<a href='SentItems?uname="+name+" '>sent items</a>");
out.println("<a href=''>Logout</a>");
}
If i click logout it redirects to login page.Help me with this
Try like this
Proper way to logout is below way:
out.println("Logout")
You have to create a servlet to call logout properly:
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("loginPage.jsp").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.print("You are successfully logged out!");
out.close();
}
}
out.println("<a href=''>Logout</a>");
I believe your javascript code must be binding the event during page load time. See related javascript code.

Eclipse Internal Browser doesn't apply HTML tags

I've created a simple servlet in Java and showing its HTML output in Eclipse internal browser.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.println("<h3> Hello World </h3>");
}
But the output is like this :
Why doesn't apply <h3> tag ?
Need to set response content type:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<h3> Hello World </h3>");
}

Acess java servlet from an ajax request

I have never used ajax and have no idea if I am doing anything right. I wrote some code to test if I could access a java servlet using ajax and it didn't work.
In the script:
var xmlhttp=new xmlHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.write=xmlhttp.responseText;
}
};
xmlhttp.open("GET", "http://localhost:8080/timer/timer, true);
xmlhttp.send();
}
and in my servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//code
PrintWriter out=response.getWriter();
out.println("hi");
All I am trying to do here is write "hi". What am I doing wrong?
Thanks for any help!
After writing to an java.io.Writer you have to execute flush() the internal Buffer to execute the operation on IO level. After all writing a stream should always get closed, to free the resources:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//code
PrintWriter out=response.getWriter();
out.println("hi");
out.flush();
out.close();
}
http://docs.oracle.com/javase/6/docs/api/java/io/Writer.html#flush%28%29

Categories