how to encode and decode url in path string in java - java

I have requirement such that i need to send a URL in Ajax and the URL is /somehost/users/{userid}/feed/{feedurl} where userid and feedurl are path params which will be
accepted in a servlet written Using Rest Frame work.
My Ajax call is
$.ajax({
url : "/somehost/users/1/feeds/"+encodeURIComponent("**Please Think
that i passing a valid URL here**")),
type : "DELETE",
/*contentType: 'Content-type: text/plain; charset=iso-8859-1',*/
data : {feed_url : tr.attr("value")},
....
....
....
)};
My servlet is
#Path("/users")
public class UserServlet {
#DELETE
#Path("{user_id}/feeds/{feed_url}")
#Produces(MediaType.APPLICATION_JSON)
public String deletefee(
#PathParam("feed_url") String feedId,
#PathParam("user_id") #DefaultValue("1") String userId) {
System.out.println("I am in UserServlet delete");
}
}
Now i am not able hit my servlet.
I want to know how to send url as a #pathparam to my servlet.

If you add the extra slash to "/somehost/users/1/feeds" so it becomes "/somehost/users/1/feeds/" does that work?
Currently you are accessing a URI like "/somehost/users/1/feeds1" instead of "/somehost/users/1/feeds/1"

Related

How to get angularjs parameters in java backend?

I have an angular app with these routes:
$routeProvider
// Home screen
.when('/', {
title : 'APP.NAME',
bodyClassName : 'home',
templateUrl : 'app/custom/templates/customTemplate.html',
controller : 'customTemplateController',
resolve : { unauthorizeRequest: unauthorizeRequest }
})
.when('/connect/:connectionToken', {
bodyClassName : 'client',
templateUrl : 'app/client/templates/client.html',
controller : 'clientController',
resolve : { updateToken: updateToken}
})
.otherwise({
resolve : { unauthorizeRequest: unauthorizeRequest }
});
and on the java side:
#POST
public APIAuthenticationResult createToken(
#FormParam("connectionToken") String token,
#Context HttpServletRequest consumedRequest,
MultivaluedMap<String, String> parameters)
HttpServletRequest request = new APIRequest(consumedRequest, parameters);
String token = request.getParameter("connectionToken");
The problem is that if I use a url like:
http://localhost:8090/connect/{connectionToken here}
I always get null on the Java side. And if I use a url like:
http://localhost:8090/connect/?connectionToken={connectionToken here}
angular doesn't hit the correct route, it goes to the otherwise route, but on the Java side I can get the token via request.getParameter.
How can I deal with this?
Try to define your controller method like this:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/connect/{connectionToken}")
public Response doStuff(#PathParam("connectionToken") String token){
System.out.println(token);
//stuff..
}
or, if you're using Spring:
#RequestMapping(value="/connect/{connectionToken}", method = RequestMethod.GET, produces="application/json")
public Response getOrderEquipment(#PathVariable("connectionToken") String token){
System.out.println(token);
//stuff..
}

AngularJS consumes JAX-RS rest web service

This is the first time that I am using a Java back-end for my web application. I have a Jax-rs webservice that I am trying to consumes with my AngularJS app
AngularJS call
$http({
url : REST_END_POINT + '/checkuser',
method : "GET",
data : {
'userId' : credentials.username,
'pwd' : credentials.password
},
dataType : "json",
headers : {
"Content-Type" : "application/json"
}
});
Webservice
#GET
#Produces("application/json")
#Consumes("application/json")
#Path("checkuser/")
public string getCheckUser(#QueryParam("userId") String userId, #QueryParam("pwd") String pwd){
try{
if(port != null){
boolean result = port.checkUser(userId, pwd);
return new java.lang.Boolean(result).toString();
}
}catch(Exception ex){
//TODO
}
return null;
}
Both userId and pwd are always null
With Firebug I can see that data contains
Object{
userId="aaa",
pwd="aa"
}
I also tried with JSON.stringify which send those data :
"{"userId":"aaa","pwd":"aa"}"
I believe that the way you are trying to access your userID and pwd is incorrect, you are using the #QueryParam which would look for the userID and pwd as query parameters of the GET request like so:
http://myservice:port/checkuser?userId=myuserid&pwd=pass
if you change your GET request to
$http({
url : REST_END_POINT + '/checkuser',
method : "GET",
params : {
'userId' : credentials.username,
'pwd' : credentials.password
},
dataType : "json",
headers : {
"Content-Type" : "application/json"
}
});
Then you should have more luck.
However I wouldn't advise this method as it could be insecure. I'd instead look at trying to utilize an existing authentication system rather than rolling your own as these existing authentication systems will be far more secure.
You can use Jackson api for converting json to/ from Java objects.
Jackson contains simple mapper methods to implicitly map your json properties to Java class member variables.
Instead of #querypram use a Java class having fields as userId and pwd

Consume Cookie and JSON with JAX-RS Jersey Service

I am sending these data to Restful Web Service (Jersey) using jQuery code and the method POST:
var dataString = {"id":1,"status":"passed","session":"nothing"};
$.post("https://localhost:8443/pv01/ws/user/cookie", dataString);
And with this data, I am sending a cookie. The data in te cookie come from an external API.
The problem what I am facing is how to receive the cookie value and the dataString together.
Here's my Java code to read a Cookie :
#POST
#Path("cookie")
public String cookie(#CookieParam("L14c") String str) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + str );
return str;
}
And for the data, I can do like this :
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("cookie")
public String cookie(DataString dataString) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + dataString );
return "ok";
}
But when I combine the two methods to accept cookie and the JSON dataString, I got Error 415, Unsupported media type!
I tried to look on HTTP Headers, but I can access only cookies.
The problem is with the jQuery request. It looks like the Content-Type is defaulting to application/x-www-form-urlencoded. You should use a Browser debugger like Firebug. Makes it easier to spot these kind of things.
From what I've tested, it should work with something like
$.ajax({
url: theUrl,
type: "POST",
data: JSON.stringify(dataString),
dataType: "json",
contentType: "application/json",
success: function(response) {
alert(JSON.stringify(response));
}
});

spring requestmapping http error 406 on file extension

I have created this REST mapping so that it can accept filenames at the end of the URI ...
#RequestMapping(value="/effectrequest/{name}/{imagename:[a-zA-Z0-9%\\.]*}",
headers="Accept=*/*", method=RequestMethod.GET,
produces = "application/json")
public #ResponseBody EffectRequest effectRequest(
#PathVariable("name") String name,
#PathVariable("imagename") String imageName)
{
return new EffectRequest(2, "result");
}
Which returns JSON content using MappingJackson2HttpMessageConverter. I make a test jQuery AJAX call to this mapping with ...
var effectName = 'Blur';
var imageName = 'Blah.jpg';
var requestUri = '/effectrequest/' + effectName + '/' + imageName;
alert(requestUri);
$(document).ready(function() {
$.ajax({
url: /*[+ [[${hostname}]] + requestUri +]*/
}).then(function(data) {
$('.effect').append(data.id);
$('.image').append(data.content);
});
});
This generates a URI of http://localhost/effectrequest/Blur/Blah.jpg and in a debugging session the filename is received correctly in the effectRequest() method above. However, the client or jQuery AJAX call receives a HTTP 406 error (Not Acceptable) from the server even with the produces = "application/json" in the RequestMapping.
After much debugging later, I have this narrowed down - when I modify the test javascript code to generate a URI of http://localhost/effectrequest/Blur/Blah.json it works. So either Tomcat or MappingJackson2HttpMessageConverter is causing the HTTP 406 error by looking at the filename extension at the end of the URI and deciding that the JSON content I'm sending back is not a good match.
Is there anyway to override this behaviour without having to encode the . (dot) in the filename?
By default, Spring MVC prefers to use the request's path when it's trying to figure out the media type for a response to a request. This is described in the javadoc for ContentNegotiationConfigurer.favorPathExtension():
Indicate whether the extension of the request path should be used to determine the requested media type with the highest priority.
By default this value is set to true in which case a request for /hotels.pdf will be interpreted as a request for "application/pdf" regardless of the Accept header.
In your case this means that the request for /effectrequest/Blur/Blah.jpg is being interpreted as a request for image/jpeg which leaves MappingJackson2HttpMessageConveter trying to write an image/jpeg response which it is unable to do.
You can easily change this configuration using ContentNegotiationConfigurer accessed by extending WebMvcConfigurerAdapter. For example:
#SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}

How to pass a value of a variable from a java class to the jsp page

I have 2 files named Admin.java and index.jsp.
In Admin.java through a function I retrieve the value of the varible named res. This variable needs to be passed to a JSP page.
The Admin.java is in C:\Users\praveen\workspace\SemanticWeb\src\controller whereas the index.jsp is in C:\Users\praveen\workspace\SemanticWeb\WebContent.
The code of Admin.java is:
public Admin()
{
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
if (action.equals("login"))
{
String userName="";
String password="";
userName = request.getParameter("username");
password = request.getParameter("password");
response.setCharacterEncoding("UTF-8");
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);
request.setAttribute("rest", res);
return;
}
The code of index.jsp is
function login(user, pass)
{
$.ajax({
type:"GET",
url: "Admin?action=login",
dataType: "text",
data: { username: user, password: pass },
success: function(response){
}
within the
function(response)
{
......
}
I need to access the value of res passed by Admin.java. I am not able to get any proper help for my code on the Internet. Please can someone help me with this.
From your code,
request.setAttribute("rest", res);
You shouldn't set it as request attribute. Setting request attributes is only useful if you're forwarding to a JSP file. You need to write it straight to the response yourself. Replace the line by
response.getWriter().write(res);
This way it'll end up in the response body and be available as variable response in your JS function.
See also:
How to update current page by Servlet/Ajax?
Seems like you're doing AJAX, so I'd say your response would need to be encoded in an AJAX-compatible way (JSON, XML, ...).
If you do AJAX-encoding, your function might look like this:
function(response)
{
var toplevel = response.<your_top_level_element>;
}
Edit:
We're using JSON Simple for JSON encoding.
Our Java backend then looks like this (simplified version without error checking):
public String execute()
{
JSONObject jsonResult = new JSONObject();
jsonResult.put( "result", "ok");
return jsonResult.toJSONString();
}
And in the Javascript function:
function(response)
{
var result = response.result; //now yields "ok"
}
If this is an ajax request, you can forward the request into another jsp page rather than return. With this
getServletContext().getRequestDispatcher("/ajax.jsp").forward(request, response);
create the jsp page(ajax.jsp) on your webcontent and add this sample code.
<p>${rest}</p>
<!-- Note: You can actually design your html here.
You can also format this as an xml file and let your js do the work.
//-->
Another way is replace your System.out.println with this
PrintWriter out = response.getWriter();
out.print("The value of res been passed is "+res);
but I guess this is a bad practice. See example here.

Categories