JSON simple program showing error - json

Tyring a simple example of json but it is showing error.
I have included gson-2.2.3.jar in class path.
I am using netbeans 7.1. This program is not deploying.
Apache tomcat log is showing:
Unable to load configuration. - action - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:10:73
Caused by: Error building results for action sayHi in namespace - action - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:10:73
Caused by: There is no result type defined for type 'json' mapped with name 'success'. Did you mean 'json'? - result - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:11:33
I am trying simple example. Please see what is the proble.
Action Class
public class AjaxActions extends ActionSupport {
private String name;
private String greeting;
public String sayHi() {
greeting = "HI " + name;
return ActionSupport.SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
Struts.xml
<package extends="struts-default,json-default" name="ajax-package" namespace="/ajax">
<action class="example.AjaxActions" method="sayHi" name="sayHi">
<result type="json">
</result>
</action>
</package>
in jsp file
<form action="" id="introForm">
<label for="name">Enter Your Name</label>
<input name="name">
<input type="submit">
</form>
<script>
$(function(){
$("#introForm").submit(function(){
var formInput=$(this).serialize();
$.getJSON('ajax/sayHi.action', formInput,function(data) {
$('.result').html('' + data.greeting + '');
return false;
});
});
</script>

add struts2-json-plugin.jar according to struts2 version in your project libraries.
if you are using struts2.3.4 then use struts2-json-plugin2.3.4.jar
And change your in your struts.xml
<package extends="struts-default,json-default"
to
<package extends="json-default".
And use the following html code.
<form action="" id="introForm">
<label for="name">Enter Your Name</label>
<input type="text" id="name" name="name">
<input onclick="javascript:getResultData();" type="submit">
<span id="resultHtml"></span>
</form>
<script>
function getResultData(){
var formInput=$("#name").val();
vat inputData={"name":formInput}
$.getJSON('ajax/sayHi.action', inputData,function(data) {
$("#resultHtml").html('' + data.greeting + '');
return false;
});
}
</script>

Related

Getting input value with freemarker

I simply forgot how to work with freemarker. I tried to create input, after submission which value of it gonna be displayed on the other page. It looks awful but here is my code :
#GetMapping("/form1")
public String getForm(){
return "form1";
}
#GetMapping("/name11/{Name}")
public String formPos(#PathVariable("Name") String name, Model model){
model.addAttribute("name", name);
return "name11";
}
html named form1
<form action="/name11" method="post">
<input name="Name" >
<button>put</button>
</form>
html named name11
<body>
<h1>${name}</h1>
</body>
#GetMapping("/form1")
public String getForm() {
return "form1";
}
#PostMapping("/name11")
public String formPos(#RequestParam("Name") String name, Model model) {
model.addAttribute("name", name);
return "name11";
}
form1 in static directory as form1.html
name11 in template directory as name11.ftlh

HTML radio button event calling Spring MVC controller

I want to make the filtering using radio button event. And I've searched about calling java method into html, and found this link. And try to implement it.
HTML file
<form action="${pageContext.request.contextPath}/servlet" method="post">
<input type="radio" value="1" name="radioFilter1"/> <br/>
<input type="radio" value="2" name="radioFilter2"/> <br/>
<input type="radio" value="3" name="radioFilter3"/> <br/>
</form>
SomeClass.java
public class SomeClass{
public String value;
public String filter1() {
return value= "1";
}
public String filter2() {
return value= "2";
}
public String filter3() {
return value= "3";
}
}
Controller.java
#RequestMapping("/servlet")
public String filterServlet(HttpServletRequest request, HttpServletResponse response) throws Exception {
SomeClass s = new FilterSorting();
if (request.getParameter("radioFilter1") != null) {
s.value= s.filter1();
} else if (request.getParameter("radioFilter2") != null) {
s.value= s.filter2();
} else if (request.getParameter("radioFilter3") != null) {
s.value= s.filter3();
}
return "/newhtml.html";
}
#RequestMapping("/newhtml.html")
public String newhtml(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
FilterSorting s = new FilterSorting();
list = Common.getList(dbSessionId, s.value);
model.addAttribute("asnlist", asnList);
return "/newhtml.html";
}
I'm using Spring framework version 4.0.0. And also I already tried using servlet, but it seems didn't work.
What I want is, when I click radioFilter2 then it will call filter2() which is set the parameter value is 2, and so on. And then the value will use as parameter to load content. But from what I've tried, it didn't work. Please help me, thanks!

MVC || HTML Form || Object reference not set to an instance of an object

I get this error and i dont know how to over come it:
"Object reference not set to an instance of an object."
Line 48: public ActionResult Upload(imageFile imageFile)
Line 49: {
Line 50: foreach (var image in imageFile.files)
Line 51: {
Line 52: if (image.ContentLength > 0)
I tried using ID attribute and name attribute and what not...
This is the problematic section in my controller :
[HttpPost]
public ActionResult Upload(imageFile imageFile)
{
foreach (var image in imageFile.files)
{
if (image.ContentLength > 0)
{
CloudBlobContainer blobContainer = _blobStorageService.GetCloudBlobContainer();
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(image.FileName);
blob.UploadFromStream(image.InputStream);
}
}
return RedirectToAction("Upload");
}
This is the HTML.Form :
<p>
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="imageFile" id="imageFile" multiple />
<input type="submit" name="submit" value="Upload" />
}
</p>
And this is the "imageFile" class :
public class imageFile
{
public IEnumerable<HttpPostedFileBase> files { get; set; }
}
What i'm doing wrong ? i read a lot of posts about this exception but none of them helped me..
Thank you.
Just change the name of your html input to be files, as in your model class:
Your input element in the view:
<input type="file" name="files" id="files" multiple />
Your model:
public class imageFile
{
public IEnumerable<HttpPostedFileBase> files { get; set; }
}

Losing data (specifically, the apostrophes) from HTML form to Java Servlet

Reference: HTML forms, php and apostrophes
I've been trying to pass data from my HTML form to my servlet for processing. However, I noticed that I'd lose the apostrophes in the text inputs. I'm not sure if this is a client or server side processing error, but looking through the reference above, i think i need to do some processing on the servlet side? Tried looking for a servlet alternative to the above but couldn't find any.
Here's the code snippets:
Html form:
<form method="post" action="CreateThreadServlet">
<b>Title</b><br>
<input type="text" name="title" size="60%" placeholder="Enter your title here"/><br>
<br><b>Tags</b><br>
<input type="text" name="tags" placeholder="Additional Tags: comma separated, e.g. Gamification, Java" size="60%" /><br>
<br><b>Details</b><br>
<textarea name="content" style="width:100%;height:50%"></textarea>
<input type="hidden" name="nick" value=<%=nick%>>
<input type="hidden" name="userid" value=<%=userid%>>
<button type="button" style='float: right;' onClick="closeDimmer()">Cancel</button>
<input type="submit" name="Submit" value="Submit" text-align='center' style='float: right;'>
</form>
This is the servlet code that processes the form:
String userid = req.getParameter("userid");
String nick = req.getParameter("nick");
String title = null; //tried using the URLDecoder, doesn't work
try {
title = URLDecoder.decode(req.getParameter("title"), "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CreateThreadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
String tags = req.getParameter("tags");
String[] tagStr = tags.split(",");
String[] addTags = req.getParameterValues("addTags");
PLEASE HELP THE NEWBIE.
As this link explains you could simply config a filter
<filter>
<filter-name>HitCounterFilter </filter-name>
<filter-class>
net.my.filters.HitCounterFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
having this:
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
chain.doFilter(request, wrapper);
}
}
so you force an UTF-8 encoding.

How to provide JSON data to Dojo tree using Struts2 framework

I'm currently developing a web application using Struts2 framework. This application requires to dynamically update the objects on the screen based on data received from another application.
At the moment, I would like to implement a dynamic tree view which nodes are updated periodically with data provided by an Action class. I’m trying to do so using the dojo.dijit.tree object from the dojo toolkit. I’m aware that I can do so using the dojo tags which are part of the struts framework, however, it lacks much of the functionality that I need (persistence, open and close branches dynamically, etc) therefore, I have opted for using the dojo toolkit instead.
My problem with the dojo.dijit.tree is that I don’t know how to provide its data using a JSON result type. I have already created a class which returns a JSON result type with the same structure needed by the dojo tree component. I have tested the generation of a dojo tree using a file “test.txt” which was generated by the class and it works as expected. However, I would like to pass the JSON data directly to the dojo.dijit.tree component without saving a file on disk. When I execute the application I get a “save as” window to save the returned JSON result.
This is my struts.xml file:
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="devResult" class="gui.JsonAction">
<result name="success">/start1.jsp</result>
</action>
</package>
<package name="example" namespace="/" extends="json-default">
<result-types>
<result-type name="json" class="org.apache.struts2.json.JSONResult"></result-type>
</result-types>
<action name="getJSONResult" class="gui.JsonAction">
<result type="json"/>
</action>
</package>
This is the jsp file which displays the tree:
<head>
<title>Testing Tree</title>
<style type="text/css">
#import "js/dojo/dojo/resources/dojo.css";
#import "js/dojo/dijit/themes/nihilo/nihilo.css";
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="isDebug: true,parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
dojo.require("dojo.parser");
</script>
<body class="nihilo">
The Tree:<br><br>
<s:url id="devResult" action="jsonAction.action"></s:url>
<div dojoType="dojo.data.ItemFileReadStore" href="%{devResult}" jsid="popStore" />
<div dojoType="dijit.Tree" store="popStore" labelAttr="sname" label="Tree" />
</body>
This is the Action class which produces the JSON result:
public class JsonAction extends ActionSupport {
private static final long serialVersionUID = 7392602552908646926L;
private String label = "name";
private String identifier = "name";
private List<ChildrenClass> items = new ArrayList<ChildrenClass>();
public JsonAction() {
ChildrenClass item1 = new ChildrenClass("name1", "cat");
ChildrenClass item2 = new ChildrenClass("name2", "cat");
ChildrenClass item3 = new ChildrenClass("name3", "cat");
ChildrenClass item4 = new ChildrenClass("name4", "cat");
items.add(item1);
items.add(item2);
items.add(item3);
items.add(item4);
}
public String execute() {
return SUCCESS;
}
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getIdentifier() {
return identifier;
}
public void setItems(List<ChildrenClass> lists) {
this.items = lists;
}
public List<ChildrenClass> getItems() {
return items;
}
}
This is the ChildrenClass which is used in the class above:
public class ChildrenClass {
private String name;
private String type;
private ChildrenClass[] children;
public ChildrenClass() {
name = "DefaultName";
type = "DefaultType";
}
public ChildrenClass(String aName, String aType) {
name = aName;
type = aType;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setChildren(ChildrenClass[] children) {
this.children = children;
}
public ChildrenClass[] getChildren() {
return children;
}
}
I would like to ask to the stackoverflow reader to please indicate me how to do to read the JSON data in the jsp file in order to populate the dojo tree. In addition, I would like to ask how can I refresh the content of it periodically.
PS: If somebody has a better method to implement something similar to this, I would be glad to receive your comments.
Thanks in advance.
I have found out a way to pass data directly from a JSON result to a dojo.dijit.tree component. Setting the "url" parameter to the action name which returns the json result type.
This is my new body of the .jsp file:
Simple Tree:<br><br>
<div dojoType="dojo.data.ItemFileReadStore" url=getJSONResult handleAs="json" jsid="popStore" />
<div dojoType="dijit.Tree" store="popStore" labelAttr="sname" label="PID 512" />