I am a novice in jsp. i am trying to access values from my java class into my jsp page. i went thru a lot of pages and implemented a lot of stuff and i thing i made it all into a mess.
this is my dao class method
public DisplayDO Display(DisplayDO disDo)throws Exception
{
System.out.println("inside dao display");
Connection conn = null;
try{
conn = DbConnection.getConn();
}
catch(Exception e)
{
e.printStackTrace();
}
Statement statement = null;
try{
statement = conn.createStatement();
}
catch(SQLException e)
{
e.printStackTrace();
}
System.out.println("dbconnection established");
int userid=disDo.getUserid();
try
{
System.out.println("inside dao try");
System.out.println("userid = "+userid);
String str= "Select address_id from user where user_id =910";
//+userid;
PreparedStatement ps= conn.prepareStatement(str) ;
ResultSet rs=ps.executeQuery(str);
int address1=0;
while (rs.next())
{
address1= rs.getInt(("address_id"));
}
int addressid = 0;
addressid = address1;
System.out.println("values of addressid= "+ addressid +"address1= "+ address1);
System.out.println("query execution successfull");
str="select name,street_name,city,gender,reg_date from user,address,registeration where user.address_id="+addressid+" && address.address_id= "+addressid+" && registeration.user_id="+userid+" ;";
rs=ps.executeQuery(str);
UserDO user = new UserDO();
RegDO regDO = new RegDO();
AddressDO addressDO = new AddressDO();
while(rs.next())
{
user.setName(rs.getString("name"));
System.out.println("name= "+rs.getString("name"));
addressDO.setStreetname(rs.getString("street_name"));
System.out.println("street_name= "+rs.getString("street_name"));
addressDO.setStreetname(rs.getString("city"));
System.out.println("city = "+rs.getString("city"));
regDO.setGender(rs.getString("gender"));
System.out.println("gender = "+rs.getString("gender"));
regDO.setReg_date(rs.getString("reg_date"));
System.out.println("reg_date = "+rs.getString("reg_date"));
System.out.println("date using getter"+regDO.getReg_date());
}
}
catch(Exception e)
{
e.setStackTrace(null);
}
return disDo;
}
THis code is working perfectly and i am getting the values in the console..
the following code is my jsp page.
<%#page import="java.lang.String" %>
<%#page import="java.io.*" %>
<%#page import="com.quinoid.e_tender.databean.RegDO"%>
<%#page import="com.quinoid.e_tender.databean.AddressDO"%>
<%#page import="com.quinoid.e_tender.databean.UserDO"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<h1>Your Values</h1>
<%
System.out.print("inside display_1");
UserDO user=(UserDO)request.getAttribute("name");
out.println(user);
AddressDO add=(AddressDO)request.getAttribute("add");
RegDO reg=(RegDO)request.getAttribute("reg");
String name,street_name,city,gender,reg_date;
name=(String)request.getAttribute("user");
/*street_name=add.getStreetname();
city=add.getCity();
gender=reg.getGender();
reg_date=reg.getReg_date();
*/%>
<!-- <script type="text/javascript">
/*document.getElementById("name").innerHTML =(String)request.getAttribute("name");
document.getElementById("street_name").innerHTML = add.getStreetname();
document.getElementById("city").innerHTML = add.getCity();
document.getElementById("gender").innerHTML = reg.getGender();
document.getElementById("reg_date").innerHTML = reg.Reg_date(); */
</script> -->
<form name="innerHTML" method ="post">
<table border="1">
<tr>
<th> Name </th>
<th>Street Name</th>
<th> City </th>
<th> Gender </th>
<th>Registration date</th>
</tr>
<tr>
<td id=name> </td>
<td id=street_name> </td>
<td id=city> </td>
<td id=gender> </td>
<td id=reg_dae> </td>
</tr>
</table>
</form>
</body>
</html>
Iam trying to display the values of "name","street_name","city","gender","reg_date" in the table and failed miserably..
This is the result in my console
the servlet is in user display
In display method
userid= 910
inside dao display
dbconnection established
inside dao try
userid = 910
values of addressid= 118address1= 118
query execution successfull
name= anjana
street_name= nagar
city = tvm
gender = F
reg_date = 1990-08-15
date using getter1990-08-15
exiting display method
inside display_1
inside display_1
do help.. thanks in advance..
Set this attribute in 'request' in your servlet before forwarding to the jsp page.
UserDO user=(UserDO)request.getAttribute("name");
out.println(user);
AddressDO add=(AddressDO)request.getAttribute("add");
RegDO reg=(RegDO)request.getAttribute("reg");
String name,street_name,city,gender,reg_date;
name=(String)request.getAttribute("user");
set these values as
request.setAttribute("name",userDo); //UserDo instance.
request.setAttribute("add",addressDo);//AddressDO instance. and so on...
And then forward it
request.getRequestDispatcher("xxxx").forward(request,response);//xxxx is jsp page you are forwarding.
And get the value in jsp using
<%=xxx%>//xxx is the reference as **name**, **city**..
try with following code,
document.getElementById("street_name").innerHTML = '<%=add.getStreetname()%>';
document.getElementById("city").innerHTML = '<%=add.getCity()%>';
document.getElementById("gender").innerHTML = '<%=reg.getGender()%>';
document.getElementById("reg_date").innerHTML = '<%=reg.Reg_date()%>';
You must set your attributes to the request object and than forward the servlet class to JSP, where you can getAttribute from the Request object as it is an implicit object in the JSP.
But when getAttribute is called you must cast it to appropriate Object type.
And Make sure you are not using Redirect mechanism, otherwise your Request object will be null because it is a new object for JSP. Only in Forward Mechanism the request object is copied to the new request object on JSP.
You can use the examples available on Net and as well
Pradeep Kr Kaushal example.
I have written this to just let you inform about Forward and Redirect mechanism effects on Request object.
You are not calling you dao class Display method anywhere.
In your dao class, change the method like so (method names in java start with a lowercase letter by convention):
public DisplayDo display() throws Exception { ...
At the end of the method, after populating them from the ResultSet, initialize a DisplayDo object and set the userDo, addressDo and regDo objects:
DisplayDO displayDo = new DisplayDO();
displayDo.setRegDo(regDO);
displayDo.setAddressDi(addressDO);
displayDo.setUserDo(userDO);
In your jsp, add the import for your dao class (assuming it is called DisplayDao):
<%#page import="com.quinoid.e_tender.dao.DisplayDao"%>
Add this to your jsp to create a new DisplayDao and access its display() method:
<% DisplayDao displayDao = new DisplayDao();
DisplayDo displayDo = displayDao.display();
UserDO userDo = displayDo.getUserDo();
...
%>
You can then output values like this:
<td id="name"><%= userDo.getName() %></td>
Related
This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 3 years ago.
I am trying to populate an html data with data from my arraylist, but i am having some difficulties. I already loaded the data and stored it inside my arraylist but when launching my program the table is empty. Could someone help me with this? I already tried googling my problem, but i cant seem to find an answer.
This is where i'm loading my data and populating it inside my arraylist
import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
#WebServlet("/registered-class")
public class myRegist extends HttpServlet{
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
getInfo registerStu = new findInfo();
String ssn = request.getParameter("ssn");
String fullName = registerStu.getFullName(ssn);
String phone = registerStu.getPhone(ssn);
List<StudentClass> classList = registerStu.loadClass(ssn);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
StudentClass stu = new StudentClass();
request.setAttribute("message", classList);
request.getRequestDispatcher("/table.jsp").forward(request,response);
//ptints out info about course
//out.println(classList.get(0));
/*StudentInfo info = new StudentInfo(ssn, fullName, phone);
HttpSession session = request.getSession();
session.setAttribute("student", info);
String address = null;
if (fullName == null) {
address = "/myRegist.jsp";
}
else if (fullName != null) {
address = "/myRegist.jsp";
}
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward(request, response);*/
}
}
My html table
<html>
<body>
<head>
<title>
View Books
</title>
</head>
<body>
<table border=2>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Author</th>
<th>No. of copies AVAILABLE</th>
<th>Number of favourites</th>
</tr>
<tr>
<td><%=b.bookID%></td>
<td><%=b.bookTitle%></td>
<td><%=b.bookAuthor%></td>
<td><%=b.bookCopies%></td>
<td><%=b.bookFavs%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
Although #olivakyle's answer is correct, I prefer the use of jstl tags instead of scriplets: it keeps the JSP less messy:
<!DOCTYPE html>
<%#page contentType="text/html"%>
<%#page pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<head>
<title>
View Books
</title>
</head>
<body>
<table border=2>
<tr>
<th>Student ID</th>
<th>Name</th>
</tr>
<c:forEach var="stu" items="${message}">
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
It's quite simple actually – given that you're familiar in passing objects to your JSP. Here is an example using the object you passed and named message and I'm just assuming it has a String property named name.
<%for (StudentClass sc: message) {%>
<span><%=sc.name%></span><br>
<%}%>
i have a connection, controller class and jsp file , i want to pass the data which i get from sql query of PostgreSQL into jsp.
i am new in spring: is there any one can help me. thanks
this is my connection class:
public class PostGisConnection {
public Connection getConn(){
Connection connection = null;
try{
String url = "jdbc:postgresql://127.0.0.1:5432/imposm3";
String user = "postgres";
String passwd = "mypass";
connection = DriverManager.getConnection(url, user, passwd);
String query1="Select * from imposm3";
Statement mystmt = connection.createStatement();
ResultSet myRrs = mystmt.executeQuery(query1);
while (myRrs.next()) {
System.out.println(myRrs.getString("id") + ", " + myRrs.getString("tags") + "," + myRrs.getString("geom"));
}catch (SQLException e){
e.printStackTrace();
return null;
}
}
}
}
this is my controller:
#RequestMapping(method = RequestMethod.GET, path = "/createObject")
public String viewSchema() {
return "/index";
}
}
and this is my jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>saeed</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<form action="/createObject" method="GET" >
<table>
<tr>
<th>OSM_ID</th>
<th>TAGS</th>
<th>GEOMETRY</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</form>
use seperate method in post PostGisConnection to get the data from database.
public Map<String, String> getdatafromdatabase()
{
String query1="Select * from imposm3";
Statement mystmt = connection.createStatement();
ResultSet myRrs = mystmt.executeQuery(query1);
Map<String, String> details= new HashMap<String, String>();
while (myRrs.next()) {
details.put("id", myRrs.getString("id"));
details.put("tags", myRrs.getString("tags"));
details.put("geom",myRrs.getString("geom"));
}
return details;
}
Then call this method in controller class in post method.use Modal attributes to send data from controller to jsp. You have to maintain a bean class for your attributes(id,tag,geom). I cant able to find any bean class so I cant able to code in your question further. Try hello world and crud operation in spring mvc.
In jsp use C:foreach method to display your records.Make sure the model attribute in controller class and jsp same.
http://viralpatel.net/blogs/spring-mvc-hashmap-form-example/
crud operation in spring mvc
http://www.javatpoint.com/spring-mvc-crud-example
This question already has answers here:
Passing an object from JSP page back to Servlet
(3 answers)
Closed 6 years ago.
I have one Java Web Application.
My User_Objects class is given below
public class User_Objects {
public String firstName;
public String middleName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
}
I forward request with my Java User_Objects to JSP with using following code
User_Objects fillObj = fillData(request);
request.setAttribute("reqObj", fillObj);
RequestDispatcher view = request.getRequestDispatcher("/organization.jsp");
view.forward(request, response);
public User_Objects fillData(HttpServletRequest request) {
User_Objects fillObj = new User_Objects();
try {
fillObj.setFirstName(request.getParameter("txtFirstname"));
} catch (Exception e) {
}
try {
fillObj.setMiddleName(request.getParameter("txtMiddlename"));
} catch (Exception e) {
}
return fillObj;
}
I successfully receive this Object into my JSP form. But I want to send this Object again to the Servlet and When I click on Submit button on my JSP form and try to get this Object into my Servlet using below code
User_Objects obj = (User_Objects) request.getAttribute("reqObj");
request.getAttribute("reqObj") gives me null
My JSP form code is given below
<%# page import="otn.aitc.io.User_Objects" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!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>Organization</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(function() {
var reqObj = '${reqObj}';
var reqStatus = '${orgStatus}';
var orgJson = '${reqOrgJson}';
orgJson = orgJson.replace("/", "'");
if(reqStatus != "" || orgJson != "") {
if(reqStatus == "false") {
document.getElementById("lblError").style.display = '';
}
else {
document.getElementById("lblError").style.display = 'none';
}
var availableTutorials = [];
if(orgJson != "") {
var parsed = JSON.parse(orgJson);
for(var x in orgJson) {
if(parsed[x] != undefined) {
availableTutorials.push(parsed[x]);
}
}
}
$("#txtOrgName").autocomplete({source: availableTutorials});
}
else {
window.location.href = "index.jsp";
}
});
function validateOrg() {
var orgName = document.getElementById("txtOrgName");
if (orgName.value.trim().length == 0) {
alert("Enter Org Name");
return false;
}
}
</script>
</head>
<body>
<form name="orgname" action="org_name" method="post">
<table align="center">
<tr align="center">
<td colspan="4"><img src="images/logo.jpg" /></td>
</tr>
<tr>
<td>Organization :</td>
<td><input type="text" id="txtOrgName" name="txtOrgName" /><label style="color: red;">*</label></td>
</tr>
<tr>
<td align="center" colspan=2><br/><input type="submit" name="btnOrgName" id="btnOrgName"
value="Validate" onclick="return validateOrg();" /></td>
</tr>
</table>
<p align="center"><label id="lblError" style="color: red;">Error Message.</label></p>
</form>
</body>
</html>
I am using Java with Eclipse.
Don't mix and match the different execution scopes.
The serlvet and the JSP page are executed on server side (actually the JSP page is compiled to a servlet, too). Once the HTTP request is finished all request based objects are discarded, including the request attributes.
In the end it is a templating engine producing HTML text.
This HTML text (with embedded JavaScript) is executed by the client's browser. This execution scope is totally different to your server request scope, which has created this HTML page. So in your JavaScript code all the Java objects used to create that page on server side are unknown and unaccessable.
So you have two alternatives.
While creating the HTML include enough information to recreate your server side object. E.g. if you have a Person object with name and age attributes, you can include name and age as hidden form fields. After submitting the form you can recreate the Person object with the hidden field values coming in as request parameters.
Pro: Simple to implement.
Con: Only feasable for small data. Data is exposed to the client and can be manipulated.
Store the object on server side inside the session.
Pro: Data is not exposed to the client.
Con: Implementation more complex because of possible concurrent access to the session variables (browser can do multiple requests for the same session at the same time).
I am trying to edit and delete a single record from multiple records.Here below is my sample record displaying on jsp page,
I can edit the record for each row easily using below code,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.util.List" %>
<%# page import="java.util.Iterator" %>
<%#page import="java.sql.ResultSet"%>
<!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=UTF-8">
<title>Insert title here</title>
<script src="jquery1.11.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
function editRecording(task_id) {
//alert(task_id)
url = "EditRecord";
window.location="/RTTSchecking/"+url+"?task_id="+task_id;
}
</script>
<table align="center" border="1px" width="80%" >
<thead>
<tr>
<th>User_Id</th>
<th>Class</th>
<th>Subject</th>
<th>Chapter</th>
<th>Planned_Features</th>
<th>Planned_Date</th>
</thead>
<%Iterator itr;%>
<%List data = (List) request.getAttribute("TaskData");
for(itr = data.iterator(); itr.hasNext();)
{
%>
<tr>
<% String s = (String) itr.next();
%>
<td style="background-color: yellow;">
<input type="text" name="tid" value="<%=s %>"></td>
<td><input type="text" name="tid" value="<%=itr.next() %>"></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><input type="button" value="edit" name="<%=s%>" onclick="editRecording(this.name);"></td>
<td><input type="button" value="delete" name="<%=s%>" onclick="deleteRecording(this.name);"></td>
<% } %>
</tr>
</table>
</body>
</html>
EditREcord(servlet):
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
String a=request.getParameter("task_id");
convty = new Connectivity();
con = convty.setConnection();
st = con.createStatement();
query = "select * from task_table where task_id='"+a+"'";
rset = convty.getResultSet(query, con);
}
catch(Exception e) {
}
finally {
request.setAttribute("EditData", rset);
RequestDispatcher dd= request.getRequestDispatcher("editdata.jsp");
dd.forward(request, response);
out.close();
//out.println(""+tid);
}
}
Above code working fine.But my problem is, i want to delete record based on User_id, Class, Subject, Chapter and Planned_Date so how can i get these values from single row (which want to delete row)?
how to achive this below code?,
<script type="text/javascript">
function deleteRecording(User_id,Class,Subject,Chapter,Date) {
//alert(task_id,Class,Subject,Chapter,Date)
url = "EditRecord";
window.location="/RTTSchecking/"+url+"?user_id="+User_id+"&Tclass="+Class+"&subject="+Subject+"&chapter="+Chapter+"&date="+Date;
</script>
once if i achieved above code then i can easily delete selected single record from multiple rows using below code,
try {
String uid=request.getParameter("user_id");
String class=request.getParameter("Tclass");
String sub=request.getParameter("subject");
String chap=request.getParameter("chapter");
String date=request.getParameter("date");
convty = new Connectivity();
con = convty.setConnection();
st = con.createStatement();
query = "delete from task_table where User_id='"+uid+"' and class='"+class+"' and subject='"+sub+"' and chapter='"+chap+"' and date='"+date+"'";
st.executeUpdate(query);
}
catch(Exception e) {
}
Note : I can do delete records using delete from task_table where User_id='"+uid+"';
but how to do with query = "delete from task_table where User_id='"+uid+"' and class='"+class+"' and subject='"+sub+"' and chapter='"+chap+"' and date='"+date+"'";
I hope someone will help me out.
Once you delete data from database that means it's deleted.
You just need to reload that page again on click of delete.
I hope you've found the solution to your problem by now. But in case you haven't, I ran into the same problem today, and after many experiments, I came up with the following syntax for deleting a row using multiple criteria:
" DELETE FROM table_name WHERE " +
" first_db_field_name = '" + matching_variable_name + "'" +
" and next_db_field_name = '" + next_matching_variable_name + "'" +
" and last_db_field_name = '" + last_matching_variable_name + "'";
I have a table where I display items from database. In first ResultSet I have created an dropdown menu that let you choose if you want item to be available or not. But, because I have created it in first ResultSet rs, I cannon use it in second ResultSet rs1. Problem is in this line:
if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno"))
And here is the whole code:
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Stil/cssstil.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Prikaz oružja</title>
</head>
<body>
<h1>Prikaz oruzja</h1>
<%
out.print("<p align = \"center\">Administrator <a style=\"color:red;\">" + session.getAttribute("user") + "</a></p>");
%>
<table align = "center" bgcolor = "darkgrey" border = "1" cellpadding="3" cellspacing="1">
<tr>
<td>
<p style = "color: black;">Naziv</p>
</td>
<td>
<p style = "color: black;">Opis</p>
</td>
<td>
<p style = "color: black;">Cena</p>
</td>
<td>
<p style = "color: black;">Dostupnost</p>
</td>
<td>
</td>
</tr>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM oruzje";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
%>
<tr bgcolor="grey">
<td><%=rs.getString("naziv")%></td>
<td><%=rs.getString("opis")%></td>
<td><%=rs.getString("cena")%></td>
<%
if (rs.getString("dostupnost").equals("1")) {
out.print("<td><p style = \"color: green; font-size: 20px\">Dostupno</p></td>");
} else {
out.print("<td><p style = \"color: red; font-size: 20px\">Nedostupno</p></td>");
}
%>
<%
int a = rs.getInt("dostupnost");
if (a == 1) {
out.print("<td><select name=\"" + rs.getString("naziv") + "polje\"><option value = \"Dostupno\">Dostupno</option><option value = \"Nedostupno\">Nedostupno</option></select></td>");
} else {
out.print("<td><select name=\"" + rs.getString("naziv") + "polje\"><option value = \"Dostupno\">Dostupno</option><option value = \"Nedostupno\">Nedostupno</option></select></td>");
}
}
%>
</tr>
<tr><td></td><td></td><td></td><td></td>
<td align=center>
<form method="post">
<% Statement statement1 = connection.createStatement();
int bre;
ResultSet rs1 = statement.executeQuery(sql);
while (rs1.next()) {
if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno")) {
bre = statement1.executeUpdate("UPDATE oruzje SET dostupnost = 0 WHERE naziv='" + rs1.getString("naziv") + "'");
} else {
bre = statement1.executeUpdate("UPDATE oruzje SET dostupnost = 0 WHERE naziv='" + rs1.getString("naziv") + "'");
}
}
} catch (Exception e) {
e.printStackTrace();
}
%>
<input type="submit" value="Apply" name="Apply" />
</form>
</td>
</tr>
</table>
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;"><img src = "Slike/home.png" alt = "home"/></p>
</body>
First, I'll split your code in Servlets and JSP and show you why this is a better way to go.
Your view (assuming is called "foo.jsp"):
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!-- adding JSTL to your project -->
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Stil/cssstil.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Prikaz oružja</title>
</head>
<body>
<h1>Prikaz oruzja</h1>
<p align="center">
Administrator <span style="color:red"><c:out value="${user}" /></span>
</p>
<!--
In this case, the form should wrap all your table
since you want to process all the input elements
inside it. Otherwise, you will update the entire data
rather than update per entity.
-->
<form method="post">
<table align="center" bgcolor="darkgrey" border="1" cellpadding="3" cellspacing="1">
<th>
<td>
<p style = "color: black;">Naziv</p>
</td>
<td>
<p style = "color: black;">Opis</p>
</td>
<td>
<p style = "color: black;">Cena</p>
</td>
<td>
<p style = "color: black;">Dostupnost</p>
</td>
<td>
</td>
</th>
<c:forEach items="${oruzjeList}" var="oruzje">
<tr bgcolor="grey">
<td>${oruzje.naziv}</td>
<td>${oruzje.opis}</td>
<td>${oruzje.cena}</td>
<td>
<p style="color: green; font-size: 20px">
<!-- printing the value dynamically in view -->
<c:out value="${oruzje.dostupnost == '1' ? 'Dostupno' : 'Nedostupno'}" />
</p>
</td>
<td>
<!--
oruzje.naziv should be an ID, not the "unique name"
because a name could contain empty spaces which
will break the name of the component
here I use id but you will replace it with your ID
-->
<select name="polje_${oruzje.id}">
<option value="1" ${oruzje.dostupnost == '1' ? 'selected' : ''}>Dostupno</option>
<option value="0" ${oruzje.dostupnost == '0' ? 'selected' : ''}>Nedostupno</option>
</select>
<!--
Additionally, we need to obtain the respective id for
the row to be updated.
We will use a hidden input field which uses the ID
-->
<input type="hidden" name="hidId_${oruzje.id}" value="${oruzje.id}" />
</td>
</tr>
</c:forEach>
<tr>
<td></td><td></td><td></td><td></td>
<td>
<input type="submit" value="Apply" />
</td>
</tr>
</table>
</form>
<p style="position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">
<img src="Slike/home.png" alt="home"/>
</p>
</body>
</html>
This assumes you have an entity that supports that maps to your database table:
public class Oruzje {
private int id;
private String naziv;
private String opis;
private String cena;
private String dostupnost;
//propers getters and setters for your fields
}
Now, your Servlet:
//yes, a Servlet can map directly to your JSP
//there's no problem using this approach
#WebServlet("/foo.jsp")
public class OruzjeServlet extends HttpServlet {
//I won't go far with more classes
//nor with other improvements to the code
//I'll write the basic stuff here in Servlet
//this method should be in an utility class
//to provide reusability
private void closeResource(Closeable resource) {
try {
if (resource != null) {
resource.close();
}
} catch (IOException e) {
//silent exception
}
}
//this method should also be in an utility class
//and should recover the connection from a DataSource
//instead of creating the physical connection everytime
private Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
} catch (Exception e) {
//this should be splitted for better handling
//but I leave this up to you
//handle the exception
//very basic handling
e.printStacktrace();
}
}
//this method should be in a proper DAO class
//reusing a connection for execution of multiple statements
private List<Oruzje> getOruzjeList(Connection con) {
List<Oruzje> oruzjeList = new ArrayList<Oruzje>();
Statement statement = null;
ResultSet rs = null;
try {
statement = connection.createStatement();
String sql = "SELECT * FROM oruzje";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
Oruzje oruzje = new Oruzje();
oruzje.setId(rs.getInt("id")); //use the real column
oruzje.setNaziv(rs.getString("naziv"));
oruzje.setOpis(rs.getString("opis"));
oruzje.setCena(rs.getString("cena"));
oruzje.setDostupnost(rs.getString("dostupnost"));
oruzjeList.add(oruzje);
}
} catch (SQLException e) {
//again, handle the exception
e.printStacktrace();
} finally {
closeResource(rs);
closeResource(statement);
}
return oruzjeList;
}
//this method will be executed when a client (browser)
//tries to enter to your foo.jsp page
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con = getConnection();
List<Oruzje> oruzjeList = getOruzjeList(con);
closeResource(con);
//setting the oruzjeList variable as attribute
//this will feed the ${oruzjeList} used in the
//<c:forEach>
request.setAttribute("oruzjeList", oruzjeList);
//now, forward the view to the right view (JSP)
//it is not a redirect
request.getRequestDispatcher("/foo.jsp").forward(request, response);
}
//this method will be executed when user selects "Apply"
//option in the view (the JSP)
//because you stated that the method to submit the <form>
//is POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//now, we just retrieve the necessary parameters and process the data
//sent from the form
Connection con = getConnection();
List<Oruzje> oruzjeList = getOruzjeList(con);
//each ? is a parameter in the query
//starting at index 1
String updateSql = "UPDATE oruzje SET dostupnost = ? WHERE id = ?";
PreparedStatement pstmt = con.prepareStatement();
for(Oruzje oruzje : oruzjeList) {
//this is where the static part of the name becomes handy
String theId = request.getParameter("hidId_" + oruzje.getId());
String theDostupnost = request.getParameter("polje_" + oruzje.getId());
//I'll avoid basic validation like
//if (theId == null || "".equals(theId))
//right to the update!
//setting the first parameter: dostupnost = ?
pstmt.setString(1, theDostupnost);
//setting the second parameter: ID = ?
//since it's an int, parsing the String to int
pstmt.setInt(2, Integer.parseInt(theId));
//perform the update for the current ID and Dostupnost
pstmt.execute();
}
//at the end, closing the resources
closeResource(pstmt);
//this is cumbersome but just to make sure
//the data was updated successfully
oruzjeList = getOruzjeList(con);
closeResource(con);
//similar to the doGet, we will forward to the view
request.getRequestDispatcher("/foo.jsp").forward(request, response);
}
}
More info:
How to avoid Java code in JSP files?
StackOverflow JSTL Wiki
StackOverflow EL Wiki
Difference between JSP forward and redirect
Sending a variable from Servlet to JSP
Retrieve values from JDBC and use JSTL tags to call the methods
Is it a good idea to put jdbc connection code in servlet class?
Difference between Statement and PreparedStatement