Parse request URL in JSTL - regex

I want to display a specific message based on the URL request on a JSP.
the request URL can be:
/app/cars/{id}
OR
/app/people/{id}
On my messages.properties I've got:
events.action.cars=My car {0} event
events.action.people=My person {1} event
Finally, on my JSP page I want to have the following code:
<spring:message code="events.${element.cause}.${?????}"
arguments="${element.param['0']},${element.param['1']}"/>
I need help figuring out which expression I could use to parse the request URL and obtain the word before the ID.

You can access the request URI in JSTL (actually: EL) as follows:
${pageContext.request.requestURI}
(which thus returns HttpServletRequest#getRequestURI())
Then, to determine it, you'll have to play a bit round with JSTL functions taglib. It offers several string manipulation methods like split(), indexOf(), substringAfter(), etc. No, no one supports regex. Just parse it.
Kickoff example:
<c:set var="pathinfo" value="${fn:split(pageContext.request.requestURI, '/')}" />
<c:set var="id" value="${pathinfo[pathinfo.length - 1]}" />
And use it as ${id}.

/app/(cars|people)/([^/]*)$
will put cars or people in backreference \1, depending on the match, and whatever is left right of the last slash in backreference \2.

My solution so far is to have a RequestUtils class that match the regex ".?/jsp/(\w+)/..jsp" and return the group(1).
in my Jsp I got:
<% request.setAttribute("entity", RequestUtils.getEntityURI(request)); %>
<spring:message code="events.${element.cause}.${entity}"
arguments="${element.param['0']},${element.param['1']}"/>
this of course did the trick. But still it would be better not to have any Java code within the JSP.

If I understand you correctly, I think you need to do something like this:
#RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(#PathVariable String ownerId, Model model) {
model.addAttribute("ownerId", ownerId);
return "myview";
}
As you can see, here the ownerId is read from the URL by Spring MVC. After that, you simply put the variable in the Model map so you can use it in your JSP.

Related

Regex Custom Redirect in Blogger for every archive.html

I need to create a regex Custom Redirect in Blogger. The purpose is to redirect all HTML archives to somewhere else.
Currently I'm using the following in Settings / Search preferences / Custom Redirects:
From:/2018_11_21_archive.html
To:/p/somewhere_else.html
Permanent:Yes
The problem is that this method requires to add every date, and that's not acceptable.
/2016_10_21_archive.html
/2016_10_22_archive.html
/2016_10_23_archive.html
/2017_07_10_archive.html
/2017_07_10_archive.html
/2017_07_10_archive.html
/2018_11_21_archive.html
/2019_11_21_archive.html
...
So far I've tried this regex with no success:
From:/2018_(.*)
To:/p/somewhere_else.html
Permanent:Yes
Blogger custom Redirects does not support regex.
But I have a solution for you, use this code, and put it after <head>
<b:if cond='data:view.isArchive and data:view.url contains "_archive"'>
<b:with value='"https://www.example.com/p/somewhere_else.html"' var='destination'>
<script>window.location.replace("<data:destination/>")</script>
<noscript><meta expr:content='"0; URL=" + data:destination' http-equiv='refresh'/></noscript>
</b:with>
</b:if>
You have to escape the "/" character! Just insert a "\" before.
This line must be like this:
From:\/2018_.*
But be aware that this way only /2018_11_21_archive.html will match.
If you need ALL dates as you mentioned, I recommend this regex below:
\/([12]\d{3}_(0[1-9]|1[0-2])_(0[1-9]|[12]\d|3[01]))_archive\.html

How to replace all anchor tags with a different anchor using regex in ColdFusion

I found a similar question here: Wrap URL within a string with a href tags using Coldfusion
But what I want to do is replace tags with a slightly modified version AFTER the user has submitted it to the server. So here is some typical HTML text that the user will submit to the server:
<p>Terminator Genisys is an upcoming 2015 American science fiction action film directed by Alan Taylor. You can find out more by clicking here</p>
What I want to do is replace the <a href=""> part with a new version which would be like this:
...
clicking here
So I'm just adding the text rel="nofollow noreferrer" to the tag.
I must match anchor tags that contain a href attribute with a URL, not just the URL string itself, because sometimes a user could just do this:
<p>Terminator Genisys is an upcoming 2015 American science fiction action film directed by Alan Taylor. You can find out more by http://www.imdb.com</p>
In which case I still only want to replace the tag. I don't want to touch the actual anchor text used even though it is a URL.
So how could I rewrite this Regex
#REReplaceNoCase(myStr, "(\bhttp://[a-z0-9\.\-_:~###%&/?+=]+)", "\1", "all")#
the other way round, where its selecting tags and replacing them with my modified text?
If you're willing, this is a really easy task for jQuery (client-side)
JSFiddle: http://jsfiddle.net/mz1rwo0u/
$(document).ready(function () {
$("a").each(function(e) {
if ($(this).attr('href').match(/^https?:\/\/(www\.)?imdb\.com/i)) {
$(this).attr('rel','nofollow noreferrer');
}});
});
(If you right click any of the imdb links and Inspect Element, you'll see the rel attribute is added to the imdb links. Note that View Source won't reflect the changes, but Inspect Element is the important part.)
If you want to effect every a link, you can do this.
$(document).ready(function () {
$("a").each(function(e) {
$(this).attr('rel','nofollow noreferrer');
});
});
Finally, you can also use a selector to narrow it down, you might have the content loading into a dom element with the id contentSection. You can do...
$(document).ready(function () {
$("#contentSection a").each(function(e) {
if ($(this).attr('href').match(/^https?:\/\/(www\.)?imdb\.com/i)) {
$(this).attr('rel','nofollow noreferrer');
}});
});
It's a bit tougher to reliably parse this in cold fusion without the possibility of accidentally adding it twice (without invoking a tool like jSoup) but the jQuery version is client-side and works by obtaining data from the DOM rather than trying to hot-wire into it (a jSoup implementation works similarly, creating a DOM-like structure you can work with).
When talking about client-side vs server-side, you have to consider the mythical user who doesn't have javascript enabled (or who turns it off with malicious intent). If this functionality is not mission-critical. I'd use JQuery to do it. I've used similar functionality to pop an alert box when the user clicks an outside link on one of my sites.
Here's a jSoup implementation, quick and dirty. jSoup is great for how it selects similarly to jQuery.
<cfscript>
jsoup = CreateObject("java", "org.jsoup.Jsoup");
HTMLDocument = jsoup.parse("<A href='http://imdb.com'>test</a> - <A href='http://google.com'>google</a>");
As = htmldocument.select("a");
for (link in As) {
if (reFindnoCase("^https?:\/\/(www\.)?imdb\.com",link.attr("href"))) {
link.attr("rel","nofollow noreferrer");
}
}
writeOutput(htmldocument);
</cfscript>

JavaScript Regx to remove certain string if a pattern is found

Lets say i have
input string as
<div id="infoLangIcon"></div>ARA, DAN, ENGLISHinGERMAN, FRA<div id="infoPipe"></div><div id="infoRating0"></div><div id="infoPipe"></div><div id="infoMonoIcon"></div>
so i want to check if inforating is 0 and then remove the div and previous div also. The output is
<div id="infoLangIcon"></div>ARA, DAN, ENGLISHinGERMAN, FRA</div><div id="infoPipe"></div><div id="infoMonoIcon"></div
Regex is not your best option here. It is not reliable when it comes to HTML.
I suggest you use DOM functions to do this (I gave you a Javascript example, you have not provided a language to be used). If I understood correctly, if there is an element with the ID of infoRating0, you want to remove it and its previous sibling. This little snippet should do that:
if (document.getElementById('infoRating0')) {
var rating0=document.getElementById('infoRating0'),
rParent=rating0.parentNode;
rParent.removeChild(rating0.previousSibling);
rParent.removeChild(rating0);
}
Also, your HTML is invalid. You can only use an ID once in your HTML. You have two divs with the same ID (infoPipe) which you should REALLY fix. Use classes instead.
jsFiddle Demo

django 'urlize' strings form text just like twitter

heyy there
i want to parse a text,let's name it 'post', and 'urlize' some strings if they contain a particular character, in a particular position.
my 'pseudocode' trial would look like that:
def urlize(post)
for string in post
if string icontains ('#')
url=(r'^searchn/$',
searchn,
name='news_searchn'),
then apply url to the string
return urlize(post)
i want the function to return to me the post with the urlized strings, where necessary (just like twitter does).
i don't understand: how can i parse a text, and search for certain strings?
is there ok to make a function especially for 'urlizing' some strings? The function should return the entire post, no matter if it has such kind of strings.
is there another way Django offers?
Thank you
First, I guess you mostly need this function in templates (you want to present the post "urlized").
There's the built-in template tag urlize, which is used like
{{ value|urlize }}
which takes a string value and returns it with links.
If you want to customize the logic, you can create your own template tag.
EDIT:
To find the # words you can use a simple regex search:
import re
a = "hello #world. foo #bar! #foo_bar"
re.findall("#(\w+)",a)
>> ['world', 'bar', 'foo_bar']

Replacing a substring using regular expressions

I want to add a call to a onclick event in any href that includes a mailto: tag.
For instance, I want to take any instance of:
<a href="mailto:user#domain.com">
And change it into:
<a href="mailto:user#domain.com" onclick="return function();">
The problem that I'm having is that the value of the mailto string is not consistent.
I need to say something like replace all instances of the '>' character with 'onclick="return function();">' in strings that match '<a href="mailto:*">' .
I am doing this in ColdFusion using the REreplacenocase() function but general RegEx suggestions are welcome.
The following will add your onclick to all mailto links contained withing a string str:
REReplaceNoCase(
str,
"(<a[^>]*href=""mailto:[^""]*""[^>]*)>",
"\1 onclick=""return function();"">",
"all"
)
What this regular expression will do is find any <a ...> tag that looks like it's an email link (ie. has an href attribute using the mailto protocol), and add the onclick attribute to it. Everything up to the end of the tag will be stored into the first backreferrence (referred to by \1 in the replacement string) so that any other attributes in the <a> will be preserved.
If the only purpose of this is to add a JavaScript event handler, I don't think Regex is the best choice. If you use JavaScript to wire up your JavaScript events, you'll get more graceful degradation if JS is not available (e.g. nothing will happen, instead of having onclick cruft scattered throughout your markup).
Plus, using the DOM eliminates the possibility of missing matches or false positives that can occur from a Regex that doesn't perfectly anticipate every possible markup formation:
function myClickHandler() {
//do stuff
return false;
}
var links = document.getElementsByTagName('a');
for(var link in links) {
if(link.href.indexOf('mailto:') == 0) {
link.onclick = myClickHandler;
}
}
Why wouldn't you do this on the frontend with a library like jQuery?
$(function(){
$("a[href^=mailto]").click(function(){
// place the code you want to execute here
})
});