struts2 drop down - struts2

I need to create a drop down menu in struts2 from List. How can I create an action class so that when a .jsp page is loaded, it populates the list first?
i found this link http://www.mkyong.com/struts2/struts-2-sselect-drop-down-box-example/ , it works too but for it work user must go to http://localhost:8080/Struts2Example/selectAction.action to make it work but what if someone were to directly go to select.jsp.

Since you're using a .jsp, you could load the dropdown with a scriptlet before you render the <s:select> tag.
However, it's better practice to allow the action to perform the loading and hide the .jsp files under /WEB-INF so they're not directly accessible. A common approach to perform this is the Prepare interceptor.
If you've got it in your interceptor stack, it will automatically invoke any method with the following name in your action before invoking the requested method:
prepare{MethodName}()
prepareDo{MethodName}()
prepare()
That means you can do something like the following in your Action:
public class YourAction extends ActionSupport {
public String prepare(){
// populate your drop down object
}
public String view(){
// forward to your jsp
return SUCCESS;
}
}
Then all you have to do is call your action's view() method and prepare will be called first by Struts.

Related

Umbraco: Check if page is marked as protected and redirect to login

In my DocType i have a property by the name of "membersOnly" (true/false).
When checked, I want to check, if the user is logged in, if not, redirect to login page with a referrer.
But what is the best way to do this - I dont want to have it in my Master template. How can I hook into the request pipeline, check if the "membersOnly" field excist, and if it does, and it is checked, and the user is not logged in, redirect the user?
Any short snippets out there?
Also, I am aware of the built-in Umbraco way of doing this. But for this case, i need it to be just a simple checkbox on the page in the backend - but the functionality that it fires, is basicly the same, as if i used the built-in Umbraco way in the backend.
You can do this using route hijacking then checking authentication through your controllers. However, if all you have to do is check for authentication, it might be a little bit of an overkill to do route hijacking for your doc types.
Essentially, to do route hijacking, you create a controller with the same name as your doctype, so if your doctype is "memberPage", your controller would look like this:
public class MemberPageController : RenderMvcController
{
public ActionResult Index(RenderModel model)
{
return base.Index(model);
}
}
Notice how it must inherit RenderMvcController in order to work.
Before returning the base RenderMvcController method "Index", you can now run code, e.g. to check authentication.
So you could do this:
public ActionResult Index(RenderModel model)
{
if (Members.IsLoggedIn())
{
return base.Index(model);
}
else
{
return Redirect("~/");
}
}
The cleanest way to implement this yourself, would probably be by creating a custom filter derived from Authorization​Filter​Attribute (located in System.​Web.​Http.​Filters).
Having the derived object use the umbracocontext and query the settings based on the current page.
Umbraco does exactly the same for their custom validation, for some inspiration check out MemberAuthorizeAttribute at github

Struts2 - validation failure using xml file causes action class paramters to disappear from resulting jsp

I have a class A :
class A extends ActionSupport{
int someId;
// getters/setters
public String execute(){
setSomeId(2);
return SUCCESS;
}
public String save(){
// something
}
}
In struts.xml, I have configured an action "ViewId" that takes us to the default method execute, where someId is set. Then, we are taken to a jsp page show.jsp where I can access the someId value. In show.jsp, I have to enter an email id and then submit the page. The action that's now called in "Save" that takes us to the save method of the action class. But, I have given some checks in the corresponding validation.xml file A-Save-validation.xml, which will check the email entered for a format. The problem is that if the xml validation fails, we are taken back to show.jsp, but the viewId parameter is now not available. Why is this so ?
The input page should appear similar to the user as before. Only the fields that are now validated should have an error page associated with them. Any workaround for this ?
Like #Umesh said, validation happens on the corresponding interecptor, before the action's method is called.
When validation fails, the action's method is never called and you will be taken to the INPUT result.
In order to achieve what you want you have some options:
Implement the preparable interface in your action
Peform the validation inside your method.
Use s:action in your jsp before the items you want populated to call an action that populates the relevant section
1 is probably the easiest. I like option 3 as well.

Inject javascript on every controller action - asp.net mvc

Whenever we make a call to any action controller whether through a full post back or an ajax call I want to check the view model and depending on some logic inject some javascript to be executed in the browser. The application is mostly already coded and what I am trying to do is to have some generic code which can do the trick. I am wondering what would be the best way to do it.
I am thinking about using action filters and then checking the model and then inject the js if required. But not sure how would that work on events like action executed etc. Any code sample will be helpful.
The other option is to do it on the client side. But again not sure how to properly do it in a generic way.
Look into overriding the base controller's OnActionExecuted event, which should provide you access to the view model after it has been processed by the action. I'm curious though, how exactly are you going to inject a snippet of javascript into an AJAX response, which is typically a simple JSON object?
If all you're really asking is how to inject javascript from the controller, you could put the following in your view:
<script type="text/javascript" defer="defer">
#Html.Raw(ViewBag.StartupScript)
</script>
You could add the above to a specific view, or a layout page. Then, you could do something like this:
public class MyController : Controller
{
public override void OnActionExecuted(...)
{
if (...)
{
ViewBag.StartupScript = "alert('hello world!');";
}
}
}
To inject on postback as well as ajax calls here is how you can do it:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\">\n\t");
sb.Append("alert('Hello Injection');");
sb.Append("</script>\n");
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.Write(sb.ToString());
}
else
{
ViewBag.StartupScript = sb.ToString();
}
}
Probably not the cleanest solution, but works.
filterContext.HttpContext.Response.Write(sb.ToString());
this will override the partial view come from Ajax call, any walk around?

Maintaining values of action variables in between different requests

I am struts2 for developing my application.
Sample code of action class would be
class sampleAction extends Action {
private List<Employee> employee;
public validate(){
--logic for validation
}
public String prepopulate(){
--logic for populating value of employee list
}
--getters and setters
}
Now my problem is on page load i call prepopulate function and populate the value of employee list. After page submit validate method is called and during that if some error happens control redirects to jsp. but this time the value of employee list is empty. I am using this list for autocompleter tag in struts2.
I have never used Struts 2 built-in validation mechanism, as I prefer client-side validation to avoid an extra round trip. This is purely a personal choice and not a standard.
First I will suggest you not to use Action and use ActionSupport: ActionSupport provides a lot of functionality out of the box and you need not to do everything yourself.
I am assuming that you are using defaultStack and if this is the case than it provides out of the box Prepare Interceptor which takes care of preparing any values before the action itself is called.
In your case, validate is called before the execute method, so you never will get a chance to re-fill the values you need in your JSP.
All you need to make sure that you have prepare() method in your action class. Here are more details for this interceptor:
Prepare Interceptor
FAQ: How do we repopulate controls when validation fails

Can MVC routing be used to create a dynamic content management system with dynamic pages stored in db rather than in view pages

Are there any good examples of mvc routing wherein every 404 page not found request is routed to a standard view in MVC which basically pulls the content from the database.
Just add this route to the bottom of your RouteTable:
routes.MapRoute("DynamicPages", "{*page}", new { Controller = "DynamicPages", Action = "Show", Page = String.Empty });
And create a controller for displaying dynamic pages from db:
public class DynamicPagesController : Controller
{
public ActionResult Show(string page)
{
var pageContent = DB.GetContentForPage(page);
return Content(pageContent);
}
}
Here's one way to do this: In your global.asax file in Application_Start, you need to set the default controller factory. Override it with an instance of your own factory.
void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
}
MyControllerFactory should inherit from DefaultControllerFactory and when selecting the controller to use, look in your database for the appropriate page you want to display. If the page exists, select the appropriate controller and override the action in the requestContext.RouteData collection to point at the appropriate action for displaying dynamic pages.
If the requested page doesn't exist, pass back a call to the base method and let it do what it would normally do.
There are other ways you could do it, but this one should work and allows you to intercept the request before you hit the 404 page.
modify the web.config file, you may Reference to this page and look at the setting custom error pages in web.config section.

Resources