I have simple login page which uses AJAX POST the page works fine in the browsers. I have created an android studio project with the web view and given the link of the login page, I have also included HTML 5 features for the page, but the login page does not send or receive any data when i run it on the android studio emulator.
The AJAX POST CODE is as follows
var ins = empID + "~" + empPassword;
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://Servername/Service1.svc/json/EmpLogin",
data: '{"EDetailslogin": "' + ins + '"}',
crossDomain: true,
dataType: "json",
processData: false,
success: function(data) {
widow.location.href = "Page2.html";
},
error: function(data) {
alert("User Not Recognized");
}
});
The android manifest code is as follows
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.Myproj.Sample">
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:icon="#mipmap/ic_launcher" android:label="#string/app_name" android:roundIcon="#mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
My Main Activity.java file has the following code with the HTML-5 features added to the page.
public class MainActivity extends AppCompatActivity {
private WebView wv1;
public String TAG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv1 = (WebView) findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
String url = "file:///android_asset/login.html";
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
WebSettings ws = wv1.getSettings();
ws.setJavaScriptEnabled(true);
ws.setAllowFileAccess(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
try {
Log.d(TAG, "Enabling HTML5-Features");
Method m1 = WebSettings.class.getMethod("setDomStorageEnabled", new Class[] {
Boolean.TYPE
});
m1.invoke(ws, Boolean.TRUE);
Method m2 = WebSettings.class.getMethod("setDatabaseEnabled", new Class[] {
Boolean.TYPE
});
m2.invoke(ws, Boolean.TRUE);
Method m3 = WebSettings.class.getMethod("setDatabasePath", new Class[] {
String.class
});
m3.invoke(ws, "/data/data/" + getPackageName() + "/databases/");
Method m4 = WebSettings.class.getMethod("setAppCacheMaxSize", new Class[] {
Long.TYPE
});
m4.invoke(ws, 1024 * 1024 * 8);
Method m5 = WebSettings.class.getMethod("setAppCachePath", new Class[] {
String.class
});
m5.invoke(ws, "/data/data/" + getPackageName() + "/cache/");
Method m6 = WebSettings.class.getMethod("setAppCacheEnabled", new Class[] {
Boolean.TYPE
});
m6.invoke(ws, Boolean.TRUE);
Log.d(TAG, "Enabled HTML5-Features");
} catch (NoSuchMethodException e) {
Log.e(TAG, "Reflection fail", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Reflection fail", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Reflection fail", e);
}
}
wv1.loadUrl(url);
//wv1.loadUrl("file:///android_asset/index.html");
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
I have also Imported all the necessary class files. Still the application does not seem to work. Can anyone please help me with this.
Related
I'm trying to call a function exposed by WCF service using ajax but the success method is always returning 'undefined' even though the function itself on the WCF side is returning the right answer
I tried debugging and printing everything and the WCF is returning the right answer but when the ajax call enters the success method object it receives is undefined
WCF:
[OperationContract]
[ WebInvoke (
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public Result_Login LoginAdmin(string email, string password)
{
System.Diagnostics.Debug.WriteLine("LoginAdmin called");
#region Declaration And Initialization Section.
Result_Login resultLogin = new Result_Login();
#endregion
#region Body Section
try
{
BLC.BLC oBLC_Default = new BLC.BLC();
BLCInitializer oBLCInitializer = new BLCInitializer();
oBLCInitializer.ConnectionString = ConfigurationManager.AppSettings["CONN_STR"];
System.Diagnostics.Debug.WriteLine("Connection string: "+ConfigurationManager.AppSettings["CONN_STR"]);
using(BLC.BLC oBLC = new BLC.BLC(oBLCInitializer))
{
resultLogin.login = oBLC.SignInAdmin(email, password);
}
}
catch(Exception ex)
{
if(ex.GetType().FullName != "BLC.BLCException")
{
resultLogin.ExceptionMsg = string.Format("Get_Persons : {0}", ex.Message);
}
else
{
resultLogin.ExceptionMsg = ex.Message;
}
}
#endregion
#region Return Section
return resultLogin;//giving the right result before ajax return method
#endregion
}
public override string ToString()
{
return base.ToString();
}
// Add more operations here and mark them with [OperationContract]
}
#region Action_Result
public partial class Action_Result
{
#region Properties.
public string ExceptionMsg { get; set; }
#endregion
#region Constructor
public Action_Result()
{
#region Declaration And Initialization Section.
#endregion
#region Body Section.
this.ExceptionMsg = string.Empty;
#endregion
}
#endregion
}
#endregion
#region Result_Login
public partial class Result_Login : Action_Result
{
#region Properties.
public bool login { get; set; }
#endregion
}
Javascript:
function IsAuthenticated_JSON() {
try {
_Params1 = new Object();
_Params1.email = $("#Login1_UserName").val();
_Params1.password = $("#Login1_Password").val();
_Params = JSON.stringify(_Params1);
_Service_Method = "LoginAdmin";
CallService(_Service_Method, IsClientAuthenticated_Completed, Service_Call_InCompleted);
}
catch (e) {
alert("IsAuthenticated_JSON: " + e.Message);
}
}
function IsClientAuthenticated_Completed(i_Input) {
try {
localStorage.setItem("UserInfo", JSON.stringify(i_Input.My_Result));
console.log("unstringify: " + JSON.stringify(i_Input.My_Result));//undefined
if (localStorage.getItem('UserInfo') != null) {
_UserInfo = JSON.parse(localStorage.getItem('UserInfo'));
_Ticket = _UserInfo.Ticket;
alert("done");
}
}
catch (e) {
console.log("error "+e.Message + " " + e.log)
}
}
function CallService(i_Service_Method, i_Success_Method, i_Failure_Method) {
var url = "";
url = js_Prepare_WCF_Url_For_Call();
var request = $.ajax({
type: "POST",
url: url,
data: _Params,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
console.log("data: "+msg.data +"status: "+ msg.status +"message: " + msg.Message);//undefined
i_Success_Method(msg);
},
error: function (msg) {
console.log("fail: " + msg.responseText + msg.statusText)
}
});
}
Web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="FuelAppEntities" connectionString="metadata=res://*/DALC.csdl|res://*/DALC.ssdl|res://*/DALC.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=FuelApp;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="CONN_STR" value="Data Source=.;Database=FuelApp;User ID=sa;Password=sa" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="project.Service1AspNetAjaxBehavior">
<enableWebScript />
</behavior>
<behavior name="My_Behavior">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="project.WCF.customBinding0">
<binaryMessageEncoding />
<httpTransport />
</binding>
</customBinding>
<webHttpBinding>
<binding maxBufferPoolSize="1048576" maxReceivedMessageSize="1048576" maxBufferSize="1048576" name="jsonpWebHttpBinding" useDefaultWebProxy="false" crossDomainScriptAccessEnabled="false" />
</webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0"/>
<services>
<service name="project.WCF">
<endpoint address="a" behaviorConfiguration="project.Service1AspNetAjaxBehavior"
binding="webHttpBinding" contract="project.WCF" />
<endpoint address="" binding="webHttpBinding" bindingConfiguration="jsonpWebHttpBinding" contract="project.WCF" behaviorConfiguration="My_Behavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Apple" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Android" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.WindowsPhone" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Blackberry" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Windows" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Not sure why you meet this problem , I have copied your code and have a test, but I could get the response.
Below is my code.
[ServiceContract]
public class MyTestRestService
{
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public Result_Login LoginAdmin(string email, string password)
{
Result_Login resultLogin = new Result_Login();
resultLogin.ExceptionMsg = "exception";
resultLogin.login = true;
return resultLogin;
}
}
Model
public partial class Action_Result
{
public string ExceptionMsg { get; set; }
public Action_Result()
{
this.ExceptionMsg = string.Empty;
}
}
public partial class Result_Login : Action_Result
{
public bool login { get; set; }
}
Endpoint config.
<service name="Service.Rest.MyTestRestService" >
<endpoint binding="webHttpBinding" contract="Service.Rest.MyTestRestService" behaviorConfiguration="web"></endpoint>
</service>
To enable cross origin request, if your wcf rest server and your client are not at the same origin.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="*"/>
</customHeaders>
</httpProtocol>
protected void Application_EndRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.StatusCode = 200;
}
}
The result.
It worked after adding
<webHttp defaultOutgoingResponseFormat="Json" />
to the service behavior in web.config
According to Android document:
Tells JavaScript to open windows automatically. This applies to the JavaScript function window.open(). The default is false.
But I didn't see any different between use or not use this API in my code, window.open works fine in the both cases, so what's the true purpose of this API or my usage is not correct?
My code sample as below:
public class MainActivity extends Activity {
private WebView mWebView;
//private Context mContext
RelativeLayout mParent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mParent = new RelativeLayout(MainActivity.this);
setContentView(mParent);
mWebView = new WebView(MainActivity.this);
WebSettings settings = mWebView.getSettings();
settings.setSupportMultipleWindows(true);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
settings.setJavaScriptEnabled(true);
mParent.addView(mWebView);
mWebView.loadUrl("file:///android_asset/create_window.html");
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
WebView newWebView = new WebView(view.getContext());
newWebView.getSettings().setUserAgentString("BBB");
//newWebView.getSettings().setJavaScriptEnabled(true);
//newWebView.setWebChromeClient(this);
newWebView.setWebViewClient(new MyWebViewClient());
//view.getSettings().setUserAgentString("CCC");
mParent.addView(newWebView);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
mParent.removeViewAt(mParent.getChildCount() - 1);
}
});
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, final String url) {
super.onPageFinished(view, url);
}
}
}
The content of create_window.html as below:
<html>
<!-- scripts -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Create Window</title>
<script>
function
openURL ()
{
alert ("opening window");
window.open ("http://www.whoishostingthis.com/tools/user-agent/", "_blank", "width=200,height=100");
}
</script>
</head>
<body>
<div>
<button onclick="openURL()">open website in new window</button>
</div>
</body>
</html>
How can I add form fields when I click on link only by using Struts2, jsp without javascript/jquery.
I want when I click on addCompte link in the same page jsp add more fields about compte in addition of client fields already exist.
I want to stay in the same jsp page, when user click on the link more fields about Account display. the Question is when user click on the link which expression should me use in
This my client.jsp code:
<body>
<h1>Show de Clients</h1>
<s:form action="updateClient">
<s:textfield name="nom" label="Nom"/>
<s:textfield name="prenom" label="Prenom"/>
<s:textfield name="age" label="Age"/>
<s:textfield name="codeClient" label="CodeClient"/>
<s:url var="addCompteURL" action="addCompteToClient">
<s:param name="codeClient" value="%{codeClient}"></s:param>
<s:hidden name="moreCompte" value="yes" label="hide"></s:hidden>
</s:url> <s:a href="%{addCompteURL}" onclick="">addCompte</s:a>
<s:if test="%{moreCompte!=null}">
<s:textfield name="numeroCompte" label="NumeroCompte"/>
<s:textfield name="solde" label="Solde"/>
<s:textfield name="dateCreation" label="DateCreation"/>
<s:submit action="addCompteToClient"
value="addCompteToClient" align="center">
</s:submit>
</s:if>
<s:else>
<s:submit action="updateClient" value="update client"
align="center">
</s:submit>
</s:else>
</s:form>
</body>
this my action code ClientAction.java:
public class ClientAction extends ActionSupport{
private int codeClient;
private String nom;
private String prenom;
private int age;
private String adresse;
private String numeroCompte;
private double solde;
private Date dateCreation;
private Client client;
List<Client> clientList;
ServiceMetier serviceMetier= new ServiceMetierImpl();
public int getCodeClient() {
return codeClient;
}
public void setCodeClient(int codeClient) {
this.codeClient = codeClient;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getNumeroCompte() {
return numeroCompte;
}
public void setNumeroCompte(String numeroCompte) {
this.numeroCompte = numeroCompte;
}
public double getSolde() {
return solde;
}
public void setSolde(double solde) {
this.solde = solde;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public List<Client> getClientList() {
System.out.println("methode getClienList");
return clientList;
}
public void setClientList(List<Client> clientList) {
System.out.println("methode setClientList");
this.clientList = clientList;
}
public String init(){
// clientList = serviceMetier.getAllClient();
System.out.println("methode init ");
return SUCCESS;
}
public String afficher(){
clientList=serviceMetier.getAllClient();
// client=serviceMetier.getClient(9);
System.out.println("methode afficher "+clientList);
return SUCCESS;
}
public String ajouter(){
System.out.println("methode afficher "+clientList);
BanqueFactory banque=new BanqueFactory();
Compte compte=banque.buildCompte();
compte.setNumeroCompte(numeroCompte);
compte.setSolde(solde);
compte.setDateCreation(dateCreation);
Client client=banque.buildClient();
client.setCodeClient(codeClient);
client.setNom(nom);
client.setPrenom(prenom);
client.setAge(age);
client.setAdresse(adresse);
client.addCompte(compte);
serviceMetier.createClient(client);
clientList=serviceMetier.getAllClient();
return SUCCESS;
}
public String addCompte(){
System.out.println("methode addCompte");
/*
BanqueFactory banque=new BanqueFactory();
Compte compte=banque.buildCompte();
compte.setNumeroCompte(numeroCompte);
compte.setSolde(solde);
compte.setDateCreation(dateCreation);
Client client=banque.buildClient();
client.setCodeClient(codeClient);
client.setNom(nom);
client.setPrenom(prenom);
client.setAge(age);
client.setAdresse(adresse);
client.addCompte(compte);
serviceMetier.updateClient(client);
// if(codeClient>0){
// serviceMetier.updateClient(codeClient);
// codeClient=0;
// }
*/
client=serviceMetier.getClient(codeClient);
return SUCCESS;
}
public String update(){
client=serviceMetier.getClient(codeClient);
if(nom!=null){
client.setNom(nom);
}
if(prenom!=null){
client.setPrenom(prenom);
}
if(age!=0){
client.setAge(age);
}
if(adresse!=null){
client.setAdresse(adresse);
}
serviceMetier.updateClient(client);
return SUCCESS;
}
public String delete(){
System.out.println("methode delete");
// if(codeClient>0){
serviceMetier.deleteClient(codeClient);
// codeClient=0;
// }
clientList=serviceMetier.getAllClient();
return SUCCESS;
}
}
this my struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="struts-default" namespace="/">
<action name= "login" class="org.presentation.action.Account">
<result name="reussite" type="redirectAction">listClient</result>
<result name="echec">logging.jsp</result>
</action>
<action name="clientInit" class="org.presentation.action.ClientAction"
method="init">
<result name="success">index.jsp</result>
</action>
<action name= "addClient" class="org.presentation.action.ClientAction"
method="ajouter">
<result name="success">clientShow.jsp</result>
</action>
<action name="listClient" class="org.presentation.action.ClientAction"
method="afficher">
<result name="success">clientShow.jsp</result>
</action>
<action name="updateClient" class="org.presentation.action.ClientAction"
method="update">
<result name="success">client.jsp</result>
</action>
<action name="addCompteToClient" class="org.presentation.action.ClientAction"
method="addCompte">
<result name="success">client.jsp</result>
</action>
<action name="deleteClient" class="org.presentation.action.ClientAction"
method="delete">
<result name="success">clientShow.jsp</result>
</action>
</package>
</struts>
It's possible by using Struts2, jsp without javascript/jquery? if not how can I add jquery code in Struts2?
Ajax is not sending the data to the specified URL. Here is my controller:
#Controller
public class HomeController {
private List<User> userList = new ArrayList<User>();
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
public String showForm() {
return "AddUsers";
}
#RequestMapping(value = "User.htm", method = RequestMethod.POST)
public #ResponseBody
String addUser(#ModelAttribute(value = "user") User user,
BindingResult result) {
String returnText;
if (!result.hasErrors()) {
userList.add(user);
returnText = "User has been added to the list. Total number of users are"
+ userList.size();
} else {
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value = "ShowUsers.htm")
public String showUsers(ModelMap model) {
model.addAttribute("Users", userList);
return "ShowUsers";
}
}
AddUser.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function AjaxCall() {
alert('ready');
//get the form variables....
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "AddUsers.htm",
data: " name=" + name + "&education=" + education,
success: function (response) {
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('ERROR : ' + e);
}
});
}
</script>
<body>
<h1>Welcome to the AddUsers page. </h1>
<table>
<tr><td>Enter your name : </td><td> <input type = "text" id="name"></td></tr>
<tr><td>Educational qualification : </td><td> <input type = "text" id="education"></td></tr>
<tr><td colspan = "2"><input type="button" value="Add Users" onclick="AjaxCall()"></td></tr>
<tr><td colspan = "2"><div id ="info"></div></td></tr>
</table>
Show users
</body>
</html>
I have inserted an alert within the ajax which never comes up. So I believe there is something wrong with the ajax method.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have also created a domain class which would store the student information:
public class User {
private String name = null;
private String education = null;
public void SetName(String name) {
this.name = name;
}
public String GetName() {
return name;
}
public void SetEdu(String education) {
this.education = education;
}
public String GetEdu() {
return education;
}
}
There is also a warning:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with
URI [/sum/] in DispatcherServlet with name 'appServlet'>`
Dispatch servlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources
in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-
INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.faisal.sum" />
</beans:beans>
I corrected the upper case problem ($.ajax instead of $.Ajax). Thanks for pointing out.
Now I have a different error:
POST http://localhost:8080/sum/AddUsers.htm 405 (Method Not Allowed)
change url:"AddUsers.htm" to url: "${pageContext. request. contextPath}/AddUsers.htm" and try.
the url you are calling is this
type: "POST",
url: "AddUsers.htm",
Which is POST, the controller method is GET. Hecne the 405 error, method not supported.
You try to send POST request but mapped your method call with GET method
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
try to change RequestMethod.GET to POST
I have a DataList and Update Panel in my page. After implementation, I checked that the response is talking very long time after using Update panels...Here is the study material. I have a Delete Command event in Datalist and works find in the above mentioned case. I was trying to implement Delete Command using Page Methods. Any Idea how to do that?
I basically want to find hidden controls in this event and have to delete the record in `database. Any help will be highly appreciated.
Rest Services
The full application can be downloaded from:
http://sdrv.ms/LJJz1K
This sample uses rest services in ASP.Net (the same concepts can be applied to a MVC application)
The clearer advantage when using rest services vs page methods, is testability.
I will guide you step by step to configure the service:
You need the following references:
System.Web.ServiceModel.dll
System.Web.ServiceModel.Activation.dll
System.Web.ServiceModel.Web.dll
Nuget packages:
jQuery
jQuery plugins:
jQuery Block UI (it’s available as a single script file)
Service info
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "/DeleteFromService",
Method = "DELETE")]
void Delete(int id);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void Delete(int id)
{
// delete your product
// simulate a long process
Thread.Sleep(5000);
}
}
In Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Add(new ServiceRoute("",
new WebServiceHostFactory(),
typeof(MyService)));
}
In web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Register scripts (they can be registered in a master page)
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js" language="javascript" ></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery.blockui.1.33.js"></script>
In a ASP.Net content page (in this sample, I am using a master page)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Delete" id="myButton" />
</asp:Content>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" language="javascript">
function deleteFromService() {
if (!confirm("Are you sure you want to delete?")) {
return;
}
$.blockUI();
$.ajax({
cache: false,
type: "DELETE",
async: true,
url: "/DeleteFromService",
data: "3", // get your id to delete
contentType: "application/json",
dataType: "json",
success: function () {
$(document).ajaxStop($.unblockUI);
alert("done");
},
error: function (xhr) {
$(document).ajaxStop($.unblockUI);
alert(xhr.responseText);
}
});
}
jQuery().ready(function () {
$("#myButton").click(deleteFromService);
});
</script>
</asp:Content>
And that’s it, ajax commands the easy way =)