Dynamic URL issue on JSP in data table - java

I am using spring and hibernate.
In JSP page I am using data table in which there are 3 columns ie App, Res, and id. The values of three columns are coming dynamically and these three are link.
For Example : Res is "xyz" and App is "abc" and user clicks on this xyz link then my url would be like /admin/<Res>/<App> so url become /admin/xyz/abc.
In controller, I am taking it as a #PathVariable and #RequestMapping is /admin/{res_name}/{app_name} so Res and App become available in controller.
My Problem :
1) If Res is "xvf\y" and App is "abc" and if user clicks on link then url become /admin/xvf/y/abc so it doesn't match with my controller request mapping. Hence , controller method is not getting called.
2) If Res is "xvf\y" and App is "ab\c" then also issue will occur.
How to handle this. Please help.

it should be URL Encoded so xvf\y is transformed to xvf%5Cy
Use e.g. URLEncoder.encode("xvf\y") (or pass desired encoding as the second param)

Related

Spring boot not saving path variable to database

I currently have a form that allows users to upload data, however, I want to save the path variable to the database for that object.
The thymeleaf form action is as follows.
<form th:action="#{/homepage/{room_id}/saveLayout(room_id=${Room.room_id})}" th:object="${layout}" method="post">
This is the controller that the form corresponds to
#PostMapping("/homepage/{room_id}/saveLayout")
public String saveLayout(#ModelAttribute("layout") Layout layout, #PathVariable(value = "room_id")long room_id) {
layout.setroomid(room_id);
layout.Service.saveLayout(layout);
return "redirect:/homepage";
}
The idea is that when a user sends the form after clicking on say room 2, the URL should be
homepage/2/saveLayout
However, the issue is that the URL does not contain the ID of the room, instead it looks like this
homepage//saveLayout
Which in turn causes spring boot to return an error saying the URL contained malicious content '//'. Even after removing the path variables and hard coding an integer 2 into the setroomid method, the room id does not change in the database. I have another controller which directs the user to the form to input the data, this adds attributes layout and room to the model. There are no red underlines in either of the HTML documents within the thymeleaf code. My setroomID method is
public void setroomid(long room_id){
roomid = roomid;
}
I should also make it clear that the actual data uploading works, however the roomID for a layout remains unchanged. If anyone is able to recommend any changes to make this work, or suggest an alternate way of binding a roomID to a layout in the database then it would be appreciated, thanks.

Javascript changes dissapear when going back from servlet to JSP

Good evening,
I have a form on a JSP page that's connected to a servlet, that form has some dynamic parts using JavaScript like adding a row to a table or adding a text field based on the selected option on a select element, Actually my problem is that I have some validations on the servlet-side, so when I go to servlet to check the (National ID) for example if there's any problem or any violations to my validation I force to get back to the form using :
if (dbm.MatchIdNumber(Candidate.getRegNumber(), Candidate.getNationalID()) == false) {
out.println("<script>\n"
+ " alert('Your National Id does not match your Registration Number');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
What happens is when I get back to the form I lose all the JavaScript changes, Which's very important.
I've been reading for a while that using ajax might be the optimal solution for me, but here is my questions:
Is there a way to call a java method from JavaScript or JQuery before getting to servlet without using ajax !?!
Is there a way to get back from the servlet to the jsp page with the ability to keep all the JavaScript Chages !?
If not !!, How to use ajax in my case ?!
Thank you so much
No. JavaScript runs on the user's browser and your Java code runs on your webserver, so basically the only way to communicate between the two is via HTTP requests.
If you don't want to use AJAX, you could provide all of the relevant info when you submit the form to the server for validation. You could pass all the info you need to re-generate the form as it was, like which new fields are there and such
First, you'll need to add a new webservice to your Java webapp which performs validation. To achieve this, you could either add additional logic to your servlet (so that it looks for a request parameter like "doValidation=1" and performs validation if it's there) or write a different servlet that handles validation itself. You'll need to decide the format it should expect the form data in and how it should return the validation information.
On your frontend page, you'll need to modify the behavior of the form so that, when you need to do validation, it performs a request to this webservice and passes along the form data. I would probably do this with jQuery and do something like jQuery.ajax(...) and pass the contents of the form as a JSON object.
When your validation servlet returns data from the ajax call, you'll need to update the form based on the data it provides. If I was doing it, I would probably just have the servlet return a JSON object like {errorMessage:"..."} and I would use jQuery to add an element to the form containing the text of the validation error when it occurs. If the servlet returns an empty string or JSON object or something, I would consider it a validation success.

Java/Struts2: How to get action name from current url

I am having a active page with its url like http://localhost:8085/projectName/namespace1/namespace2/namespace3/sell.action?id=22
Now i want get the action name(4th name after the sign /) i.e setuppageforwared.
How to achieve this ? Please help me to know because i read many books of struts2 i could not find anything which solve this problem.
Before i was using PHP framework codeigniter which easily solve this type of problem using uri segment features(click here) . I am aspecting the same here in Struts2.
Given Url String: http://localhost:8085/projectName/namespace1/namespace2/namespace3/sell.action?id=22
Expected Output: sell
Did you look for ActionContext#getName() ?
Edit :
Since you were not clear about it, I suppose you want to get the name of the action being executed from inside the action. So, in your action execute method, you'll have something like this :
String actionName = ActionContext.getContext().getName();

how to forward back to JSP page without losing the data entered in fields?

I have a simple MVC-based JSP application. Something like:
*.jsp -> ControllerServlet -> *Command.java -> *Service.java -> *DAO.java -> Oracle db
A typical link in the application looks like this:
myapp/controller?cmd=ShowEditUser&userid=55
Which causes ShowEditUserCommand.java execute() method to run and will forward to editUser.jsp
In editUser.jsp, they fill in the fields, then click Save which posts to myapp/controller?cmd=ModifyUser which runs ModifyUserCommand.java execute() method which modifies the user data and forwards to viewUser.jsp.
Everything works fine.
The problem is, in ModifyUserCommand.execute() I'm checking to see if the username is unique. If they try to enter a username that already exists, I set an error value to true and errorMessage value to Already in use.
Then because of the error I forward to the original editUser.jsp (not viewUser.jsp) and the error is displayed above the form.
MY PROBLEM IS (finally! ;) -- when the user is returned to editUser.jsp with the error message displayed, the data they entered in the fields is all blanked out. How can I set it so whatever they entered in the fields is still in place?
Any suggestions or advice are greatly appreciated!
Rob
Simplest way would be to pass the form fields back to your editUser.jsp in your forward action in ModifyUserCommand.execute(). You can do that with individual parameters i.e.
editUser.jsp?field1=1&field2=2
Alternatively, you could pass data with other methods - i.e. encoded JSON.
You can then process your fields in your editUser.jsp via the page's request object and set your form field values accordingly.
There may be other ways to do this depending on what underlying framework (if any) you are using. But this is a basic way of approaching it.

wicket: mapping different paths to the same class on request to generate different content in markup

I developed a shopsystem. there is a product page, which lists the available items filtered by some select menus. there is also one item detail page to view some content about each product. the content of that page will be loaded out of an xml property file. if one would click the link in the listview of an item, to view some details, an item specific GET parameter is set. with the parameters value, i can dynamically load the content for that specific item from my properties, by altering the loaded keys name.
so far so good, but not really good. so much to the backgroud. lets get to some details.
most of all, this is some SEO motivated stuff. so far there is also a problem with the pageinstance Id in the url for statefull pages, not only because of the nonstable url, also because wicket is doing 302 redirects to manipulate the url. maybe I will remove the statefull components of the item detailpage to solve that problem.
so now there are some QR-code on the products being sold, that contain a link to my detail page. these links are not designed by myself and as you can imagine, they look a whole lot of different like the actual url. lets say the QR-code url path would be "/shop/item1" where item1 would be the product name. my page class would be ItemDetailPage .
I wrote an IRequestMapper that I am mounting in my WebApplication#init() that is resolving the incoming requests URL and checks wether it needs to be resolved by this IRequestMapper. If so, I build my page with PageProvider and return a requesthandler for it.
public IRequestHandler mapRequest(Request request) {
if(compatibilityScore>0) {
PageProvider provider = new PageProvider(ItemDetailPage.class, new ItemIDUrlParam(request.getUrl().getPath().split("/")[1]));
provider.setPageSource(Application.get().getMapperContext());
return new RenderPageRequestHandler(provider);
}
return null;
}
So as you can see, I build up a parameter that my detailpage can handle. But the resulting URL is not very nice. I'd like to keep the original url by mapping the bookmarkable content to it, without any redirect.
My first thought was to implement an URLCodingStrategy to rebuild the URL with its parameters in the form of a path. I think the HybridUrlCodingStrategy is doing something like that.
After resolving the URL path "/shop/item1/" with the IRequestMapper it would look like "/shop/item?1?id=item1" where the first parameter off course is the wicket pageinstance Id, which will most likely be removed as I will rebuild the detail page to be stateless :(
after applying an HybridURLCodingStrategy it might look like "/shop/item/1/id/item1" or "/shop/item/id/item1" without pageinstance Id. another Idea would be to remove the second path part and the parameter name and only use the parameters value so the url would look like "/shop/item1" which is then the same url as it was in the request.
Do you guys have any experience with that or any smart ideas?
The rewuirements are
Having one fix URL for each product the SE bot can index
no parameters
stateless and bookmarkable
no 302 redirects in any way.
the identity of the requested item must be available for the detailpage
with kind regards from germany
Marcel
As Bert stated, your use case should be covered with normal page mounting, see also the MountedMapper wiki page, for your case a concrete example:
mountPage("/shop/${id}", ShopDetailPage.class);
Given that "item1" is the ID of the item (which is not very clear to me), you can retrieve it now as the named page parameter id in Wicket. Another example often seen in SEO links, containing both the unique ID and the (non-unique, changing) title:
mountPage("/shop/${id}/${title}", ShopDetailPage.class);
Regarding the page instance ID, there are some ways to get rid of it, perhaps the best way is to make the page stateless as you said, another easy way is to configure IRequestCycleSettings.RenderStrategy.ONE_PASS_RENDER as the render strategy (see API doc for consequences).

Categories