How the best way to handle query strings in Java JSP?
The method request.getQueryString() returns only a strings, how can I get the value of a specific string? Should I parse that string?
thanks
request.getParameter("param-name");
if query string is like
id=12&name=abc
to get name you can do this
request.getParameter("name");
Related
I have this column in a MySQL table which has a JSON string and I'm trying to pull records using regex.
For example, the column 'paylod' (datatype long text) holds this value
{
"type":"assignment",
"location":"12345"
}
I'm using RLIKE to fetch records based on location.
select * from table where payload RLIKE '"location":"[[:<:]]12345[[:>:]]"';
When using this query in java, I'm using prepared statement.
String pattern = "\"location\":\"[[:<:]]12345[[:>:]]\""
And when I use preparedStatement.setString(payload, pattern), I'm not getting any results back. But when I execute the query in workbench, I see the rows fetched.
I'm guessing it's because I'm using setString, it is wrapping pattern with double quotes and MySQL is not able to parse it.
So is there a way forward? My requirement is to get records based on key-value pair in the JSOn payload column.
Alright, adding escape character in string helped.
String pattern = "'\"location'\":'\"[[:<:]]12345[[:>:]]'\"";
String patternValue = pattern.replaceAll("'","\\\\");
So the string becomes \"location\":\"[[:<:]]12345[[:>:]]\" where \ serves as escape character for " in mysql, when string is wrapped inside ""
I have a stored function that takes below arguments in database.
CREATE OR REPLACE FUNCTION
public.abc(
id integer,
title text,
description text,
valid_until_date timestamp with time zone,
user_is_ext boolean,
remarks text)
{
//statements
}
I need to invoke this stored function. I am able to invoke directly in database using below query:
select "abc" (0,'title','description','2010-01-01 00:00:00+01',false,'text')
However i am not able to invoke using JDBC template in my SpringBoot application.
String sql="select \"abc\" (?,?,?,?,?,?)";
List<Integer> ids=jdbcTemplate.query(sql,new Object[]{id,myObj.getTitle(), myObj.getDescription(), myObj.getValidDate(), myObj.isUserExt(), ,myObj.getRemarks()},new BeanPropertyRowMapper(Integer.class));
Can someone help me to figure out what is it that I am missing?
i get "The column index is out of range:" error.
I tried using "update" instead of "query"
int ind=jdbcTemplate.update(sql, id,myObj.getTitle(), myObj.getDescription(), myObj.getValidUntilDate(), myObj.isUserExt(), myObj.getRemarks());
then i get following error
""2017-07-10 14:51:16 [http-bio-8080-exec-60] ERROR c.s.k.l.exceptions.ExceptionHandlers --- A result was returned when none was expected. –
tried using SimpleJDBC call as mentioned on the comment. getting below error while passing timestamp as a parameter in SQLParameter object
""2017-07-10 16:18:16 [http-bio-8080-exec-97] ERROR c.s.k.l.exceptions.ExceptionHandlers --- Bad value for type timestamp : org.springframework.jdbc.core.SqlParameter#3a4cbd06
Finally i resolved it!!
In my case I'm trying to invoke a stored function that returns an integer value. please find the code snippet below.
String sql="select * from \"stored_function_name\" (?,?,?,?,?,?,?,?,?)";
Integer result=jdbcTemplate.queryForObject(sql,Integer.class, new Object[] {all input parameters separated by coma});
Similarly we can use other variants of query.
Please make sure the parameters that you pass to function should have same datatype as in postgres database. If its a timestamp in db and you have date as string, you can convert it to timestamp using below code
Timestamp.valueOf("date_string in yyyy-mm-dd hh:mm:ss format")
Thank you everyone!!
I have to make a http request with encrypted query param from one end to another. Say for an example,
String queryParam = "bookName=WingsOfFire&author=AbdulKalam";
String encryptedQueryParam = encrypt(queryParam, encryptionKey);
The final url would be like
domain_name?encryptedQueryParam
On the other end, I would decrypt the query params and obtain the query String. Like
String decryptParam = decrypt(encryptedQueryParam, decryptKey);
Here I'm manually de-serialising my query params at the other end instead of request.getPameter("value").
Is there any other option to handle it in a better way? Any help would be greatly appreciated :-)
I am having CLOB column in Oracle Data Base , I want to insert String .
It works if I use setCharacterStream, but how to insert String by setBytes am getting exception.
Please help me.
String s = "Hello How are you Data for CLOB column";
ps.setCharacterStream(1, new StringReader(s), s.length());
ps.setByte(1,Byte.parseByte(s));
Exception Trace :
java.lang.NumberFormatException: For input string: "Hello How are you Data for CLOB column"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Byte.parseByte(Byte.java:151)
at java.lang.Byte.parseByte(Byte.java:108)
at colb.test.InertClob.main(InertClob.java:24)
Here are two good examples (with sample code, for select and insert):
Handling CLOBS made easy:
http://rocksolutions.wordpress.com/2010/06/07/handling-clobs-made-easy-with-oracle-jdbc-10g/
Adding large object type to databaase
http://docs.oracle.com/javase/tutorial/jdbc/basics/blob.html
please refer to the Java API DOC
Parses the string argument as a signed decimal byte. The characters in the string must all be decimal digits,
You should:
Turn the String to a byte array by calling s.getBytes() for example or any other.
Call setBytes method, not setByte
When retrieving from the database, don't forget how you got the bytes, in order to restore the String properly.
In HttpServletRequest, getParameterMap returns a Map of all query string parameters and post data parameters.
Is there a way to get a Map of ONLY query string parameters? I'm trying to avoid using getQueryString and parsing out the values.
You can use request.getQueryString(),if the query string is like
username=james&password=pwd
To get name you can do this
request.getParameter("username");
Contrary to what cularis said there can be both in the parameter map.
The best way I see is to proxy the parameterMap and for each parameter retrieval check if queryString contains "&?<parameterName>=".
Note that parameterName needs to be URL encoded before this check can be made, as Qerub pointed out.
That saves you the parsing and still gives you only URL parameters.
The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.
The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":
GET /persons?age=42
The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":
PUT /persons?age=42
hair=grey
So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2 will return
password : [pwd1, pwd2] (length = 2)
username : [james, smith] (length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
Java 8
return Collections.list(httpServletRequest.getParameterNames())
.stream()
.collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));
I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending
http://mycompany.com/myapp/myservlet?first=11&second=22
say:
http://mycompany.com/myapp/myservlet/11/22