This question already has an answer here:
Set String to clickable URL
(1 answer)
Closed 6 years ago.
What I mean is, when the user search a particular stuff, for instance Supreme,
It will print out supremenewyork.com , Supreme, A skateboarding shop/clothing brand[1][2] established in New York City in April 1994.
How do I make the text supremenewyork.com become an URL. Basically I get the parameter from servlet and printed on a JSP result page. Based by what I know it cannot be done in the Solr side.
Any expert in Solr able to give me a solution?
Below is my following code.
System.out.println("request parameter: "
+ request.getParameter("search"));
PrintWriter out = response.getWriter();
try {
HttpSolrServer solr = new HttpSolrServer("http://localhost:8983/solr/Corename/");
SolrQuery query = new SolrQuery();
String test;
// Getting the parameter from the textbox name search
query.setQuery(request.getParameter("search"));
query.setFields("id", "content");
query.setStart(0);
QueryResponse response1 = solr.query(query);
SolrDocumentList results = response1.getResults();
for (int i = 0; i < results.size(); ++i) {
test = results.toString();
String testresults = test.replace("numFound=2,start=0,docs=[","");
testresults = testresults.replace("numFound=1,start=0,docs=[","");
testresults = testresults.replace("numFound=4,start=0,docs=[","");
testresults = testresults.replace("SolrDocument{", "");
testresults = testresults.replace("content=[", "");
testresults = testresults.replace("id=", "");
testresults = testresults.replace("]}]}", "");
testresults = testresults.replace("]}", "");
request.setAttribute("testresults", testresults);
System.out.println(testresults);
request.getRequestDispatcher("Results.jsp").forward(request,
response);
}
} catch (SolrServerException se) {
se.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
JSP Code:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>THE SUPER SEARCH</title>
</head>
<body>
<h4>Here's the following results</h4>
<%String testresults=(String)request.getAttribute("testresults");
out.print("" + testresults);
%>
</body>
</html>
I discourage to do this thing directly in Solr, IMHO it is like to ask MySql to store a string and return a url.
Anyway, if you really want do this with Solr, there are many ways:
use Solr DocTransformers
format the output of one or more fields, I suggest to use XSLTResponseWriter which can return also json.
add to your Solr instance your own SearchComponent, here is an interesting post and here.
another way I know is Alba, Solr Plugins made easy.
At last, if you really want have back a ulr, you could just store the url in a field during the indexing.
UPDATE
Looking at code you have posted, the biggest problem I see is the way you're using to iterate on the returned results set. You should do something like this:
for (SolrDocument d : response1.getResults()) {
String content = (String) d.get("content");
long id = (long) d.get("id");
}
A Solrdocument internally is a LinkedHashMap.
Related
I have search the net, but cannot seems to find the solutions on how to do Solr highlight function. I am using java eclipse jsp & servlets.
F.Y.I I am using Solr 5
My objective is when user search the words "Hello" The word hello will be highlighted.
For example: Hello I suck at programming!
Any expert in Solr can give me some solution? I am sure that people will down vote my question. But I got to give it a try.
Here is the my code that I have tried. I had commented SOLR highlight in the following code how any expert in Solr can take it a look and tell me what I should do next. Also wish that some expert in Solr can share their source code if they done something like this before.
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
MalformedURLException {
System.out.println("request parameter: "
+ request.getParameter("search"));
PrintWriter out = response.getWriter();
try {
HttpSolrServer solr = new HttpSolrServer("http://localhost:8983/solr/name/");
SolrQuery query = new SolrQuery();
String test;
String content;
//SOLR HIGHLIGHT
query.set("hl", "true");
query.set("hl.snippets", "1");
query.set("hl.simple.pre", "<em>");
query.set("hl.requireFieldMatch","true");
query.set("q", "value:supreme");
query.set("hl.fl", "id,content");
query.setQuery(request.getParameter("search"));
query.setFields("id");
query.setStart(0);
QueryResponse response1 = solr.query(query);
SolrDocumentList results = response1.getResults();
for (int i = 0; i < results.size(); ++i) {
test = results.toString();
As per the snippet you have provided you are searching on field supreme but wish to highlight fields id and content. As far as I know, highlighting allows you to highlight the field on which match was found.
Try highlighting supreme and check the results.
Also highlighting results can be had from calling getHighlighting()
QueryResponse response1 = solr.query(query);
response1.getHighlighting()
You're searching in the field value, but you're only asking for highlighting to be performed on the fields id and content.
query.set("hl.requireFieldMatch","true");
query.set("q", "value:supreme");
query.set("hl.fl", "id,content");
Since you're also telling Solr to only highlight in fields where there's a match, no highlighting will take place. You'll have to either include the field you're expecting the match in (value) in your hl.fl list, or you'll might have to drop the hl.requireFieldMatch setting (possibly depending on the analysis chain and how the fields are indexed).
Use this for highlighting:
String searchTerm="harry",result=results.toString();
Pattern pattern = Pattern.compile("(" +
Pattern.quote(searchTerm.toLowerCase()) + ")",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
result = pattern.matcher(result.toString()).replaceAll("<strong>$1</strong>");
results=results.add(result);
System.out.println(result);*/
This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
doGet and doPost in Servlets
(5 answers)
Closed 1 year ago.
I'm new to JSP/Servlet based web programming. I am currently following some tutorials of servlet and JSP but I found some of the example given doesn't make too much sense for me, for example, in one of the examples of servlet chapter, a servlet look like this:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");
}
}
To me, the way of displaying the html content is ugly. So I am wondering whether there is a way to make servlet return an object (or a primitive data type) as response, and the front-end part (jsp) use this object to render html content on the browser. I did some research and found out using
request.setAttribute();
is one of implementation of sending an object as response back to client. So I wrote the following servlet, I just paste a snippet of it:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Driver manager and DB url:
final String jdbcDriver = "com.mysql.jdbc.Driver";
final String DBUrl = "jdbc:mysql://localhost/zoo";
// DB credentials:
final String userName = "username";
final String password = "password";
//DB Query:
final String sql = "SELECT name FROM pet WHERE age=10;";
//Response ArrayList:
ArrayList<String> nameList = new ArrayList<String>();
try {
// Register a DB Driver:
System.out.println("Registering Driver.......");
Class.forName(jdbcDriver).newInstance();
// Open a connection:
System.out.println("Openning conncetion.......");
Connection conn = DriverManager.getConnection(DBUrl, userName, password);
// Execute a query:
System.out.println("Executing query.......");
Statement stmt = conn.createStatement();
// Store the result in ResultSet:
System.out.println("Loading the result......");
ResultSet rs = stmt.executeQuery(sql);
// Extract data from ResultSet:
System.out.println("Extracting data.......");
while (rs.next()) {
nameList.add(rs.getString("name"));
}
} ...some catch statement
request.setAttribute("nameList", nameList);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
So basically this is JDBC is to extract all the pets' names whose age is 10, then store names in a ArrayList of String. I used setAttribute to store this ArrayList and make the index.jsp to handle this response. The index.jsp looks like this:
<%# page import="java.io.*,java.util.*"%>
<html>
<body>
<jsp:include page = "/GetPet" flush = "true" />
<%
ArrayList<String> nameList = request.getAttribute("nameList");
for (String name : nameList) {
out.write("<p>" + name + "</p");
}
%>
</body>
</html>
However, I got an error:
An error occurred at line: 6 in the jsp file: /index.jsp
Type mismatch: cannot convert from Object to ArrayList
So I'm wondering does anyone know:
What's going wrong on this specific error.
What is the best way to make JSP and servlet interact with each other? How the response from servlet be like? How JSP should handle this response?I don't want to write all the html markup in the servlet apparently.
Any hint/article/code example/blog will be greatly appreciated.
I have achieved sending an integer variable to a jsp page using the following code:
resp.sendRedirect(("result.jsp?fibNum=" + fibNum));
But when I try the same to pass the array, int[] fibSequence I get the following passed to the address bar of the jsp page:
Does anyone have any advice on how I can output the array value passed over to the jsp page?`
This is how I sent the array across to the result jsp page within the doPost():
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
// read form fields
String fibNum = req.getParameter("fibNum");
try{
//Get reference from server's registry
Registry registry = LocateRegistry.getRegistry("127.0.0.1");
//Lookup server object from server's registry
IFibonacci fibonacci_proxy = (IFibonacci)registry.lookup("PowerObject");
int fibMax = Integer.parseInt(fibNum);
//Invoke server object's methods
//Get Fibonacci array.
int[] fibSequence = fibonacci_proxy.fibonacciArrayTest(fibMax);
for (int value : fibSequence) {
System.out.println(value);
}
//System.out.println(Arrays.toString(fibSequence));
}catch(NotBoundException nbe){
nbe.printStackTrace();
}catch(RemoteException re){
re.printStackTrace();
}
//send input to the result page using a redirect
//resp.sendRedirect(("result.jsp?fibNum=" + fibNum));
resp.sendRedirect(("result.jsp?fibSequence=" + fibSequence));
}
How I've tried to retrieve the array values on the jsp page and print them, but I'm getting a fibSequence cannot be resolved to a variable although this is the name of the array passed over:
Return to Main<br>
<%String[] var_array=request.getParameterValues("fibSequence");%>
<%System.out.print(""+fibSequence);%>
</form>
Trust the compiler. fiBSeq ist not defined. You defined fibSequence. But passing that array as an argument will not work, because you will pass (int[]).toString() which is probably not what you want. You can serialize and encode it, if it is not too big. Or post it.
EDIT 1
int [] array = {1,2,3,4,5,6,7,8,9};
System.out.print(""+array);//<-- print [I#15db9742 or similar
EDIT 2
Encoding the array on the sender side
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
String param = Arrays.toString(array);
param = param.substring(1, param.length()-1);//removing enclosing []
String encArray = URLEncoder.encode(param, "utf-8");
// Send encArray as parameter.
resp.sendRedirect(("result.jsp?fibSequence=" + encArray));
Decoding the array on the receiver side
String encArray = request.getParameterValues("fibSequence");
String decArray = URLDecoder.decode(encArray,"utf-8");
//Now you can parse the list into an Integer list
String [] var_array = decArray.split(",");
In jsp, put the code between <% ... %>. If you get some unresolved symbol errors you have to import the missing libraries.
Can be one or more of the following, simply copy the statements at the top of the page.
<%# page import="java.io.*" %>
<%# page import="java.net.*" %>
<%# page import="java.util.*" %>
(maybe java.util is imported per default, I am not sure)
BUT ATTENTION
Be aware of not sending too much data in this manner! The size of an URL maybe is not unlimited. Also the data is visible in the URL, a 'nasty' user could simply copy and reproduce requests.
A better way to send data is using HTTP post.
Here is the better answer to transfer array variable from servlet to jsp page:
In Servelet:
String arr[] = {"array1","array2"};
request.setAttribute("arr",arr);
RequestDispatcher dispatcher = request.getRequestDispatcher("yourpage.jsp");
dispatcher.forward(request,response);
In Jsp:
<% String str[] = (String[]) request.getAttribute("arr"); %>
<%= str[0]+""+str[1] %>
I need a regex pattern for finding web page links in HTML.
I first use #"(<a.*?>.*?</a>)" to extract links (<a>), but I can't fetch href from that.
My strings are:
<a href="www.example.com/page.php?id=xxxx&name=yyyy" ....></a>
<a href="http://www.example.com/page.php?id=xxxx&name=yyyy" ....></a>
<a href="https://www.example.com/page.php?id=xxxx&name=yyyy" ....></a>
<a href="www.example.com/page.php/404" ....></a>
1, 2 and 3 are valid and I need them, but number 4 is not valid for me
(? and = is essential)
Thanks everyone, but I don't need parsing <a>. I have a list of links in href="abcdef" format.
I need to fetch href of the links and filter it, my favorite urls must be contain ? and = like page.php?id=5
Thanks!
I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href attribute of each links. It will match whether double or single quotes are used.
<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1
You can view a full explanation of this regex at here.
Snippet playground:
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;
const textToMatchInput = document.querySelector('[name=textToMatch]');
document.querySelector('button').addEventListener('click', () => {
console.log(textToMatchInput.value.match(linkRx));
});
<label>
Text to match:
<input type="text" name="textToMatch" value='<a href="google.com"'>
<button>Match</button>
</label>
Using regex to parse html is not recommended
regex is used for regularly occurring patterns.html is not regular with it's format(except xhtml).For example html files are valid even if you don't have a closing tag!This could break your code.
Use an html parser like htmlagilitypack
You can use this code to retrieve all href's in anchor tag using HtmlAgilityPack
HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);
var hrefList = doc.DocumentNode.SelectNodes("//a")
.Select(p => p.GetAttributeValue("href", "not found"))
.ToList();
hrefList contains all href`s
Thanks everyone (specially #plalx)
I find it quite overkill enforce the validity of the href attribute with such a complex and cryptic pattern while a simple expression such as
<a\s+(?:[^>]*?\s+)?href="([^"]*)"
would suffice to capture all URLs. If you want to make sure they contain at least a query string, you could just use
<a\s+(?:[^>]*?\s+)?href="([^"]+\?[^"]+)"
My final regex string:
First use one of this:
st = #"((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+ \w\d:##%/;$()~_?\+-=\\\.&]*)";
st = #"<a href[^>]*>(.*?)</a>";
st = #"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)";
st = #"((?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)[\w\d:##%/;$()~_?\+,\-=\\.&]+)";
st = #"(?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)";
st = #"(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+)|(www\.)[\w\d:##%/;$()~_?\+-=\\\.&]*)";
st = #"href=[""'](?<url>(http|https)://[^/]*?\.(com|org|net|gov))(/.*)?[""']";
st = #"(<a.*?>.*?</a>)";
st = #"(?:hrefs*=)(?:[s""']*)(?!#|mailto|location.|javascript|.*css|.*this.)(?.*?)(?:[s>""'])";
st = #"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = #"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
st = #"(http|https)://([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = #"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])?)";
st = #"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = #"http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
st = #"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*";
my choice is
#"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*"
Second Use this:
st = "(.*)?(.*)=(.*)";
Problem Solved. Thanks every one :)
Try this :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var res = Find(html);
}
public static List<LinkItem> Find(string file)
{
List<LinkItem> list = new List<LinkItem>();
// 1.
// Find all matches in file.
MatchCollection m1 = Regex.Matches(file, #"(<a.*?>.*?</a>)",
RegexOptions.Singleline);
// 2.
// Loop over each match.
foreach (Match m in m1)
{
string value = m.Groups[1].Value;
LinkItem i = new LinkItem();
// 3.
// Get href attribute.
Match m2 = Regex.Match(value, #"href=\""(.*?)\""",
RegexOptions.Singleline);
if (m2.Success)
{
i.Href = m2.Groups[1].Value;
}
// 4.
// Remove inner tags from text.
string t = Regex.Replace(value, #"\s*<.*?>\s*", "",
RegexOptions.Singleline);
i.Text = t;
list.Add(i);
}
return list;
}
public struct LinkItem
{
public string Href;
public string Text;
public override string ToString()
{
return Href + "\n\t" + Text;
}
}
}
Input:
string html = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> 2.<a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> ";
Result:
[0] = {www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
[1] = {http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
C# Scraping HTML Links
Scraping HTML extracts important page elements. It has many legal uses
for webmasters and ASP.NET developers. With the Regex type and
WebClient, we implement screen scraping for HTML.
Edited
Another easy way:you can use a web browser control for getting href from tag a,like this:(see my example)
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"https://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"www.aaa.xx/xx.zz/xxx\" ....></a>";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
List<string> href = new List<string>();
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("a"))
{
href.Add(el.GetAttribute("href"));
}
}
Try this regex:
"href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))"
You will get more help from discussions over:
Regular expression to extract URL from an HTML link
and
Regex to get the link in href. [asp.net]
Hope its helpful.
HTMLDocument DOC = this.MySuperBrowser.Document as HTMLDocument;
public IHTMLAnchorElement imageElementHref;
imageElementHref = DOC.getElementById("idfirsticonhref") as IHTMLAnchorElement;
Simply try this code
I came up with this one, that supports anchor and image tags, and supports single and double quotes.
<[a|img]+\\s+(?:[^>]*?\\s+)?[src|href]+=[\"']([^\"']*)['\"]
So
click here
Will match:
Match 1: /something.ext
And
<a href='/something.ext'>click here</a>
Will match:
Match 1: /something.ext
Same goes for img src attributes
I took a much simpler approach. This one simply looks for href attributes, and captures the value (between apostrophes) trailing it into a group named url:
href=['"](?<url>.*?)['"]
I think in this case it is one of the simplest pregmatches
/<a\s*(.*?id[^"]*")/g
gets links with the variable id in the address
starts from href including it, gets all characters/signs (. - excluding new line signs)
until first id occur, including it, and next all signs to nearest next " sign ([^"]*)
I have been finding it difficult to understand where I am going wrong. I understand that we should move with the times but I am not sure how to replace a scriptlet, that I can get to do the job, with the JSTL taglibrary functions.
I have a Model class called Ranges.class which contains a rangeName (String) and a startRange (BigDecimal) and an endRange (BigDecimal) value. I have a DAO class that handles all the db queries (crud type methods). I have a method in RangesDao.class called getAllRanges() which will get all the potential ranges from a mysql db and return a List. This will fetch all the Range objects which include the rangeName, startRange and endRange.
Q: So basically what I want to do is from my jsp page when a text input is selected I want to check if it is between the start and end value of each Range object (that was returned in the List) and when I have a match I want to update a different text input with that objects rangeName value.
This is what I have so far.
Range.class
package za.co.zs6erb.model;
import java.math.BigDecimal;
public class Range {
private int range_id;
private String rangeName;
private BigDecimal startRange;
private BigDecimal endRange;
//...getters and setters for each of the above variables ...
#Override
public String toString() {
return "Ranges [range_id=" + range_id + ", Range Name=" + rangeName + ", Start Range=" + startRange
+ ", End Range=" + endRangeBand + "]";
}
}
DAO Class: This is the getAllRanges() method
public List<Range> getAllRanges() {
List<Range> rangeList = new ArrayList<Range>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from ranges order by range_id");
while (rs.next()) {
Range lRange = new Range();
lRange.setID(rs.getInt("range_id"));
lRange.setRangeName(rs.getString("rangeName"));
lRange.setStartRange(rs.getBigDecimal("start_range"));
lRange.setEndRange(rs.getBigDecimal("end_range"));
rangeList.add(lRange);
}
} catch (SQLException e) {
e.printStackTrace();
}
return rangeList;
}
Controller: This class has a doGet() and a doPost() method the piece I am busy with is the doGet(). The doPost() is used when adding a "plannedRoute" object (just an object that has several other attributes that need to be added to a different table. - not the issue here) From the doGet() I list all the "plannedRoute" objects which all have one Range associated with each. When adding a new route I launch a jsp page from the doGet() method. The following part should make things a little clearer.
doGet():
private static String LIST_PLANNEDROUTES = "plannedroutes.jsp";
private RangeDao rDao;
//Constructor
public PlannedRouteController() {
super();
rDao = new RangeDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward = "";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("new")) {
forward = LIST_PLANNEDROUTES;
request.setAttribute("rd", rDao);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
So now we have the crux of the issue ...
plannedRoutes.jsp
<%# page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyTest</title>
<script src="sj/jquery.js"></script>
<script type="text/javascript">
//<!--
$(document).ready(function(){
$("#range").change(function() {
alert("A Range was entered");
<c:forEach var="entry" items="${rd}">
alert( "HERE>" + ${entry.rangeName});
</c:forEach>
document.getElementById("testName").value = $("#range").val();
});
});
//-->
</script>
</HEAD>
<BODY>
<form method="POST" action='<form method="POST" action='ContactController' name="frmAddContact">' name="frmAddRoute">
Range: <input type="text" id="range" name="range" />
Name: <input type="text" id="testName" name="testName" readonly />
<!-- a whole bunch of other stuff here -->
</form>
</BODY>
</HTML>
Q: So when the value in the range input text field changes (I call the method in the tag and there I want to step through the List and match what was typed in to see if it falls between the start and end range of any of the Range Objects. When I find a match I want to be able to fetch the rangeName attribute of that object and add that to the testName input text area.
I hope this is clear enough. I have tried the without success and am not sure where to go from here without using scriptlets ... Any help would be appreciated.
Kind Regards
Sean
First, you're putting the DAO object into the request, but in the jsp you want to access the list that the DAO method would return. Call the method in your controller and put the resulting list into the request.
request.setAttribute("rd", rDao.getAllRanges());
The rest all needs to be client-side code unless you want to change your design to use ajax. Try serializing the range list, in the controller, into a JSON string. Then in your jsp, you'll be giving javascript access to the data. Let's say you're using Gson to serialize in your servlet:
request.setAttribute("rd", new Gson().toJson(rDao.getAllRanges(), List.class));
So when you access ${rd} in the jsp, it will be a String in the following form:
[{"range_id":1,"rangeName":"Range 1", "startRange":10.0, "endRange":19.99},{"range_id":2,"rangeName":"Second Range", "startRange":18.75, "endRange":29.5}]
In the jsp, you set that as a javascript variable that can be accessed by your change function.
$("#range").change(function() {
var rdArray = ${rd};
alert("A Range was entered");
var floatVal = parseFloat($("#range").val());
var rangeFound = false;
var rdSize = rdArray.length;
var index = 0;
while (index < rdSize && !rangeFound)
{
var rangeObject = rdArray[index++];
if (floatVal >= rangeObject.startRange && floatVal <= rangeObject.endRange)
{
rangeFound = true;
$('#testName').val(rangeObject.rangeName);
}
}
});