Please I need help on passing arraylist from servlet to the jsp page.I'm trying to populate dropdown values from Database.I have successfully connected to the Database and the values are stored in the list. The list is passed to the servlet.In the servlet, i checked by printing the values retrieved in the console. It's working fine too. Also, i set the attribute to the list and forwarded to my jsp page using request dispatcher. In my jsp page, I'm trying to get the values retrieved using jstl. I have also added the jstl jar and added the jstl tag on the top of the jsp page. I have searched many times for jstl syntax and also implemented that in my jsp. But still values are not retrieved in my dropdown.
Thanks in advance.Please someone help me.
------Success.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%-- <%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> --%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- <%# page import = "pack.DtoForm" %>
<jsp:useBean id="dform" scope="page" class="pack.DtoForm" />
<jsp:useBean id="Countries" class="pack.ViewValuesInDB" scope="page"/>
<%# page import="java.util.*" %> --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success page</title>
</head>
<body>
<h1>Success page</h1>
<div class="dbstyle">
<h4>Let's start learning connecting to the database!</h4>
<br>
<!-- <form action="DAOServlet" method="get" name="Countries"> -->
<label >Countries*:</label>
<select id="Countries" name="Countries" >
<c:forEach items="${list}" var="listt">
<option value="${listt.Countries}">${listt}</option>
</c:forEach>
</select>
</div>
<!-- </form> -->
</div>
<div>
</div>
</body>
</html></pre>
DtoForm----------------------
package pack;
public class DtoForm {
private String Countries;
public String getCountries() {
return Countries;
}
public void setCountries(String countries) {
this.Countries= countries;
}
}
ViewValuesInDB----------------------------
package pack;
import java.sql.*;
import java.util.ArrayList;
import com.sybase.jdbcx.*;
public class ViewValuesInDB {
Connection con = null;
Statement stmt = null;
SybDriver sybDriver = null;
DtoForm dform=new DtoForm();
//List<DtoForm>dform =new ArrayList<DtoForm>();
ArrayList<String> list=new ArrayList<String>();
public ArrayList<String> makeConnection() throws Exception {
try
{
sybDriver = (SybDriver) Class.forName(
"com.sybase.jdbc2.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
con = DriverManager.getConnection(
"jdbc:sybase:Tds:ip:port","username", "password");
System.out.println("Database connected");
Statement stmt = con.createStatement();
String query = "select Countries from Country";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String a=rs.getString(1);
dform.setCountries(a.toString());
list.add(dform.getCountries());
}
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
System.out.println("Error is "+e.getMessage());
}
return list;
}
public static void main(String args[]) throws Exception {
System.out.println("inside DB main function");
ViewValuesInDB sc = new ViewValuesInDB();
sc.makeConnection();
}
}
---------------genrated html---------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success page</title>
<style>
.dbstyle
{
width:100%;
height:540px;
background-color:#FDF5E6;
}
</style>
</head>
<body>
<h1>Success page</h1>
<div class="dbstyle">
<h4>Let's start learning connecting to the database!</h4>
<br>
<!-- <form action="DAOServlet" method="get" name="Countries"> -->
<label >Countries*:</label>
<div>
<select id="Countries" name="Countries" >
</select>
</div>
<!-- </form> -->
</div>
<div>
</div>
</body>
</html>
-------servlet modified--------
package pack;
import java.util.ArrayList;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DropdownServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
System.out.println("action is called inside dropdown");
ViewValuesInDB daoobj = new ViewValuesInDB();
ArrayList<String> list;
try {
list = daoobj.makeConnection();
System.out.println(list);
if(null == list)
{System.out.println("list is null");
}
else{
System.out.println("list has values");
}
request.setAttribute("list", list);
request.getRequestDispatcher("Success.jsp").forward(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
System.out.println("inside servlet function");
DropdownServlet sc = new DropdownServlet();
sc.doGet(null, null);
}
}
Related
I want to set the focus on the InputRadioGroup but it appears it doesn't have the ElementReference attribute unlike the other Blazor built-in form components. Should I just extend the InputRadioGroup and add the ElementReference or is there another way to set focus on the InputRadio or InputRadioGroup?
You could refer to the sample below to focus on the InputRadio.
Vehicle.cs
namespace BlazorApp1.Model
{
public class Vehicle
{
public string Name { get; set; }
}
}
file1.js
window.jsfunction = { focusElement: function (id) { const element = document.getElementById(id); element.focus(); } }
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>BlazorApp1</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="BlazorApp1.styles.css" rel="stylesheet" />
<script src="file1.js"></script>
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
Index.razor
#inject IJSRuntime js
#page "/"
<div>
<h4> vehicle Selected - #vehicle.Name </h4>
<EditForm Model="vehicle">
<InputRadioGroup #bind-Value="vehicle.Name" >
#foreach (var option in rdOptions)
{
<InputRadio Value="option" id=#option #onfocus="alrt" /> #option <br />
}
</InputRadioGroup>
<br>
<input Id="idPassWord" Type="password" />
<button #onclick="clickOK">Set Focus</button>
</EditForm>
</div>
#code{
BlazorApp1.Model.Vehicle vehicle=new BlazorApp1.Model.Vehicle(){Name = "auto"};
List<string> rdOptions = new List<string> { "car", "bus", "auto" };
private async void clickOK()
{
await Focus("car");
}
private void alrt()
{
Console.WriteLine("Element focused");
}
public async Task Focus(string elementId)
{
await js.InvokeVoidAsync("jsfunction.focusElement", elementId);
}
}
Output:
In the above code example, I am generating the InputRadio on the page which has the OnFocus event. While we try to set the Focus on the InputRadio using the JS code. OnFocus event gets fired and displays the message in a browser console. This proves that InputRadio is getting focused.
Further, you could modify the code as per your own requirements.
After some investigation, seems like the ability to focus for InputRadio/InputRadioGroup was removed due to some prior issues. They now returned the focus after I raised the issue, and it will be included to .NET 7.
I create a small admin tool and I decided to convert it to a Razor class library so that I will be able to use it in other applications as well. I created the Razor Class Library project and I added all the razor pages that I had in my main project and I tried to test the new project. The problem was that the framework for some reason did not recognize the html helpers so I created a new clean project and try to find out what is wrong and the result was that the application did not fire the post action of the razor page and the asp-for property was not using properly the property value. I used the following code in order to test the Razor Class Library.
Page1.cshtml.cs
public class Page1Model : PageModel
{
[BindProperty]
public Input MyInput { get; set; }
public class Input
{
public string Name { get; set; }
}
public void OnGet()
{
}
public void OnPost()
{
}
}
Page1.cshtml
#page
#model WebApplication1.MyFeature.Pages.Page1Model
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Page1</title>
</head>
<body>
<form method="post">
<input asp-for="MyInput.Name" /><br />
<input type="submit" />
</form>
</body>
</html>
The generated html was the following
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Page1</title>
</head>
<body>
<form method="post">
<input asp-for="MyInput.Name" /><br />
<input type="submit" />
</form>
</body>
</html>
As you can see the input for MyInput.Name appears as I typed it the Page1.cshtml file. The right output shoud be the following:
<input type="text" id="MyInput_Name" name="MyInput.Name" value="" /><br />
Do I have to do something in order to make the html helpers work and the OnPost action to be called when a post request occurs?
I found the solution to the problem and I decided to share it with you just in case someone else has the same problem.
In order to make it work I had to add the file _ViewImports.cshtml in the pages folder of the Razor Class Library and add the following line:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Currently, I am using JxBrowser 6.14.2 to print a PDF file which is embedded in tag "". However, I can only get a blank PDF file(save as PDF or print).
The html code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>iframe</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
</head>
<body style="text-align: center" >
<iframe src="iframe.pdf#toolbar=0" id="myFrame" name="myFrame" width="600" height="800"></iframe>
<input type="button" value="print" onclick="testPrint();">
<script type="text/javascript">
function testPrint(){
var iframe = document.getElementById("myFrame");
iframe.contentWindow.print();
}
</script>
</body>
</html>
And the java:
package com.test.print;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
public class JxBrowserPrintPdf {
public static void main(String[] args) {
Browser browser = new Browser();
BrowserView browserView = new BrowserView(browser);
JFrame frame = new JFrame("JxBrowser - PrintPDF");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.add(browserView,BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
browser.loadURL("http://localhost:8888/.../iframe.html");
frame.setVisible(true);
}
}
The webpage displays the contents of the PDF file, but after clicking the print button "print", I get the blank file. And I can get the correct file in the Google browser.
Hope someone can solve my problem. Thanks.
I have a simple example of page method.but its not getting called.the breakpoint at GetDate() function never get hit and always it shows alert as 'Failure'.
aspx page is :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default13.aspx.cs" Inherits="Default13" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" >
function btnTest_onclick() {
PageMethods.GetDate(Success, Failure);
}
function Success(data) {
alert("success");
alert(data);
}
function Failure(data) {
alert("failure");
alert(data.toSource());
}
</script>
</head>
<body >
<form id="form1" runat="server" method="post">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" ScriptMode="Debug" >
</asp:ScriptManager>
<%--<input type="button" id="btnSave" value="Save" onclick="btnTest_onclick" />--%>
<asp:Button id="btnSave" runat="server" Text="Save" OnClientClick="btnTest_onclick()"/>
</div>
</form>
</body>
</html>
and the aspx.cs page is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
public partial class Default13 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetDate()
{
return "str";
}
}
any suggestions?
Thanks in Advance,
I think issue is because your button is server side control, will suggest you to call PageMethod from html button instead.
Still If you require to do so,Please try following code.
<asp:Button id="btnSave" runat="server" Text="Save" OnClientClick="btnTest_onclick(); return false;"/>
I am using jquery webcam plugin in a MVC4 page. The plugin is here: http://www.xarg.org/project/jquery-webcam-plugin/.
I am using save method on the plugin after capturing the image but it is not posted to the controller action.
This is the cshtml page:
#{
ViewBag.Title = "Index";
}
<!DOCTYPE html>
<html lang="es">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>#ViewBag.Title - Prueba WebCam</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/styles/base")
#Scripts.Render("~/scripts/jquery", "~/scripts/jqueryui", "~/scripts/webcam")
<script type="text/javascript">
$(function () {
$("#camera").webcam({
width: 320,
height: 240,
mode: "save",
swffile: "#Url.Content("~/Scripts/WebCam/jscam_canvas_only.swf")",
onTick: function () { },
onSave: function () { alert('Almacenamiento realizado') },
onCapture: function () { webcam.save("#Url.Action("Save")"); alert('Captura realizada'); },
debug: function () { },
onLoad: function () { }
});
});
function CaptureAndSave() {
webcam.capture();
}
</script>
</head>
<body class="home desytec">
<header>
</header>
<!-- MAIN -->
<div id="main">
<!-- wrapper-main -->
<div class="wrapper">
<!-- headline -->
<div class="clear"></div>
<div id="headline">
<span class="main"></span>
<span class="sub"></span>
</div>
<!-- ENDS headline -->
<!-- content -->
<div id="content">
<div id="camera"></div>
<br /><br /><br />
<input type="button" onclick="CaptureAndSave();" value="Capturar" />
</div>
<!-- ENDS content -->
</div>
<!-- ENDS wrapper-main -->
</div>
<!-- ENDS MAIN -->
<footer>
</footer>
</body>
</html>
And this is the controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Capture.Controllers
{
public class CaptureController : Controller
{
//
// GET: /Capture/
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Save(HttpPostedFileBase file)
{
try
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/Captures"), pic);
file.SaveAs(path);
return Json(true, JsonRequestBehavior.AllowGet);
}
}
catch
{
}
return Json(true, JsonRequestBehavior.AllowGet);
}
}
}
Save method of the controller get never called and in fact, by using firebug, no POST is done.
By the way. The camera works because I can see the it in the canvas (DIV id = camera).
And OnCapture callback is called after I press the capture button.
Any help on this, please?
Thanks
Jaime
Your Save action is not called because the jscam_canvas_only.swf only contains the "callback" mode. For the full API (so for the "save" mode) you need download and use the jscam.swf.
So change your webcam setup to:
$("#camera").webcam({
//...
swffile: "#Url.Content("~/Scripts/WebCam/jscam.swf")",
//...
});
Now your Save action will be called but the file parameter will be always null, because the jscam.swf send the image data as hexadecimal string in the request body.
The default model binding infrastructure is not handling this so you need to write some additional code:
if (Request.InputStream.Length > 0)
{
string pic = System.IO.Path.GetFileName("capture.jpg");
string path = System.IO.Path.Combine(Server.MapPath("~/Captures"), pic);
using (var reader = new StreamReader(Request.InputStream))
{
System.IO.File.WriteAllBytes(path, StringToByteArray(reader.ReadToEnd()));
}
return Json(true, JsonRequestBehavior.AllowGet);
}
You need to remove the file parameter and access the raw data from the Request.InputStream but because it is a hexadecimal string you need to convert it to a byte[] before saving it.
There is no default conversion built in .NET but SO is full of good solutions:
How do you convert Byte Array to Hexadecimal String, and vice versa?
In my sample I've used this method:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length/2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
}
return bytes;
}