I was able to send a simple String from javascript/local html in Webview to Java.
How do I send the whole form object to Java ?
public class JFXTest1 extends Application {
WebView webview = new WebView();
webview.getEngine().load(JFXTest1.class.getResource("local1.html").toExternalForm());
JSObject jsobj = (JSObject) webview.getEngine().executeScript("window");
Local1JSBridge bridge = new Local1JSBridge();
bridge.setWindow(jsobj);
jsobj.setMember("java", bridge);
And my bridge.
public class Local1JSBridge {
public void printFormData(String data1){
System.out.println( data1);
}
}
The javascript part that calls the method in the Java class.
<html>
<head></head>
<body>
hi :)
<form id="form1" name="form1">
<input type="text" id="text1">text value</input>
</form>
<button onclick="java.printFormData(document.getElementById('text1').value);">Submit</button>
<br/>
<button onclick="java.exit()">Exit</button>
</body>
I can't find a way to actually get the form data without executing Javascript back in the HTML document, but the following seems to basically work:
public void printFormData(Object form) {
System.out.println(form.getClass() + " " + form);
if (form instanceof Element) {
NodeList inputs = ((Element)form).getElementsByTagName("input");
for (int i = 0 ; i < inputs.getLength(); i++) {
Node input = inputs.item(i);
Element inputEl = (Element)input ;
String id = inputEl.getAttribute("id");
String value = (String) engine.executeScript(id+".value");
System.out.printf("%s : %s %n", id, value);
}
}
}
and then in the HTML:
<html>
<head></head>
<body>
hi :)
<form id="form1" name="form1">
<input type="text" id="text1">text value</input>
</form>
<button onclick="java.printFormData(document.getElementById('form1'));">Submit</button>
<br/>
<button onclick="java.exit()">Exit</button>
</body>
</html>
Related
I am working with the registration processing using the spring security following the article of building https://github.com/Baeldung/spring-security-registration. As per this article, the HTML pages take the input and insert it into the database.
I am working with a Flutter application on the front-end. I want that when the user requests to reset password a link is sent to the email of a user and when the user clicks on the verification link it will create a session and redirect to the UI Page on the app to write the New Password. When the user enters the New Password it will update the password of that user.
updatePassword.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"/>
<style>
.password-verdict{
color:#000;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script th:src="#{/resources/pwstrength.js}"></script>
<title th:text="#{message.updatePassword}">update password</title>
</head>
<body>
<div sec:authorize="hasAuthority('CHANGE_PASSWORD_PRIVILEGE')">
<div class="container">
<div class="row">
<h1 th:text="#{message.resetYourPassword}">reset</h1>
<form>
<br/>
<label class="col-sm-2" th:text="#{label.user.password}">password</label>
<span class="col-sm-5"><input class="form-control" id="password" name="newPassword" type="password"
value=""/></span>
<div class="col-sm-12"></div>
<br/><br/>
<label class="col-sm-2" th:text="#{label.user.confirmPass}">confirm</label>
<span class="col-sm-5"><input class="form-control" id="matchPassword" type="password" value=""/></span>
<div id="globalError" class="col-sm-12 alert alert-danger" style="display:none"
th:text="#{PasswordMatches.user}">error
</div>
<div class="col-sm-12">
<br/><br/>
<button class="btn btn-primary" type="submit" onclick="savePass()"
th:text="#{message.updatePassword}">submit
</button>
</div>
</form>
</div>
</div>
<script th:inline="javascript">
var serverContext = [[#{/}]];
$(document).ready(function () {
$('form').submit(function(event) {
savePass(event);
});
$(":password").keyup(function(){
if($("#password").val() != $("#matchPassword").val()){
$("#globalError").show().html(/*[[#{PasswordMatches.user}]]*/);
}else{
$("#globalError").html("").hide();
}
});
options = {
common: {minChar:6},
ui: {
showVerdictsInsideProgressBar:true,
showErrors:true,
errorMessages:{
wordLength: /*[[#{error.wordLength}]]*/,
}
}
};
$('#password').pwstrength(options);
});
function savePass(event){
event.preventDefault();
$(".alert").html("").hide();
$(".error-list").html("");
if($("#password").val() != $("#matchPassword").val()){
$("#globalError").show().html(/*[[#{PasswordMatches.user}]]*/);
return;
}
var formData= $('form').serialize();
$.post(serverContext + "user/savePassword",formData ,function(data){
window.location.href = serverContext + "login?message="+data.message;
})
.fail(function(data) {
if(data.responseJSON.error.indexOf("InternalError") > -1){
window.location.href = serverContext + "login?message=" + data.responseJSON.message;
}
else{
var errors = $.parseJSON(data.responseJSON.message);
$.each( errors, function( index,item ){
$("#globalError").show().html(item.defaultMessage);
});
errors = $.parseJSON(data.responseJSON.error);
$.each( errors, function( index,item ){
$("#globalError").show().append(item.defaultMessage+"<br/>");
});
}
});
}
</script>
</div>
</body>
</html>
This will create the session and update the password perfectly.
But I want to send a post request and a newPassword to store in the database. But unable to create the session.
Controller.java
#RequestMapping(value = "/user/savePassword", method = RequestMethod.POST)
#ResponseBody
public String savePassword(#RequestParam("newPassword") String newPassword) {
final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
userService.changeUserPassword(user, newPassword);
return "Password has been changed successfully. ";
}
This
final User user = (User)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
is not creating the session of the user when I directly hit the URL from UI App.
Please tell me the way to do so.
it's hard to understand what happened wrong. If I understood correctly, and you follow this example https://www.baeldung.com/spring-security-registration-i-forgot-my-password is impeccable, then at the time of checking the token from the letter, you should have been authorized.
I guess, it should be here
public String validatePasswordResetToken(long id, String token) {
PasswordResetToken passToken =
passwordTokenRepository.findByToken(token);
if ((passToken == null) || (passToken.getUser()
.getId() != id)) {
return "invalidToken";
}
Calendar cal = Calendar.getInstance();
if ((passToken.getExpiryDate()
.getTime() - cal.getTime()
.getTime()) <= 0) {
return "expired";
}
User user = passToken.getUser();
Authentication auth = new UsernamePasswordAuthenticationToken(
user, null, Arrays.asList(
new SimpleGrantedAuthority("CHANGE_PASSWORD_PRIVILEGE")));
SecurityContextHolder.getContext().setAuthentication(auth); // authorization after validation of reset token
return null;
}
Please, give some more about your situation. Give me a full example of this. Or you just what to save a password directly?
How to pass text field value from jsp to java class.
my .jsp code is
<html>
<head></head>
<body>
<FORM>
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</body>
</html>
my .java class code is
here in string str i need to get the textfield value.
class sample{
String str=""; //C:/check/svntes
File exportDir = new File(str);
if (exportDir.exists()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Path ''{0}'' already exists", exportDir);
throw new SVNException(err);
}
exportDir.mkdirs();
}
Hmm .. let's assume how your jsp & java file interact with each other. Correct if im wrong.
A.jsp file
<html>
<head></head>
<body>
<FORM ACTION="B.JSP" METHOD="POST"> //edited part
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</body>
</html>
B.JSP
<jsp:useBean id="sample" scope="page" class="com.home.file.sample" /> // sample is java file name
String name = request.getParameter("text1");
int iRowAffected = 0;
//-------now pass parameter "name" to your sample java file
sample.function_name("name");
Sample.java
public class sample
{
public int function_name(String NAME)
{
String str = NAME;
File exportDir = new File(str);
if (exportDir.exists()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Path ''{0}'' already exists", exportDir);
throw new SVNException(err);
}
exportDir.mkdirs();
//continue with your coding
}
}
To passing value from JSP to Java, you need java Servlet.
Call servet from form tag and then get value using request.getParameter("your value") api of request object.
JSP Page:
<form action="HelloServlet" method="POST">
Please enter your name:
<input type="text" name="text1" id="text1">
<br>
<input type="submit" value="Submit">
</form>
Servlet :
public class HelloWorld extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// reading the user input
String text1= request.getParameter("text1");
}
}
Is your java class a servlet?
Because then you need to post to your servlet like this:
<form action="ServletName" method="GET">
Please enter your name:
<input type="text" name="text1" />
<br />
<input type="submit" value="Submit" />
</form>
And then in your servlet you can get the string value like this:
String str = request.getParameter("name");
name.jsp
<FORM action="/submitName" method="get">
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
First of all, in your above jsp file two things are missing action
and method(optional, by default it takes "get") attributes.
Now to get the input value in you java class, you need to write a Servlet class and configure it in the web.xml with a url mapping "/submitName".
MyServlet.java
// Import required java libraries
// Extend HttpServlet class
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("text1"); //should be same name as form input name
System.out.println(name);
}
}
web.xml will be as follows,
<web-app>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/submitName</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>name.jsp</welcome-file>
</welcome-file-list>
</web-app>
I got answer by this way..Its working fine.
my.jsp code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form >
Enter the word: <input type="text" name="word">
<input type="submit">
<%# page import = "dem.hashmap"%> <!-- //importing java class -->
<%
hashmap hm = new hashmap(); /* creating reference for my java class */
String inputvalue = request.getParameter("word");
String output = hm.dircreation(inputvalue); /* calling java method */
out.println(inputvalue);
%>
</body>
</html>
my hashmap .java class:
package dem;
import java.io.File;
public class hashmap {
String nav;
public String dircreation(String dir)
{
System.out.println("The Value is--------->"+dir);
boolean success = false;
File directory = new File(dir);
System.out.println("1....The Value is--------->"+dir);
if (directory.exists()) {
System.out.println("Directory already exists ...");
} else {
System.out.println("Directory not exists, creating now");
success = directory.mkdir();
if (success) {
System.out.printf("Successfully created new directory : %s%n", dir);
} else {
System.out.printf("Failed to create new directory: %s%n", dir);
}
}
return nav;
}
}
I was trying to make autocomplete in different ways, but nothing works at all.
From here and here
Hope you help me guys. I have a project that uses Spring MVC + jsp + hibernate. I want to create a search textbox, which also will be work as a autocomplete for Last Names of clients.
When I open a clients page with help of my Controller I send, via a model, a list with clients and list with Last Names, the last one for autocomplete.
Here is my controller:
#Controller
#RequestMapping("/clients")
public class ClientsController {
#Autowired
public ClientsService clientsService;
#Autowired
private ServicesService servicesService;
#Autowired
private OrdersService ordersService;
#Autowired
private Order_serviceService order_serviceService;
#Autowired
private ObjectMapper objectMapper;
#RequestMapping(method = RequestMethod.GET)
public String listClients(Model model) {
List<Clients> allClients = clientsService.listClients(
new RequestAllClientsEvent()).getClients();
List<String> lastNamesList = new ArrayList<>();
for(int i = 0; i < allClients.size(); i++){
lastNamesList.add(allClients.get(i).getLast_name());
}
Collections.sort(lastNamesList);
String json = "";
try{
json = objectMapper.writeValueAsString(lastNamesList);
} catch(Exception e){}
model.addAttribute("clientsList", allClients);
model.addAttribute("lastNamesList", json);
return "clients";
}
Then in jsp page I want to add some how my lastNamesList to the script source:
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"> </script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script>
$(function() {
$( "#query" ).autocomplete({
source: lastNamesList
});
});
</script>
</head>
my input textbox is:
<div class="ui-widget">
<input class="form-control" type="search" id="query" name="query" required>
</div>
I thought I could get something like that if I just write source: lastNamesList :
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
Could you please help me to do this in right way. It would be great if I could be able to use list or array from my controller.
Thanks.
upd.changed my controller, added json conversion, but it didnt help. Looks like scripts dont work on my page...confused even more O_o
upd. here is my working code:
Controller:
#RequestMapping(value = "/searchlastname", method = RequestMethod.GET, headers = "Accept=*/*")
public
#ResponseBody
List<String> searchLastName(#RequestParam("term") String query) {
List<Clients> clientsList = clientsService.searchClient(new SearchClientEvent(query)).getClients();
List<String> lastnameList = new ArrayList<>();
System.out.println("Found clients size: " + clientsList.size());
for (Clients clients : clientsList) {
lastnameList.add(clients.getLast_name());
}
Collections.sort(lastnameList);
return lastnameList;
}
script:
$(document).ready(function () {
$("#lastNameAuto").autocomplete({
source: 'clients/searchlastname'
});
});
in jsp:
<form class="form-horizontal" role="form" action="<c:url value="/clients/search"/>" method="get">
<div class="input-group input-group-sm">
<span class="input-group-addon"><spring:message code="label.enterClientInfo"/></span>
<input class="form-control" type="search" id="lastNameAuto" name="query" required>
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<spring:message code="label.searchClient"/>
</button>
</span>
</div>
</form>
Hope it helps someone else! ;)
From your update ,
You should have a model class and do a explicit conversion to send the json object. either using gson library or you can go with the existing method by sending the list .
For a beginner i would advise to learn from the nice example here
Hope this helps !!
I render a TextField. It's value is populated by script, not the user. I need to get that value from Java but I get null by doing textField.getInput();
Any ideas how to get that value and use it in Java code?
I had the same problem a few month ago. One problem is, that setting the input value via javascript doesn't fire the "onChange" event which you could easily use to get the value.
The solution I implemented might not be the easiest one, but it's working:
put a form with a hidden ajax submit link around your input
when you fill your input with javascript, use javascript also to do a form submit
html:
<html xmlns:wicket="http://wicket.apache.org">
<body>
<div>
<a href="#" onclick="document.getElementById('input').value = 'test'; document.getElementById('myForm').submit();">fill
input</a>
<form wicket:id="form" id="myForm">
<input type="text" wicket:id="input" id="input">
<a style="visibility: hidden;" wicket:id="submit">submit</a>
</form>
<p> Output:
<wicket:container wicket:id="output"></wicket:container>
</p>
</div>
</body>
</html>
and the corresponding java:
public class HomePage extends WebPage {
private String inputValue;
public HomePage(final PageParameters parameters) {
super(parameters);
final Label output = new Label("output", new PropertyModel<String>(
this, "inputValue"));
output.setOutputMarkupId(true);
add(output);
Form form = new Form("form");
form.add(new AjaxSubmitLink("submit") {
#Override
protected void onAfterSubmit(AjaxRequestTarget target, Form<?> form) {
super.onAfterSubmit(target, form);
target.add(output);
}
});
add(form);
form.add(new TextField<String>("input", new PropertyModel<String>(this,
"inputValue")));
}
}
Explanation:
The TextField gets an AjaxFormSubmitBehaviour with a custom event.
This event can be triggered by javascript. I use jQuery, as it is provided by Wicket anyway.
See the code:
public class Example extends WebPage
{
public Example(PageParameters pp)
{
super(pp);
final Model<String> m = new Model<String>("");
Form<Void> f = new Form<Void> ("form");
TextField<String> textField = new TextField<String>("textField", m, String.class);
textField.setOutputMarkupId( true );
textField.setMarkupId( "myuniqueid" );
textField.add( new AjaxFormSubmitBehavior("customevent")
{
protected void onSubmit(AjaxRequestTarget target)
{
System.out.println("Model value:"+m.getObject());
target.add( this.getComponent() );
}
} );
f.add(textField);
add(f);
}
}
HTML
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
</head>
<body>
<a href="#" onclick="$('#myuniqueid').val('test'); $('#myuniqueid').trigger('customevent');">fill
input</a>
<form wicket:id="form">
<input wicket:id="textField"></input>
</form>
</body>
</html>
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am developing a web application in JSP. I made this page with JSP, CSS and HTML. There are six buttons. Every button calls a JavaScript method, so the first button is a call of the par() method.
<html>
<head>
<title>Welcome d To Student University</title>
<link rel="stylesheet" type="text/css" href="../css/stlogin.css">
<link rel="stylesheet" type="text/css" href="../css/background.css">
<link rel="stylesheet" type="text/css" href="../css/back.css">
<script src="StInfo.jsp">
</script>
</head>
<body>
<div class=main>
<div class=blank></div>
<div class=welcome><h1 class=welcome><center>Welcome Student</center></h1>
<div class=logout><a href='logout.jsp?value=st'>Logout</a></div></div>
</div>
<br>
<div class=menu>
<div class=leftgap>.
</div>
<div class=option>
<center>
<button type="button" onclick=par() class="Bt_menu">Check Parsnal Info</button>
</center>
</div>
<div class=option>
<center>
<button type="button" onclick=faculty() class="Bt_menu">All Faculty Details</button>
</center>
</div>
<div class=option>
<center>
<button type="button" onclick=exam() class="Bt_menu">Next Exams Details</button>
</center>
</div>
<div class=option>
<center>
<button type="button" onclick=atten() class="Bt_menu">Attendance Details</button>
</center>
</div>
<div class=option>
<center>
<button type="button" onclick=Result() class="Bt_menu">Exam Result Details</button>
</center>
</div>
<div class=option>
<center>
<button type="button" onclick=Notices() class="Bt_menu">College Notices / Details</button>
</center>
</div>
</div>
<p id=Table></p>
</body>
</html>
in this page i used this script tage as :-
<script src="StInfo.jsp">
</script>
now i show u my StInfo.jsp file there are the java script method .
<%#page import="data.*;" %>
<%
ServletConfig con=getServletConfig();
ServletContext ctx=con.getServletContext();
DataRet d;
%>
function par()
{
try
{
// i sat ctx.setAttribute("id") is 1 already in my last page . so the output will be 1 of it .
<%DataRet.setAtt(""+ctx.getAttribute("id"),"stlogin");%>
var id=<%=ctx.getAttribute("id")%> // if i did that than the value 1 store in id .
var id=<%=DataRet.get(2)%> // but when i did that nething happen and code didn't work .
}catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
//alert("id");
document.getElementById("Table").innerHTML="<center><table border='10'><th>College Id</th> <th>Name</th><th>Father Name</th><th>Department</th><th>Year</th><th>Semester</th><th>Ph. No.</th><th>Address</th>\
<tr>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
</tr></table><center>";
}
and here is my DataRet File ---
package data;
import java.sql.*;
import connection.connection;
public class DataRet
{
static Connection c;
static ResultSet re;
static Statement s;
static String id;
static
{
try
{
c=connection.getConnect();
System.out.println(c);
s = c.createStatement();
System.out.println("Statement Object Created = "+s);
}catch(Exception e){System.out.println(e);}
}
public static void setAtt(String table)
{
try{
re=s.executeQuery("select * from "+table);
}catch(Exception e){}
}
public static void setAtt(String att,String table)
{
System.out.println("Table Sated");
id=att;
int i=0;
try
{
re=s.executeQuery("select * from "+table);
while(re.next() && re.getString(3).equals(att))
{
i++;
break;
}
System.out.println("curser on "+i);
}catch(Exception e){System.out.println(e);}
}
public static void change()
{
try{
re.next();
}catch(Exception e){}
}
public static String get(int val)
{
System.out.println("value geted of "+val);
try{
String o=re.getString(val);
//o=string.valueOf(o);
System.out.println(o);
return o;
}catch(Exception e){ System.out.println("Problum in Geting Value"+e);}
System.out.println("return null");
return null;
}
}
Now the question is that when i call a method *<%=ctx.getAttribute("id")%> * in stInfo.jsp then this method print 1 in very coloum . and when i call
<%=DataRet.get(2)%> method then file didn't work ....
The storing of data from a JSP scriptlet should be pretty straight forward just like you have it.
var id=<%=ctx.getAttribute("id")%>
Although I would recommend you to be careful with the returning data, if it isn't a number for sure, then you must put it between quotes just to be sure the JS doesn't break. For example:
if <%=DataRet.get(2)%> returns a string "TEST" then the resulting JS would look like:
var id=TEST
And that would just simply break because there is no variable named TEST. You need to enclose it in double or single quotes like:
var id="<%=DataRet.get(2)%>";
Also you have to keep in mind the semicolons at the end of every line, and escape any possible chars that can break the JS code. Remember, the JS code has not been executed yet after the JSP has compiled, so it is like if you wrote that JS code manually.
If this code is not working start by checking what <%=DataRet.get(2)%> is returning, and also if there are any JS errors.
Hope it helps.