Ajax call not hitting controller - java

hi I am trying to Use Ajax with Spring Mvc Porltet In liferay.I Have a Jsp File and Controller Class.I want to insert a data in the form but my controller class is Not Called.So please Help Me to Solve this Problem.When I Click on submit My COntroller class is not called.
my .jsp code as follws:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects/>
<portlet:renderURL var="renderOneMethodURL">
<portlet:param name="action" value="renderOne"></portlet:param>
</portlet:renderURL>
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
</portlet:actionURL>
Call RenderOne method
<%-- <form action="${actionOneMethodURL}" method="post">
User Name: <input type="text" name="userName">
<input type="submit">
</form> --%>
<div id="request">
<div id="bigForm">
<h2> REQUEST</h2>
<h3> Enter Request Details :</h3>
<p>Name: <input name="name">
Code: <input name="code" size="6">
Request: <input name="request">
Type: <input name="type" size="6"></p>
<hr></hr>
<div class="block2">
<h2> Attribute Value Pair(Avp)</h2>
<p class="remark"> Recursive structure of avp. You can nest one AVP inside another..</p>
<div data-holder-for="branch"></div>
</div>
<div class="clear"></div>
<p> </p>
<p class="remark" align="right" padding-right:"1cm";>Click here to generate JSON representation of the form</p>
<p align="right">
<input type="submit" id="saveBigForm"></p>
</div>
<style type="text/css">a {text-decoration: none}</style>
<!-- Subforms library -->
<div style="display:none">
<div data-name="branch">
<table>
<td>Name:</td> <td><input name="name"></td>
<td>Code:</td> <td><input name="code"></td>
<td>Vendor:</td> <td><input name="vendor"></td>
<td>Multiplicity:</td><td><input name="multiplicity"></td>
<td>Index:</td><td><input name="index"></td>
<td>CDR-Index:</td><td><input name="cdrIndex"></td>
<tr>
<td >Type:</td><td><input name="type"></td>
<td>Value:</td><td><input name="value"></td>
</tr>
</table>
<div style="margin:10px; border-left:3px solid black" data-holder-for="branch"></div>
</div>
</div>
<div id="popup"></div>
</div>
and my javascript
$('#saveBigForm').click(function(){
var json = $('#bigForm').jqDynaForm('get');
showFormJson(json);
// var myInfoUrl = "<c:out value="${actionOneMethodURL}" />";
$.ajax({
type: "POST",
//url: "http://localhost:9090/first-spring-mvc-portlet//WEB-INF/servlet/view",
//url : myInfoUrl,
url : "${actionOneMethodURL}",
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
});
and controller class as follows
package com.myowncompany.test.springmvc.controller;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
#Controller(value = "MyFirstSpringMVCTestController")
#RequestMapping("VIEW")
public class MyFirstSpringMVCTestController {
private static Log log = LogFactoryUtil.getLog(MyFirstSpringMVCTestController.class);
/*
* maps the incoming portlet request to this method
* Since no request parameters are specified, therefore the default
* render method will always be this method
*/
#RenderMapping
public String handleRenderRequest(RenderRequest request,RenderResponse response,Model model){
return "defaultRender";
}
#RenderMapping(params = "action=renderOne")
public String openSaveSearchPopup(RenderRequest request, RenderResponse response, Model model){
return "render1";
}
#RenderMapping(params = "action=renderTwo")
public String openDeeplinkForInfoI(RenderRequest request, RenderResponse response){
return "render2";
}
#RenderMapping(params = "action=renderAfterAction")
public String testRenderMethod(RenderRequest request, RenderResponse response){
log.info("In renderAfterAction method");
return "renderAfterAction";
}
#ActionMapping(params = "action=actionOne")
public void actionOne(ActionRequest request, ActionResponse response) throws IOException {
String userName=ParamUtil.get(request, "userName", "");
log.info("server input stream is :::"+ request.getPortletInputStream().toString());
System.out.println("we ri nnnnnnnnn");
log.info("userName is==>"+userName);
response.setRenderParameter("action", "renderAfterAction");
}
#ActionMapping(params = "action=actionTwo")
public String addMyChannelAction(ActionRequest actionRequest, ActionResponse actionResponse) {
return "action2";
}
}
iam getting the log as follows:
09:36:56,291 INFO [DispatcherPortlet:119] Portlet 'firstspringmvc' configured successfully
09:36:56,300 INFO [localhost-startStop-19][PortletHotDeployListener:454] 1 portlet for first-spring-mvc-portlet is available for use
10:09:49,460 WARN [http-bio-9090-exec-138][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
10:09:54,325 WARN [http-bio-9090-exec-139][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}

Try with jsp core tag,
url : "<c:url value='/VIEW/actionOne' />"
OR
url : "<c:out value='${actionOneMethodURL}' />"

Include JSTL core in JSP i.e.:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
and Change your ajax URL
url : "${actionOneMethodURL}"
to
url : "<c:url value='/VIEW/actionOne' />",

From what you have told us so far I can identify those causes:
your javascript has a problem and is not running at all (open with google chrome or firefox and press F12. Go to the Console tab and tell us if you have any errors there.
since you have a different javascript file, as the warning said, ${actionOneMethodURL}is not defined there. So you can do it like this:
In your HTML (the .jsp file you postet at top):
<script type="text/javascript">
ajaxLink = "${actionOneMethodURL}";
</script>
In your javascript file:
url : window.ajaxLink;
Experiment with this, I have no way to test it may need some tweaks like where you add the script (near the beginning of the document, near the end), and if the " surrounding the ${actionOneMethodURL} are needed.

in .jsp page add
var actionurl =${actionOneMethodURL};
in example.js on ajax call
$.ajax({
type: "POST",
url : actionurl,
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});

Related

How to get an HTML data form to my web service?

I'm working on a project and I'm trying to get an HTML form data into my REST web service, so I can insert it into my database, I don't know where to get the HTML form data from.
This is my web service:
package hananepkg;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* #author mon pc
*/
#Path("generic")
public class GenericResource {
DBConnector db = new DBConnector();
#Context
private UriInfo context;
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
/**
* Retrieves representation of an instance of pkg.GenericResource
* #return an instance of java.lang.String
*/
#GET
#Produces(MediaType.TEXT_HTML)
public String insert(#QueryParam ("name")String name,#QueryParam ("email")String email,#QueryParam ("password")String password,#QueryParam ("confirmpassword")String confirmpassword) {
//TODO return proper representation object
return "<html><body><h1>"+db.insertData(name,email,password,confirmpassord)+"</body></h1></html>";
}
/**
* PUT method for updating or creating an instance of GenericResource
* #param content representation for the resource
*/
#PUT
#Consumes(MediaType.TEXT_HTML)
public void putHtml(String content) {
}
}
This is my html page:
<section id="contact" class="contact3">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Sign In</h2>
</div>
<div class="col-lg-6 mt-5 mt-lg-0" data-aos="fade-left" data-aos-delay="100">
<form action="forms/contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Username" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="password" class="form-control" name="subject" id="password" placeholder="Password" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="password" class="form-control" name="subject" id="confirmpassword" placeholder="Confirm Password" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="text-center"><button id="submit" type="submit">Sign In</button></div>
</form>
</div>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "http://localhost:8080/HananeTest/",
data: formToJSON(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
alert('Success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Error: ' + textStatus);
}
});
});
});
function formToJSON()
{
return JSON.stringify
({
"username": $('#name').val(),
"email": $('#email').val(),
"password": $('#password').val()
"password": $('#confirmpassword').val() });
};
</script>
Any suggestions how to get the input data into my web service so I can insert it to my database?
In your resource you have generic and in JS you have HananeTest as path. Make sure your are using the correct paths on both sides.
Your formToJSON function does not fill the parameter confirmpassword but has a duplicate entry for password. Make sure that all the parameters are set properly.
In JS you are currently using a JSON string and in your service you are referring to individual query parameters. To get JSON data to your method, you can annotate it with #Consumes({MediaType.APPLICATION_JSON}) and then use a simple POJO with the corresponding fields as attributes.
Example:
#Path("api/user")
public class YourResource {
#GET
#Consumes({MediaType.APPLICATION_JSON})
#Produces(MediaType.TEXT_HTML) // depending on what you want to return
public String insert(UserDTO user) {
// validation logic
// insert user into database
// return something
}
}
public class UserDTO {
private String username;
private String email;
private String password;
private String confirmpassword; // can possibly be removed if you check in JS whether the passwords match
// getters and setters
}

How to use Shiro without login page for WEB application

I have a WEB Application which wrote with Struts2. And It doesn't have a login page. The login page is a div of the main page.
I want to use Shiro for security of my application.
I don't understand how to use Shiro without the login page.
And I don't understand how to pass a username to Shiro from Struts Action.
Please help me.
Thank you.
My Action:
public class InternalLoginAction extends ActionSupport {
private String remoteUser;
public String execute() throws NamingException, SQLException {
HttpServletRequest request = ServletActionContext.getRequest();
remoteUser = request.getRemoteUser();
if (remoteUser != null) {
User user = new User();
user.setId(user.calcIdTemp(remoteUser));
user.setName(remoteUser);
user.setCompanyId(LoginDao.getUserCompanyId(remoteUser.toUpperCase()));
user.setExternal(false);
user.saveSession();
//I want to pass username to Shiro here.
}
return SUCCESS;
}
public String getRemoteUser() {
return remoteUser;
}
public void setRemoteUser(String remoteUser) {
this.remoteUser = remoteUser;
}
}
I am sorry, but I cannot show all page. Only this is:
<div id="login-dialog" title="Authorization" class="hide">
<form id="login-dialog-form" >
<table>
<tr>
<td>Login:</td>
<td>
<input id="login-dialog-login" name="form.login" size="22" maxlength="22" class="text ui-widget-content ui-corner-all" data-parsley-required="true" autofocus>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input id="login-dialog-pass" name="form.pw" type="password" size="22" maxlength="22" class="text ui-widget-content ui-corner-all" data-parsley-required="true" data-parsley-minlength="6" data-parsley-maxlength="20">
</td>
</tr>
</table>
<br>I am employee of XXX
</form>
</div>
My function:
internalLogin: function() {
$.ajax({
url: '/xxx/public/internalLogin.do',
type: 'POST',
success: function(data) {
location.reload(true);
},
error: function(request, textStatus, errorThrown) {
wsp.alertMessage(request.responseText);
}
});
You probably want to handle all of the login logic before you get into your action.
Shiro works out of the box with Servlet filters. For example this example (which is just a couple JSP) doesn't actually handle any of the login logic:
https://github.com/apache/shiro/tree/master/samples/servlet-plugin
Other than rendering a login form. The Shiro Servlet Filter intercepts the post to the login page (in this case /login.jsp) and handles everything else automatically.

i can't access freemarker variables in external javascript file

i cant get the value of a freeMarker variable when i put my code in a external javascript file
here is my page when the javascript code inside, this works i can get the value of my freemarker variable in this way:
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign title="value 1">
<#assign subtitle="value 2">
<script>
function doAjaxPost()
{
var name= $('#name').val();
var lastName= $('#lastName').val();
var json = {"name" : name, "lastName" : lastName};
console.log(json);
var variableFreeMarker = "${freeMarkValue}";
console.log('this value is: ' + variableFreeMarker);
$.ajax(
{
type: "POST",
url: "myUrl",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
/* error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}*/
});
}
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
but if i put my javascript code in a external file in this case myPageScript.js and then call that script in my page i cant get the value of my freeMarker variable this is how i'm calling my script
<script src="../resources/js/scripts/myPageScript.js"></script>
and this is my page that dont work
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
this output in my chrome console "${freeMarkValue}" instead of the value of the variable
here are my controllers i'm processing the form using jquery ajax
#RequestMapping(value = "myForm", method = RequestMethod.GET)
public String myForm(Model model) {
model.addAttribute("freeMarkValue", "controll");
return "myForm";
}
#RequestMapping(value = "myForm", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User objetmapped = mapper.readValue(json, User .class);
User person = new User iox();
person.setName(objetmapped .getName());
person.setLastName(objetmapped .getLastName());
);
model.addAttribute("freeMarkValue", "second controller value");
return toJson(objetmapped );
}
private String toJson(User person)
{
ObjectMapper mapper = new ObjectMapper();
try
{
String value = mapper.writeValueAsString(person);
// return "["+value+"]";
return value;
}
catch (JsonProcessingException e)
{
e.printStackTrace();
return null;
}
}
You can move your variable into a script block in the html page.
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<script>
// This variable can be accessed from myPageScript.js
var variableFreeMarker = "${freeMarkValue}";
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
Or add it as a value of a hidden input etc..
<input type="hidden" id="myVal" value="${freeMarkValue}">
Your JS (in a seperate script) would then need to read the value for example using jQuery.
var aValue = $("#myVal").val();
I use the first method for common stuff such as adding a date format string that is specific to the user on to every page. They will have global scope so be careful with naming.

Liferay: How to make enctype="multipart/form-data" and method="post" work together?

I'm developing a web app using liferay portal server 6.2
JSP code -
<form id="mainForm" action="<portlet:actionURL/>" method="post" enctype="multipart/form-data" >
<input type="hidden" id="varImport" name="varImport"/>
<div class="tab-pane" id="uploadFile">
<p>Please upload a file</p>
<div id="inputFileDiv">
<input type="file" name="uploadFile" />
</div>
</div>
<input type="submit" class="btn btn-info" onClick="import()" value="IMPORT" />
</form>
<script>
function import() {
console.log("importing");
document.getElementById("varImport").value = "IMPORTFILE";
document.getElementById("mainForm").submit();
}
</script>
Servlet code -
#Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
System.out.println("myPortlet.processAction() >> " + request.getParameter("varImport"));
//... rest of the code.
}
If I remove enctype from jsp form, I get the value of varImport in my servlet.
But if i keep it, it returns null.
What am i missing?
import com.liferay.portal.util.PortalUtil;
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
System.out.println("myPortlet.processAction() >> " + uploadRequest.getParameter("varImport"));

File upload using ajax and jQuery in Spring without using FormData

I want to upload an excel file in my application using ajax,jQuery and Spring form. Following is my code. I am able to hit the controller with #modelAttribute which is nothing but a Simple Java Class having one Multipart file attribute but that file attribute in the FileUploadForm is null when the request is coming to Controller. Can anyone suggest what wrong I am doing. I am doing this in IE8 so can not use FormData. Thanks in advance.
JSP
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var form = $('#myForm');
form.find('#submitButton').click(function() {
$.ajax({
type : "POST",
url : form.attr('action'),
enctype : 'multipart/form-data',
data : form.attr('modelAttribute'),
success : function(data) {
alert("Success"+data);
},
error : function(data) {
alert("error");
}
});
});
});
</script>
</head>
<body>
<form:form method="post" action="upload" id="myForm"
modelAttribute="uploadForm" enctype="multipart/form-data">
<table id="fileTable">
<tr>
<td><input name="file" id="uploadedFile" type="file" /></td>
</tr>
</table>
<br />
<!-- <button class="btn btn-primary" type="submit" value="Upload">
Upload</button> -->
<input type="submit" class="btn btn-primary" id="submitButton"
value="Upload" />
</form:form>
And following is my controller code.
Controller
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(#ModelAttribute("uploadForm") FileUploadForm form,
Model model) {
MultipartFile file = form.getFile();
String name = file.getOriginalFilename();
FileSystemResource fsr = new FileSystemResource(name);
StatusVO statusVO = service.loadAndProcessUploadedFile(fsr.getFile());
model.addAttribute("status", statusVO);
return "/common/message";
}
Following is FileUplaodForm Class
FileUploadForm.java
import org.springframework.web.multipart.MultipartFile;
public class FileUploadForm {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
If form is not getting submitted by submit button, simply try like this,
var form = $('#myForm');
form.find('#submitButton').click(function() {
form.submit(); //This will submit your form.
});
Hope this helps.
Hey Thanks all for your quick response but i got it solved. Ajax not at all works with file uploads. So I removed all ajax related code and made it simple form submit. Now working fine.

Categories

Resources