send String from java to js, using current project - javascript

Before ask this question, I have already read the forum and tried a lot of from forum suggestions. I do not know , maybe i do not clearly understand or maybe the reason that i apply to my current project, however answer on the forum is not working in my project
Java:
#RequestMapping(value = "/warehouseWhisky", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView viewAllWhiskyInWarehouse() {
Iterable<WhiskyDTO> list = whiskyService.seeAllWhisky();
String email = receiveEmailFromSecurity.getEmail();
System.out.println(email);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("viewAvailableWhisky", list);
modelAndView.addObject("email", email);
modelAndView.setViewName("whisky");
return modelAndView;
}
This code correct, I recive in HTML string:
<input type="button" id="someThingNew" th:value="${email}"/>
But I didn't recieve this parameters in js:
var nameUser = $("#someThingNew").val();
console.log(nameUser);

I think the problem is caused because of the special characters in email like '#'. In other word you cannot send email address using #PathVariable (with ordinary routing configuration). Instead of #PathVariable, you can send email using #RequestParam and send it as a query parameter.

I think the first method is probably fine - just you are calling the wrong URL. What is your server mapping? I would expect something like -
http://localhost:8080/warname/warehouseWhisky/test#test.com
The issue with the second one is that its expecting similar to the following - which is why you are getting a 500
#RequestMapping(value = "/warehouseWhisky/{email}")

Related

How can I access parameters from a POST (or other HTTP) request in a C# server?

I'm building a Reactjs application using ASP.Net Core, and I'm completely new to this. I have a JS component that (to the best of my knowledge) is making an appropriate fetch request (POST) to a C# server controller. The server is definitively receiving the request. However, I have absolutely no idea how to access the parameters of the request (which I am passing through the body).
I've tried using [FromBody] to access the body directly. I've also tried to utilize the Request.Body, the Request.Form, the Request.Query, the Request.Params, etc. I've attempted to follow the guidelines I've found online that seem to try to address my problem. Several of them flat-out haven't worked. Most of them are using key words, classes, etc. that are not available to me in my current libraries, and they don't list the appropriate libraries. For all I know, I've stumbled across the right answer already. But for someone like me with a highly logical mind but also pretty much zero experience in the field, I can't wrap my mind around any of it.
My POST request using fetch in JavaScript:
fetch('api/Database/PushStatus',
{
method: 'post',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify({ order: this.state.orderNum, status: this.state.newStatus })
}
).then(response => {
response.json().then(data => {
this.setState({ reqCheck: "" + response, didPush: false });
})
}).catch(err => {
this.setState({ reqCheck: "Failure! (js)", didPush: false })
});
And my request handling on my C# server:
[Route("api/[controller]/[action]")]
public class DatabaseController : Controller
{
string conStri = "Data Source=ADM293\\MSSQLSERVER01;Initial Catalog=testDB;User ID=sa;Password=password.1";
SqlConnection cnct = null;
[HttpPost]
public void PushStatus(string order, string status)
{
cnct = new SqlConnection(conStri);
SqlCommand command = new SqlCommand("insert into testTable values ('" + order + "', '" + status + "');", cnct);
using (cnct)
{
cnct.Open();
int result = command.ExecuteNonQuery();
cnct.Close();
}
}
}
I would like my server to be updated with the contents of this.state.orderNum and this.state.newStatus.
Instead, my server is updated with empty string values (which makes perfect sense).
You can create a class that represents the request:
public class PushStatusRequest
{
public string Order { get; set; }
public string Status { get; set; }
}
And use it like this:
[HttpPost]
public void PushStatus([FromBody] PushStatusRequest request){
//request.Status
//request.Order
}
#Anteo is right. But I would like to add some explanation.
You have faced two different ways to pass params to a controller.
You try to use a body (setting body in request) as an entrance and the query (in the controller) as an output.
Well, body is one type and it requires to be some model on a Controller side. Use [FromBody] to automatically retrieve your data from a request into a model. Create this model as a separate class following the same naming politics (ignoring case).
Then, a query string is what you are using at the controller side. On a request side, it follows the URL like this: https://host:port/route/to/then/query/params. So, if I am not mistaking a base URL is a part https://host:port. Everything is left is a query string. A part of that is being mapped to the route to your controller's action. Anything left is interpreted as useful info and mapped to an action params.
So, here is the moment for you to choose (depending on the length of your orderNum and newStatus) which approach to use. I would recommend using the body as it is more data than routing.
Also, If you inherit [ControllerBase][1], then you can use Request property in action to access the request itself. But be careful here.
P.S. I would recommend you to read more about requests, things like form data, body, queries, etc.
If have any further questions feel free to ask.
By default, capitalization changes between JavaScript and C#. So, you probably just need to change your method signature:
public void PushStatus(string Order, string Status)
That said, having the class the way #Anteo suggested is usually better. Also, I assume you put SqlConnection just for clarity. You shouldn't do it in the controller

Passing multiple parameters from angular to rest service

I am trying to pass the data to my rest services through $http.get() using URL.There are 10-12 parameters which I need to pass.
Angular script.js
$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
'&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
'&filter4='$scope.filter4)
The scope variables would come as undefined sometimes.But I guess that will not be a problem.I checked the console, the URL is getting formed correctly with all 12-13 parameters.
Now I am trying to get this in rest service using #QueryParam like below -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(#QueryParam("filter1") final String filter1,
#QueryParam("filter2") final String filter2,
#QueryParam("filter3") final String filter3){
}
The problem is that the #QueryParam is working for 2 parameters but when I am increasing the number of parameters, it is failing. As per the browser console, I am getting 404 error.
Is there any limitation to the number of parameters we can pass? I need to pass 12-13 parameters.How can I achieve this?
Update -
I was able to resolve my issue . I was using Date datatype in #QueryParam because of which it was throwing 404 error . Changed it to String and it worked . Did not know that we cannot use Date in QueryParam .
Apologies for not putting the detailed problem .
If you want to do it in the proper RESTful way then you can try like this, I have given it for couple of variables, but you can do for any.
#RequestMapping(path = "/rest/test/getAllData/{filter1}/{filter2}", method = RequestMethod.GET)
public Data getAllData(#PathVariable String filter1, #PathVariable String filter2) {
// code here
}
You can also achieve it using RequestParam, an example below, ensure your parameters matches
#RequestMapping(path = "/rest/test/getAllData", method = RequestMethod.GET)
public Data getAllData(#RequestParam String filter1, #RequestParam String filter2) {
// code here
}
If you still have a complicated structure then send it as a POST with the JSON data in the request body
#RequestMapping(path = "/rest/test/getAllData", method = RequestMethod.POST, consumes = "application/json")
public Book getAllData(#RequestBody ObjectKey objectKey) {
// code here
}
For passing more number of parameters, you can use Rest parameter. It is used to access indefinite number of arguments passed to a function.
Syntax :
function add (...numbers){}
const params = new HttpParams()
.set('paramName1', value1)
.set('paramNmae2', value2);
return this.httpClient.get<IMyObject[]>(this.myUrl, {params} ).pipe(
tap(data=>console.log('ALL:'+JSON.stringify(data))),
catchError(this.handleError));

JSF : How to change value of jsf input before sending request (to encrypt password)

I'm trying to implement the really good answer of FriendlyCryptoNeighbor here and I'm quite new to all jsf stuff.
In order to encrypt the password (like RSA_With_Public_Key(SHA256(password))) client side, I would like to override the <h:input to call an encryption function in javascript. But I can't manage to find a way to do this.
The problem is that I have a bean bound to the input value ... In a RESTful server it will be easy to encrypt and make the request from javascript but there, I'm not sure how all of this works.
-- UPDATE 1
For the moment, I execute a javascript script on click on the commandButton, which update a hidden field where my bean is bound.
I am not sure why you want to do it on client and not in the bean itself..
But in jsf you can use Converter to convert you input.. Look at this example.
It is very easy to do
http://www.mkyong.com/jsf2/custom-converter-in-jsf-2-0/
I took the important things here..
First thing is the page..
<h:inputText id="bookmarkURL" value="#{user.bookmarkURL}"
size="20" required="true" label="Bookmark URL">
<f:converter converterId="com.mkyong.URLConverter" />
</h:inputText>
Than you need to build the converter
#FacesConverter("com.mkyong.URLConverter")
public class URLConverter implements Converter{
#Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
String HTTP = "http://";
StringBuilder url = new StringBuilder();
//if not start with http://, then add it
if(!value.startsWith(HTTP, 0)){
url.append(HTTP);
}
url.append(value);
//use Apache common URL validator to validate URL
UrlValidator urlValidator = new UrlValidator();
//if URL is invalid
if(!urlValidator.isValid(url.toString())){
FacesMessage msg =
new FacesMessage("URL Conversion error.",
"Invalid URL format.");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ConverterException(msg);
}
URLBookmark urlBookmark = new URLBookmark(url.toString());
return urlBookmark;
}
#Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
return value.toString();
}
}
Hope that helps..

WebApi Method with single value and AngularJs $http json handling

I am encountering an issue and I ran out of ideas, I need some guidance towards the origin and/or the solution:
Server Side
I added the standard Microsoft Web Api Controller class "ValuesController" which looks like this:
public class ValuesController : ApiController
{
public string Get(int id){ return "value"; }
...
Client Side
In my AngularJS Controller function I have a simple get
$http({method:'GET',url: '/api/values/1'}).success(function(data){
$scope.value =data;
})
The HTML looks like this:
<input type="text" ng-model="value" />
The weird thing(the issue) is that I get: "value" in my input instead of just value (no quotes).
To avoid misunderstandings, I am getting this:
Instead of this:
And of course the questions are: why?? and how do I fix it*?
*hopefully the answer will not be returning an object instead of a simple string :)
I have the impression that this is due to security vulnerabilities in the JSON format. In the documentation of the $http service there is section called JSON Vulnerability Protection that suggests that Angular takes a few precautions to avoid an attack.
They recommend the reading of the following article: Anatomy of a Subtle JSON Vulnerability which as far as I can see delves into a case similar to yours.
Bottom line, I think you will have to return a full JSON object and not just a string. An alternative is to make sure you are getting a JSON object, by doing
$scope.value = JSON.parse(value)
The preferred (Angular provided solution) is
$scope.value = angular.fromJson(data);

BreezeJS Selecting ComplexType properties

I am running into an issue with Breeze and Durandal which is leading me to believe it may be a bug with Breeze or that I don't know the right syntax.
Here is my model (given that Address is just a simple ComplexType class)
public class Person {
public int Id {get;set;}
public string Name {get;set;}
public Address MyAddress {get;set;}
}
And on the front-end with Breeze JS, I have the following:
EntityQuery.from('Person').select('id,name').orderBy('id');
The above line works perfect, but if I have:
EntityQuery.from('Person').select('id,name,myAddress').orderBy('id');
I get the error message that Error retreiving data. deferred is not defined
It looks like as though, you can't have the ComplexType property in the Select statement. Anyone else is running into this issue? Thanks for your help in advance.
Edit: May 8, 2013 - This is now fixed in v 1.3.3
I've just confirmed that this is a bug - Your query syntax is correct ( you do not need an expand for complex types). I will try to get this corrected in the next release and will post back here when it gets in. And thanks for the repro :)

Categories

Resources