I have the following servlet code to store a data for a specific reason and later I retrieve the same data in another scenario in a project. It works fine as expected.
// setting
ServletContext context = request.getSession().getServletContext();
context.setAttribute("imageData", data);
// retrieving ...
ServletContext context = request.getSession().getServletContext();
byte[] data = (byte[])context.getAttribute("imageData");
Now, In an another project, where I use plain java program, where I want to store data similar to this servlet logic. I tried using the same code in plan java project, but it throws error, not accepting this servletcontext in plan java file.
Could someone please help, 1.) what is the equivalent in plan java to store like this temporarily or 2.) How to make that servletconext code working in plain java ?
Thank you in advance!
Getsy
How about simple HashMap<String, Object>
You can consider using simply a HashMap in the applet context.
If you need to use the same code in applet and web contexts, add a layer of abstraction and two implementations to manage the attributes depending on the context.
Related
I am converting an application from struts 1 to Spring MVC and I am trying to figure out what to do in my Java code when its using the import org.apache.struts.config.MessageResourcesConfig and org.apache.struts.util.MessageResources. In the spring-servlet.xml file I added the line to include my message resources properties file but I am not longer going to use the struts 1 libraries. How would I go about the conversion of this part of the code?
It is used a good bit throughout the application such as places like this:
this.config = new MessageResourcesConfig();
this.config.setParameter("path that was used here was set in the spring-servlet configuration file");
this.resources = MessageResources.getMessageResources(this.config.getParameter());
I would refactored the way you load the Resources using java.util.ResourceBundle
// load resourcebundle.properties
bundle = ResourceBundle.getBundle("resourcebundle");
You can then get a value using
String val = bundle.getString(key);
You can have an helper class to get the values you need, and/or find a way to pass it to the JSP (cannot help you there, sorry)
I'm doing an assignment where I have to use a web service using apache axis (Using eclips Mars) to make a desktop application in Java. It has to use an existing dynamic web project I already created.
Web project was to add/remove companies and employee details in a (Oracle) database in a web interface. It worked as required. But when the web service was created, It doesn't allow me to create a web client. It gives this error:
IWAB0399E Error in generating Java from WSDL:
java.io.IOException: ERROR: Missing <soap:fault> element inFault "IOException"
in operation "IOException", in binding getCompanies
Apparently, it wont allow me to return HashMaps from methods I created. (When I changed my whole project without returning Hashmaps, I can create the client) But I need to get HashMaps.
Are there any way to get HashMaps from the web service I created ???
I've refereed This question in SO. But I have no idea what's the accepted answer was saying.
EDIT:
OK. Now I know that I can't use HashMaps in web services as they can't be marshal and unmarshal. Then I found This question which I tried. But the problem still stands. (I guess I didn't used the answer mentioned above correctly.) As a beginner in this field, I actually don't get how to wrap (Or serialize) Hashmap and retrieve it back. Can someone show an example ?
You can try to wrap your HashMap in a class and create a custom adapter using it with #XmlJavaTypeAdapter to allow JAXB to make the object serialisation correctly.
public class Response {
#XmlJavaTypeAdapter(MapAdapter.class)
HashMap<Integer, Student> students;
public HashMap<Integer, Student> getStudents() {
return students;
}
public void setStudents(HashMap<Integer, Student> map) {
this.students = map;
}
}
Then just use this class as a return value of your web method.
See more:
Doc API
Example
I am working on "migration from JSP to FLEX, and java as back-end. I am novice in java and JSP.
I am stuck at getting values from a java servlet where it takes httprequest and there is a function called forward(request,response) which responds as JSP page with requried values in it.
Now I need to change that and get only data from that servlet and use that in flex.
Problem:
case1: When using httpservice it takes result as string, but unable to get as object.
case2: If I use RemoteObject , it needs method in java servlet to get return value, which is not present in existing servlet.
Can I get any suggestions on this problem.
Thank You
case1: you don't use forward anymore, you set the type of data you want to return, for example:
response.setContentType("application/json");
... and returning data in servlet is done by writing data to a stream like:
PrintWriter out = response.getWriter();
out.print(object);
but it's a while ago since I did this, so there may be some small problem you will face...
case2: if you are using servlet, it's correct to use HTTPService, RemoteObject will not work, it is used differently....
Now, if I can, I would suggest diferent thing to use than servlets - to obtain data from a java server to Flex - I love to use GraniteDS.
I will just state some benefits I see, in case you are interested:
It is easy to setup:
- in java, you will just add a graniteDS library, two config files (granite+services-config xmls) add a granite servlet config to web.xml
- in flex there is also granite library and services-config.xml
When set up, using it is also flowleslly easy - you have a class with a method (or simple bean or ejb) in Java which just return an object of any type! And that's it in Java
In flex, in this case you use RemoteObject which you just call that remote java method and in result handler you get your dataGranite will take care of serializing+transfer+deserializing and just give you the Object (either just dynamic {} or even exact class type)
I have a customized JSP tag library with a Java class (extending TagSupport) that generates the output for my web application. It has some parameters that are formed into HTML code using a StringBuilder.
Now the generated HTML is becoming more complex and hard to handle with calls of StringBuilder.append, so I'd like to replace the code generation with a Freemarker template.
I already found out that I could use a generic Struts component tag instead, because the Struts tags already use Freemarker template files, so I could write a tag like:
<s:component template="/components/myStruct.ftl">
<s:param name="myParam" value="%{'myParam'}" />
</s:component>
Then writing the specified template file myStruct.ftl would probably solve my problem. I actually did not try if Struts really finds and uses that file correctly, but I optimistically expect it to work.
My question is, if it's also possible to retain the current code with the customized tag
<my:struct param="myParam" />
and only change the Java class linked to that tag.
I've found code that reads a Freemarker template:
Configuration config = FreemarkerManager.getInstance().getConfiguration(pageContext.getServletContext());
config.setServletContextForTemplateLoading(pageContext.getServletContext(), "/components");
Template templ = config.getTemplate("myStruct.ftl");
templ.process(params, pageContext.getOut());
but it seems very circuitously to me and I wondered what would be the "standard" way to do it. Additionally it seemed that you cannot use tags from the Struts tag library in a template used like this. (I ran into an ArrayIndexOutOfBoundException, caused by Sitemesh... I did not analyze it yet.)
My intention was to keep the Java class as some kind of wrapper around the Struts component tag. Maybe somthing like:
OgnlValueStack stack = TagUtils.getStack(pageContext);
Component c = new Component(stack);
c.addParameter("param", param);
But I don't know how to continue this code stub. It may be crap anyway.
Is there an easy/"standard" way to do this or do I simply have to get rid of the customized tag?
Thanks in advance.
A friend of mine sent me this link:
http://cppoon.wordpress.com/2013/02/27/how-to-create-a-struts-2-component-with-freemarker/
This is what I was looking for. The gist is to change the customized tag to not extend TagSupportbut AbstractUITag which makes it a Struts tag instead of a JSP tag, roughly speaking.
This enables the automatic linkage (by name and path conventions) to my Freemarker template. I basically followed the instructions on that page. I only added the methods that are abstract in the super class, so they had to be implemented.
IMO the site lacks of a description of how the UI bean class is linked to the tag class. But as the IDE forces you to implement the getBean method inside the tag class, you quickly get to this code (using the classes described on that site):
#Override
public Component getBean(OgnlValueStack stack, HttpServletRequest request, HttpServletResponse response)
{
Pagination pagination = new Pagination(stack, request, response);
pagination.setList(list);
return pagination;
}
This might not be completely correct for the recent Struts, but it worked for the ancient version I've got to use.
Thanks again to the guy who sent me the link :)
I have a JSP 2.0 file containing calls to a custom tag that needs to know what bundle is currently in use on the page, so it can look up some resources. The custom tag is written in Java. The bundle can change depending what page the custom tag is used on, but the resource key will always be the same, so I wanted to use the existing fmt:bundle tag to specify this, e.g.:
<fmt:bundle basename="myBundle">
<custom:tag title="text.title"/>
</fmt:bundle>
I've been assuming that the fmt:bundle tag can be read from (or otherwise provides its environment to) the inner tags, where the custom tag is in the above example (in the same way that it interacts with the fmt:message tag), but I haven't been able to figure out how to access the LocalizationContext that fmt:bundle supposedly defines from within the Java that defines the custom tag.
I've tried
LocalizationContext lc = (LocalizationContext)Config.get(
pageContext.getRequest(),Config.FMT_LOCALIZATION_CONTEXT);
ResourceBundle rb = lc.getResourceBundle();
String s =rb.getKey(title);
but I just get
java.util.MissingResourceException: Can't find resource for bundle
java.util.PropertyResourceBundle, key text.title
which seems to indicate that is not the right place to look (I guess that has fallen through to the default bundle?).
One workaround might be to pass the bundle name into the custom tag, but I'm sure what I want to achieve should be possible, if only my poor JSP know-how didn't let me down, so I hope someone can help me get a better understanding!
What should I be doing?
According to the JSTL specification there is a class named LocaleSupport that implements the bundle lookup and may be used by any tag handler implementation that needs to produce localized messages.