Posting data from Servlet to Rest webservice - java

I want to submit form data to servlet which is Jersey rest client
and inside this servlet I have to call a Restful Webservice.
I have to pass all form data to that rest Webservice and after that we will get a response object from rest to servlet.
I have to pass this response object directly to JSP page here request and response will be in JSON format.

you can use servlet to send data to web service by sendRedirect("<url>")

Is it really necessary to call REST Class from a Servlet?
If so, the following is the way. But your REST call will be treated as a plain class. To call any method of the Rest class you have to create its object and access its methods.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestURI = req.getRequestURI();
RestClass restClassObj = new RestClass();
String parameter1 = "";
String parameter2 = "";
String parameter3 = "";
String restResponse = "";
if(StringUtils.endsWith(requestURI, "services") || StringUtils.endsWith(requestURI, "services/")){
parameter1 = req.getParameter("parameter1");
parameter2 = req.getParameter("parameter2");
parameter3 = req.getParameter("parameter3");
restResponse = restClassObj.getRestClassMethodResponse(parameter1,parameter2,parameter3);
}
resp.setContentType("application/json");
resp.getWriter().write(restResponse);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
Now the RestClass is,
public class RestClass {
public RestClass() {
}
public String getRestClassMethodResponse(#FormParam("parameter1") String parameter1, #FormParam("parameter2") String parameter2, #FormParam("parameter3") String parameter3){
//Now write your own logic and return the data to the Servlet class in //JSON format
return jsonResponse;
}
}

Related

POST datas via Angular.post and retrieve it as JSON through servlet

I have an interface as so:
export interface Product {
product: string;
quantity: number;
status: string;
}
I post an Array populated with datas of this interface type:
sendDatas(productsArray:Product[])
{
const header: HttpHeaders = new HttpHeaders({'Content-Type': 'application/json'});
const options = {headers : header};
this.http.post<any>("/ssservice", JSON.stringify(productsArray), options).subscribe();
}
I want to retrieve the data sended with Angular in my servlet as JSON (I though using GSON library) and eventually know if that's not too much how to
to finally convert it to a List<List<Object>>type
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
WhichTypeToUse? JSONvalue = request.iDontKnowWhatMethodToUseToGrabValues();
List<List<Object>> convertedValues = HowCanIconvertTheValues(JSONvalue)
}
How can I achieve that? any help is greatly appreciated.

SpringBoot embedded tomcat server reads unicode character in query parameter as null

I have a rest end point designed in spring boot. Tomcat is being used as embedded server. It takes a query parameter.
When I pass query parameter as param1%uFF07 tomcat internally reads parameter as null
When I pass query parameter as param1%FF07 tomcat reads as some character.
tomcat only reads '%' character when followed by two hexadecimal numbers, if u is placed after '%' character tomcat parse parameter as null with message
Character decoding failed. Parameter [name] with value [param1%uFF07]
has been ignored. Note that the name and value quoted here may be
corrupted due to the failed decoding. Use debug level logging to see
the original, non-corrupted values. Note: further occurrences of
Parameter errors will be logged at DEBUG level.
Here is spring boot controller code
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value = "name", required = false) String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
You are passing % sign in your url, but % is symbol in url, to pass % as it is... you will have to pass %25 then it will work as you expected.
So, if you pass %25uFF07 then it will show you %uFF07 as value.
No need to change anything in application.properties or any kind of settings. I have tested this in my project.
Please feel free to ask for any clarification. Hope It Helps.
I found out a way using filters. Basics about filters could be found over here. We can intercept request query string there and use Tomcat UDecoder class to parse the query string and if any exception is thrown we can show response of 400
public class SimpleFilter implements Filter {
private final UDecoder urlDecoder = new UDecoder();
private final Logger logger = LoggerFactory.getLogger(SimpleFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
String queryString = httpServletRequest.getQueryString();
if (queryString != null) {
ByteChunk byteChunk = new ByteChunk();
byteChunk.setBytes(queryString.getBytes(), 0, queryString.length());
try {
urlDecoder.convert(byteChunk, true);
} catch (IOException ioException) {
logger.error("Hazarduos character found in request parameter.");
httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());
return;
}
}
chain.doFilter(request, response);
}
#Override
public void destroy() {
}
}

How parse object in HttpServletResponse?

I have a problem when I try to encode object in http response. I do not know how to do it. I will have use the header?
public class Download extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{
PersistenceManager pm = PMF.get().getPersistenceManager();
String method = req.getParameter("method");
if(method.equals("view")){
Query query = pm.newQuery(Article.class);
List<Article> articles=null;
try {
articles=(List<Article>) query.execute();
}
finally {
query.closeAll();
}
Article article= art.get(0);
res.setContentType("application/octet-stream");//??
//problem here
}
}
}
There is a setHeader() method on the HttpServletResponse class. For example, you can set the content type using the following statement:
response.setHeader("Content-Type", "text/html");
Here is a link with a good tutorial on the topic: http://tutorials.jenkov.com/java-servlets/httpresponse.html
Here is the JavaDoc on the class if you need more parameters:
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html

Forward request to another rest service using filter

I am writing a servlet filter to forward Jersy requests based on certain condition. But they does not seem to forwarding.
public class SampleFilter
extends GenericFilterBean
{
#Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException
{
String generateRedirectUrl=FormURL((HttpServletRequest)req);
RequestDispatcher dispatcher = req.getRequestDispatcher(generateRedirectUrl);
dispatcher.forward(req, resp);
}
private String FormURL(HttpServletRequest req)
{
// get the request check if it contains the customer
String reqUrl = req.getRequestURI();
log.info("Original Url is"+reqUrl);
if(reqUrl.contains("test"))
{
return "/api/abcd/" +"test";
}
return "Someurl";
}
}
I need to forward the url as below.
Original: http://localhost/api/test/1234/true
New URL:http://localhost/api/abcd/1234/true
Am I doing any thing wrong.
"Am I doing any thing wrong."
In general I think this will work - you can forward from a filter, but your logic is wrong.
Using your rule below:
Original: http://localhost/api/test/1234/true
New URL:http://localhost/api/abcd/1234/true
The code:
if(reqUrl.contains("test"))
{
return "/api/abcd/" +"test";
}
will produce /api/abcd/test which is not what you're after.
I would do something like the following:
private String formURL(HttpServletRequest req) {
// get the request check if it contains the customer
String reqUrl = req.getRequestURI();
if (log.isInfoEnabled() {
log.info("Original Url is"+reqUrl);
}
if(reqUrl.contains("test")) {
return reqUrl.replace("test", "abcd");
}
return "Someurl";
Also, the code is very brutal. This will also change the URL
http://test.site.com/abd/def
to
http://abcd.site.com/abd/def
which is probably not what you want. You'll probably need to either do more clever string manipulation or convert to something like the URI class which will allow you to target the path more accurately.
Hope this helps,
Will

How to redirect to a JSP file from Servlet

I'm a beginner and am trying to understand how to re-direct to a JSP file from a Servlet. My Servlet "generates" a result after receiving replies from a current JSP file and with that I result I want to pass it to a different JSP file. I understand that there is a line of code:
request.getRequestDispatcher("/upload.jsp").forward(request, response);
But do I create a separate method for that and call it in the doGET?
you can do
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/upload.jsp").forward(request, response);
}
even though you created a method seperately you need the request and response object to the method.
I am heavily recommending the official docs:
http://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html
and the pictorial
If you're using version 3.0 with annotations the redirects are very simple.
Suppose you have a User class (Strings fullname and Username with setters and getters) and UserDAO class that deals with database manipulation .
Suppose this is your controller:
#RequestMapping(value = "/user_list")
public String users(HttpServletResponse response, HttpServletRequest request)
{
//some function to verify access
boolean authorized = client.getAccess();
request.setAttribute("authorized", authorized);
if (authorized)
{
List<User> users = UserDAO.geUsers();
request.setAttribute("users", users);
return "user_list";
}
else
{
return "access_denied";
}
}
Then you can redirect from any location using the following syntax
#RequestMapping(value = "/create_user", method = RequestMethod.POST)
public String add_user(HttpServletResponse response, HttpServletRequest request)
{
boolean authorized = client.getAccess();
if (authorized)
{
User user = new User();
user.setUserName(request.getParameter("username"));
user.setFullName(request.getParameter("fullname"));
if (UserDAO.saveUser(user))
{
return "redirect:/user_list";
}
else
{
return "error";
}
}
else
{
return "access_denied";
}
}
The redirect:/user_list will return updated user_list (eg if you were inserting to db your
changes will be reflected).
Btw: you can drop the .jsp and path in your controller if you add few lines to your xml:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-xml-example/
Have a look at those tutorials:
http://www.javatpoint.com/spring-3-mvc-tutorial
http://www.javatpoint.com/servlet-tutorial

Categories