As mentioned in my last post about NanoWeb I wanted to add support for other view types. Well that I have now done. It’s been submitted to the nanocontainer jira, where you can download it if you want it. I have also updated my last posts NanoWeb Sample WAR to include this and samples on how to use it. Just download and drop into your tomcat/webapps folder.
Configuration
The default view type is still velocity, but to add others such as JSP add the following init-param in the web.xml.
<servlet>
<servlet-name>NanoWeb</servlet-name>
<servlet-class>org.nanocontainer.nanowar.nanoweb.NanoWebServlet
</servlet-class>
<init-param>
<param-name>viewtypes</param-name>
<param-value>.jsp,.vm</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Just list the extensions to the view technologies you want to use. While not tested this should also work for freemarker.
In the above example it will first look for .jsp views and then try .vm views.
Using POJO as NanoWeb Actions
I hadn’t realized this, but Aslak mentioned that there was already support for plain Java actions. It turns out that all you have to do is register it to the Request scope of the PicoContainer in your web.xml file:
pico.registerComponentImplementation("/salary",org.nanocontainer.sample.nanoweb.SalaryCalculator)
The Java class itself couldn’t be simpler. Just implement properties with setters and getters. All methods without parameters that return a String can be called via the web as actions.
Here’s a simple example:
public class SalaryCalculator {
private String name;
private String salary;
public String getName() {
if (name==null)
return "Enter name";
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSalary() {
if (salary==null)
return "0";
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getMonthlySalary(){
return Double.toString(Double.parseDouble(salary)/12);
}
public String calculate(){
if (name==null||salary==null)
return "input";
else
return "view";
}
}
This certainly is simple. Just make sure you don’t add any exploitable methods in your actions such as:
public String transfer() {
queue.publish(new Transfer(getAmount(),getRecipient()));
}
This entry was posted in the following Categories: Java