Pass selected value from dropdown using JSP - java

I need to implement some basic dropdown using jsp and java, but I can't find more info how to do that. So I never write something using JSP and when I didnt find nothing that help the last options for me was to ask.
I want to get the selected value and when click the button to send the value to anoher .jsp file ("selector.jsp in my case")
Please folks help me with some easy solution.
p.P.: Sorry for my english (:
index.jsp
<FORM method="post" action="selector.jsp">
<select name="select" id="dropdown">
<%
Test t = new Test();
t.getList().add("a");
t.getList().add("b");
t.getList().add("c");
for(int i=0; i < t.getList().size(); i++){
%>
<Option value="<%t.getList().get(i);%>"><%=t.getList().get(i)%></Option>
<%}%>
</select>
<input type="submit" value="click">
selector.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
You selected:
<%
request.getParameter("select");
request.getParameterValues("select");
%>
</body>
</html>

I found a solution by removing
value="<%t.getList().get(i);%>"
from and leave the code just with
<Option><%=t.getList().get(i)%></Option>
but i don't know why... if someone can explain will be great.
Thx! (:

As you have indicated in your post, the problem is solved by replacing
value="<%t.getList().get(i);%>"
with
<Option><%=t.getList().get(i)%></Option>
The reason that works is as follows:
In your first form, <%t.getList().get(i);%>, you have a JSP scriptlet. This is Java code that is executed inline. In your case, this executes the "get" method. Note however that the get method returns a value, but this value is not output into the response stream.
In your second form, you have formed a JSP expression by using "<%=". "<%=" is shorthand for "out.println", thus you have provided shorthand for the following:
<Option><% out.println(t.getList().get(i)) %></Option>
This writes the return value of the method call to the output stream. So that when this output reaches the browser, there is an actual value within the Option tags.

Related

List with springboot and thymeleaf

I am trying to get a list of objects that are sent to the server from the html form as parameters for my list, then I will loop through those entries and then return them through the springboot th:each. But it doesn't seem to be working at all. On load the form appears but when I enter a value in it, then it returns an error page and the URL however turns:
http://localhost:8080/#%7B/%7D?%24%7Bcontent%7D=hello
this output in eclipse says:
Expression "content" is not valid: only variable expressions ${...} or selection expressions *{...} are allowed in Spring field bindings
Note: content here is the value property in my form.
My controller looks like this:
#Controller
public HelloList() {
this.addUs = new ArrayList <>();
}
#RequestMapping("/")
public String getlist(#RequestParam (required = false) String content, Model model) {
if (content != null && !content.trim().isEmpty()) {
this.addUs.add(content);
}
model.addAttribute("list",addUs);
return "index";
}
the index.html looks like this
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
</head>
<body>
<div>
<ul>
<li th:each="amHere: ${addUs}">
<span th:text="${amHere}">hello! world</span>
</li>
</ul>
<form action="#{/}" method="GET">
<input type="text" name="content"/>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
</html>
This might be a duplicate but it seems like most of the solutions I came across are not helping. So any help is mostly appreciated. Thank you in advance.
Turns out I was missing the initialization of my list in the constructor. I initialized the list by adding a value to it first in the constructor like this.
this.addUs.add("Hello World");
Because the #RequestMapping is mapped to the home path in my case index.html, any request gets sent there automatically.
working example
action = "#{/}" should be th:action="#{/}". That's the reason you're seeing the weird url (because it's url encoding #{/}). Thymeleaf only evaluates expressions that start with th:.
I'm not sure about the other error. It looks like the html you've pasted doesn't match up with the error you are getting.
If you urldecode http://localhost:8080/#%7B/%7D?%24%7Bcontent%7D=hello, you get http://localhost:8080/#{/}?${content}=hello, which doesn't line up with your form.

How to solve HTTP Status 404

I'm trying to write a simple web app in JSP that allows user to choose 2 numbers in the range 1-100 from 2 drop-down lists and then print out those numbers. However, I keep receiving the error message:
Below is my code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Game Table</title>
</head>
<body>
<form method="post">
#rows:
<select name="row">
<%
for(int i=1;i<=100;i++){
out.println("<option value="+"\""+i+"\""+">"+i+"</option>");
}
%>
</select>
#columns:
<select name="column">
<%
for(int i=1;i<=100;i++){
out.println("<option value="+"\""+i+"\""+">"+i+"</option>");
}
%>
</form>
<%
String row=request.getParameter("row");
String column=request.getParameter("column");
if(row!=null && column!=null){
out.println(row+" "+column);
}
%>
</body>
Thank you so much
well, problem is in navigation not in your code. For not showing dropdown menu so use proper url mapping to run your jsp like http://localhost:8080/yourwebprojectname/game.jsp game.jsp is assumption of your following above code page name.
Your code have many error like missing of action="" like
<form method="post" action="book.jsp">
</Select> tag above the form
Main problem is you dont have any button or use of ajax to show the output that you trying to display via Scriptlet
for simple solution add a button inside your form
<input type="submit" value="show" name="show"/>
add code something like this inside your Scriptlet
if("show".equals(request.getParameter("show"))){
if(row!=null && column!=null){
out.println(row+" "+column);
}
}
I am not completely sure, but it might be returning 404 (not found) because you are not submitting this data correctly. See, there is no "action" atribute indicating where it should go (e.g. "save.jsp").
Hope it helps! :)

How to parse a webpage that includes Javascript? [duplicate]

This question already has answers here:
Parse JavaScript with jsoup
(2 answers)
Closed 9 years ago.
I've got a webpage that creates a table using Javascript. Right now I'm using JSoup in my Java project to parse the webpage. By the way JSoup isn't able to run Javascript so the table isn't generated and the source of the webpage is incomplete.
How can I include the HTML code created by that script in order to parse its content using JSoup? Can you provide a simple example? Thank you!
Webpage example:
<!doctype html>
<html>
<head>
<title>A blank HTML5 page</title>
<meta charset="utf-8" />
</head>
<body>
<script>
var table = document.createElement("table");
var tr = document.createElement("tr");
table.appendChild(tr);
document.body.appendChild(table);
</script>
<p>First paragraph</p>
</body>
</html>
The output should be:
<!DOCTYPE html>
<html>
<head>
<title>
A blank HTML5 page
</title>
<meta charset="utf-8"></meta>
</head>
<body>
<script>
var table = document.createElement("table");
var tr = document.createElement("tr");
table.appendChild(tr);
document.body.appendChild(table);
</script>
<table>
<tr></tr>
</table>
<p>
First paragraph
</p>
</body>
</html>
By the way, JSoup doesn't include the table tag as it isn't able to execute Javascript. How can I achieve this?
First possibility
You have some options outside Jsoup, i.e. employing a "real" browser and interact with it. An excellent choice for this would be selenium webdriver. With selenium you can use different browsers as back end, and maybe in your case the very lightweight htmlUnit would do already. If more complicated JavaScript is called there is often no other choice then running a full browser. Luckily, phantomjs is out there and its footprint is not too bad (headless and all).
Second possibility
Another approach could be that you grab the javascript source with JSoup and start a JavaScript interpreter within Java. For that you could use Rhino. However, if you go that path you might as well use HtmlUnit directly, which is probably a bit less bulky.

Multiple body tags in Sitemesh 3

I have been using Sitemesh 3 for my project and so far it's been working great. Recently I came across a situation where I am stuck.
My final view has to be composed of 2 html files, both have their own and tags.
File1:
<html>
<head>Head1</head>
<body>body1</body>
</html>
File2:
<html>
<head>Head2</head>
<body>body2</body>
</html>
I am composing a view using freemarker include tag. So, the composed HTML looks like:
<html>
<head>Head1</head>
<body>body1</body>
</html>
<html>
<head>Head2</head>
<body>body2</body>
</html>
Following is my decorator:
<html>
<head>
<sitemesh:write property='head'/>
</head>
<body>
<div class="container">
<sitemesh:write property='body'/>
</div>
</body>
</html>
But once decorated, the final output I am getting is:
<html>
<head>
<head>Head1</head>
</head>
<body>
<div class="container">
<body>body1</body>
</div>
</body>
</html>
But the expected output is
<html>
<head>
<head>
Head1
Head2
</head>
</head>
<body>
<div class="container">
body1
body2
</div>
</body>
</html>
I came across a similar question, but that solution won't work for me because I don't want to create multiple decorators.
I just want to know if it's possible in Sitemesh 3. If yes, then how.
Thanks.
If you don't mind extending Sitemesh 3 then this is fairly easy to do by adding support for server side includes in your decorator template. I do exactly this in another library (UtterlyIdle).
I'm using StringTemplate as my decorator language but this should work in Freemarker or any other templating tool. I add in a PageMap and then in my decorator template call
$include("someUrl").body$
This does a include and then parses the output with the Sitemesh 3 engine. This allows you to have as many includes as you like.
Hope that makes sense

Reading a JSP variable from JavaScript

How can I read/access a JSP variable from JavaScript?
alert("${variable}");
or
alert("<%=var%>");
or full example
<html>
<head>
<script language="javascript">
function access(){
<% String str="Hello World"; %>
var s="<%=str%>";
alert(s);
}
</script>
</head>
<body onload="access()">
</body>
</html>
Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities
The cleanest way, as far as I know:
add your JSP variable to an HTML element's data-* attribute
then read this value via Javascript when required
My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.
The HTML part without JSP:
<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
Here is your regular page main content
</body>
The HTML part when using JSP:
<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
Here is your regular page main content
</body>
The javascript part (using jQuery for simplicity):
<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var valuePassedFromJSP = $("body").attr("data-customvalueone");
var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");
alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>
And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/
Resources:
HTML 5 data-* attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Include javascript into html file Include JavaScript file in HTML won't work as <script .... />
CSS selectors (also usable when selecting via jQuery) https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
Get an HTML element attribute via jQuery http://api.jquery.com/attr/
Assuming you are talking about JavaScript in an HTML document.
You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.
You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.
The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:
<script type="text/javascript">
var myObject = <%= the string output by the JSON library %>;
</script>
This will give you an object that you can access like:
myObject.someProperty
in the JS.
<% String s="Hi"; %>
var v ="<%=s%>";
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
<title>JSP Page</title>
<script>
$(document).ready(function(){
<% String name = "phuongmychi.github.io" ;%> // jsp vari
var name = "<%=name %>" // call var to js
$("#id").html(name); //output to html
});
</script>
</head>
<body>
<h1 id='id'>!</h1>
</body>
I know this is an older post, but I have a cleaner solution that I think will solve the XSS issues and keep it simple:
<script>
let myJSVariable = <%= "`" + myJavaVariable.replace("`", "\\`") + "`" %>;
</script>
This makes use of the JS template string's escape functionality and prevents the string from being executed by escaping any backticks contained within the value in Java.
You could easily abstract this out to a utility method for re-use:
public static String escapeStringToJS(String value) {
if (value == null) return "``";
return "`" + value.replace("`", "\\`") + "`";
}
and then in the JSP JS block:
<script>
let myJSVariable = <%= Util.escapeStringToJS(myJavaVariable) %>;
</script>
The result:
<script>
let myJSVariable = `~\`!##$%^&*()-_=+'"|]{[?/>.,<:;`;
</script>
Note: This doesn't take separation of concerns into consideration, but if you're just looking for a simple and quick solution, this may work.
Also, if you can think of any risks to this approach, please let me know.

Categories