Integrating Eclipse with MySQL - java

I am facing a problem while integrating a web application developed in eclipse with a mysql database (mysql workbench).
below are the jsp files I used and the database name.
database username -- root
password -- 1234
Login.jsp
<%--
Document : Login
Created on : 28 Feb, 2015, 8:50:26 AM
Author : Lahaul Seth
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Demo with JSP</title>
</head>
<body>
<form method="post" action="userdetail.jsp">
<center>
<table border="1" cellpadding="5" cellspacing="2">
<thead>
<tr>
<th colspan="2">Login Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>Username</td>
<td><input type="text" name="username" required/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" required/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" />
<input type="reset" value="Reset" />
</td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>
userdetail.jsp
<%# page language="java" %>
<%# page import="org.owasp.esapi.ESAPI" %>
<%# page import="org.owasp.esapi.codecs.Codec" %>
<%# page import="org.owasp.esapi.codecs.MySQLCodec" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%! Connection con= null; %>
<%! Statement stmt= null; %>
<%! ResultSet rs= null; %>
<%! MySQLCodec mc= null; %>
<html>
<head><title>List Users</title></head>
<%
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
String uid = request.getParameter("uid");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(ClassNotFoundException ce){out.println(ce);}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "1234");
stmt = con.createStatement();
String sql = "select * from userdetail where id = "+Integer.parseInt(uid);
//out.println(sql);
rs = stmt.executeQuery(sql);
%>
<body>
<br>
<br>
<div align="center"><b>You have Successfully Logged In Mr/Ms<%=uname%>, Your Details are :-</b></div>
<br>
<br>
<br>
<form action="view.jsp">
<table align="center">
<% while(rs.next()) {%>
<tr><td>First Name</td><td><input type=text name="fname" value='<%=rs.getString("firstname")%>' ></td></tr>
<tr><td>Last Name</td><td><input type=text name="lname" value='<%=rs.getString("lastname")%>'></td></tr>
<tr><td>Email</td><td><input type=text name="email" value='<%=rs.getString("email")%>'></td></tr>
<tr><td>Phone</td><td><input type=text name="phone" value='<%=rs.getString("phone")%>'></td></tr>
<tr><td>Address</td><td><input type=text name="address" value='<%=rs.getString("address")%>'></td></tr>
<%
}
rs.close();
stmt.close();
con.close();
}catch(SQLException exception){
//out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
//out.println("-->");
}
%>
</table>
</form>
</body>
</html>
auth.jsp
<%# page language="java" %>
<%# page import="org.owasp.esapi.ESAPI" %>
<%# page import="org.owasp.esapi.codecs.Codec" %>
<%# page import="org.owasp.esapi.codecs.MySQLCodec" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%! Connection con=null; %>
<%! Statement stmt= null; %>
<%! ResultSet rs= null; %>
<%! MySQLCodec mc= null; %>
<html>
<head><title>This is a Jdbc Example</title></head>
<body>
<%
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(ClassNotFoundException ce){out.println(ce);}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost/test:3306","root", "1234");
stmt = con.createStatement();
//String sql = "select * from user_detail where uname='" + uname +"' and pass='" + pass + "'";
mc = new MySQLCodec(0);
String sql = "SELECT * FROM userdetail WHERE uname = '" + ESAPI.encoder().encodeForSQL( mc, uname) + "' and pass = '" + ESAPI.encoder().encodeForSQL( mc, pass) +"'";
out.println(sql);
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
boolean loggedIn = true;
//response.sendRedirect("userdetail.jsp?uid=1");
out.println("Successfully logged in");
} else {
//response.sendRedirect("login.jsp");
out.println("Username and/or password not recognized");
}
rs.close();
stmt.close();
con.close();
}catch(SQLException exception){
//out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
//out.println("-->");
}
%>
</body>
</html>
MySQL datatbase
Error page

Well, this sounds to be a class path issue. Could you please check MySQLCodec class present in WEB-INF/classes or present in any jar in WEB-INF/lib path.
You can double check the tomcat war directory. It should be in the below sample folder structure.

Related

request.getParameter in jsp returns null or empty string

I made an html textbox for an input and want to connect this to database.
But everytime I make an input to the textbox and move on to the result page, the result only shows the name of the attribute but not any tuples.
I think the request.getParameter() returns null or empty string. I did several tries but cannot find any solution.
Here's my code.
This's selectTestForm.jsp
<%# page contentType="text/html; charset=utf-8" %>
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Select the game</title>
</head>
<body>
<p>Input opponent team</p>
<form name="form1" method="get" action="result.jsp">
<p>Opponent team : <input type="text" name="oppon"></p>
<p><input type="submit" name="Submit" value="send"></p>
</form>
</body>
</html>
And this's the result.jsp
<%# page contentType="text/html; charset=utf-8" %>
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Find the game</title>
</head>
<body>
<table width="500" border="1">
<tr>
<td width="100">Game ID</td>
<td width="100">Opponent Team</td>
<td width="100">Start Date</td>
</tr>
<%
String opponent = (String) request.getParameter("oppon");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
System.out.println("Driver loading error");
}
try{
String jdbcUrl = "jdbc:oracle:thin:#localhost:1521:xe";
String userId = "sports_booking";
String userPass = "jade";
con = DriverManager.getConnection(jdbcUrl, userId, userPass);
String sql = "select * from game where opponent=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "opponent");
rs = pstmt.executeQuery();
while( rs.next() ) {
String game_id = rs.getString("game_id");
String start_date = rs.getString("start_date");
%>
<tr>
<td width="100"><%= game_id %></td>
<td width="100"><%= opponent %></td>
<td width="100"><%= start_date %></td>
</tr>
<%
}
}catch(SQLException e){
e.printStackTrace();
if(rs != null) {
try {
rs.close();
}catch(SQLException sqle) {}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException sqle) {}
}
if(con != null) {
try {
con.close();
}catch(SQLException sqle) {}
}
}
%>
</table>
</body>
</html>
I'd appreciate if you help my problem thanks!
The problem is line pstmt.setString(1, "opponent");, as you set a const "opponent" string instead of the variable.
pstmt.setString(1, "opponent"); -> pstmt.setString(1, opponent); should work now.

JSP search option

i have been trying to make it work for a long time now. but none of the reference works. so far these are my latest code regarding search. hopefully someone can help. i am new in jsp and this is final graduation project. so badly need help.
code:
index.jsp:
<div class="container">
<form class="form-inline" method="post" action="search.jsp">
<input type="text" name="roll_no" class="form-control" placeholder="Search roll no..">
<button type="submit" name="save" class="btn btn-primary">Search</button>
</form>
search.jsp:
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "hospital";
String userid = "hospital";
String password = "hospital";
String NAME=request.getParameter("NAME");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!DOCTYPE html>
<html>
<body>
<h1>Search Data</h1>
<table border="1">
<tr>
<td>CODE</td>
<td>NAME</td>
<td>PRICE</td>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select * from product where NAME="+NAME+"' ";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("CODE") %></td>
<td><%=resultSet.getString("NAME") %></td>
<td><%=resultSet.getString("PRICE") %></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>

I am trying to insert data in to a SQL database in my local computer using Java jsp

I am creating a web application in java jsp using Eclipse and Tomcat.but I am stock unable to insert the data in to my local SQL server. The Form of the page is coded in HTML then I want the Java code part to get the data entered and insert the data in to the database but when I click the submit button absolutely nothing happens, no error message, no warning so far I am only able to type and clear the form. I am very new in Java. I just pick up this codding language recently but I am determine to learn it.
Help please here is my full code.
<%# page import="java.text.*,java.util.*" session="false"%>
<%# page import="java.sql.*" %>
<%#page import="javax.swing.JOptionPane" %>
<%#page import="java.util.Date" %>
<%#page import ="java.io.IOException" %>
<%#page import ="javax.servlet.ServletException" %>
<%#page import ="javax.servlet.http.HttpServlet" %>
<%#page import ="javax.servlet.http.HttpServletRequest" %>
<%#page import ="javax.servlet.http.HttpServletResponse" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<%# 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 Laptops Data</title>
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<%!public class Insert extends HttpServlet {
String dbURL = "jdbc:sqlserver://localhost\\SQLYRSIN";
String user = "pass";
String pass = "pass";
Connection conn = null;
PreparedStatement InsertLaptops = null;
ResultSet resultSet = null;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String LaptopMake, LaptopModel, LaptopServicetag, LaptopDatein, LaptopNotes, LaptopType;
LaptopMake = req.getParameter("iMake");
LaptopModel = req.getParameter("iModel");
LaptopServicetag = req.getParameter("iServiceTag");
LaptopDatein = req.getParameter("iDatein");
LaptopNotes = req.getParameter("iNotes");
LaptopType = req.getParameter("iType");
try {
conn = DriverManager.getConnection(dbURL, user, pass);
Statement st = conn. createStatement();
st.executeUpdate("INSERT INTO LaptopsTable (Make, Model, [Service Tag], Datein, Notes, Type)"
+ " VALUES ('"+LaptopMake+"','"+LaptopModel+"','"+LaptopServicetag+"','"+LaptopDatein +"','"+LaptopNotes+"','"+LaptopType+"')");
JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE);
st.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}%>
<div id="header">
<div class="logo">
<span> Resident Screening</span> Jinventory
</div>
</div>
<div id="container">
<div class="content">
<h1>Add New Laptop</h1>
<p>Make sure all Service Tag Enter in here are Laptops</p>
<div id="box">
<form name="LaptopsForm" method="get" class="contentfonts"
action="LaptopsInsert2.jsp" method="Post">
<table>
<tbody>
<tr>
<td>Service Tag</td>
<td><input type="text" name="iServiceTag" size="40"></td>
</tr>
<tr>
<td>Make</td>
<td><input type="text" name="iMake" size="40"></td>
</tr>
<tr>
<td>Model</td>
<td><input type="text" name="iModel"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="iDate"></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" name="iTyped" Value="Laptop"
disabled="disabled"></td>
</tr>
<tr>
<td>Notes</td>
<td><input Type="text" name="iNotes" size="30" height="40"></td>
</tr>
<tr>
<td><input type="reset" name="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
Here's a draft which you could use as a starting point.
As mentioned before, you should seriously consider some changes to your design:
Separate View (.jsp) from Business-Logic (SQL-Statements etc.)
Don't use scriptlets ( <% and so on )
Creating a Servlet within JSP is overkill - a JSP is compiled into a servlet by the servlet container.
Don't create Connections one-by-one. Use a connection pool. This will pay off quickly.
In the code you'll see some changes to your setup:
form is submitted per POST
instead of subclass, JSP checks for methods POST and only then tries the insert.
never ever use Swing inside Webapps. If that JOptionPane was opened, your webapp would block at that point, while the Dialog was shown somewhere on your server.
Use of PreparedStatement instead of Statement this prevents SQL injection. You'll still want to check against Cross-Site-Scripting if you plan on displaying the inserted values in your webapp again.
Disclaimer: I haven't tested or even tried to compile this code. Edit was done only to point you in the right direction.
Here it goes
<%#page import="java.text.*,java.util.*" session="false"%>
<%#page import="java.sql.*" %>
<%#page import="java.util.Date" %>
<%#page import ="java.io.IOException" %>
<%#page import ="javax.servlet.ServletException" %>
<%#page import ="javax.servlet.http.HttpServlet" %>
<%#page import ="javax.servlet.http.HttpServletRequest" %>
<%#page import ="javax.servlet.http.HttpServletResponse" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<%# 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 Laptops Data</title>
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<%
if("POST".equals(request.getMethod()) {
String dbURL = "jdbc:sqlserver://localhost\\SQLYRSIN";
String user = "pass";
String pass = "pass";
Connection conn = null;
PreparedStatement InsertLaptops = null;
ResultSet resultSet = null;
String LaptopMake, LaptopModel, LaptopServicetag, LaptopDatein, LaptopNotes, LaptopType;
LaptopMake = req.getParameter("iMake");
LaptopModel = req.getParameter("iModel");
LaptopServicetag = req.getParameter("iServiceTag");
LaptopDatein = req.getParameter("iDatein");
LaptopNotes = req.getParameter("iNotes");
LaptopType = req.getParameter("iType");
try {
conn = DriverManager.getConnection(dbURL, user, pass);
PreparedStatement st = conn.prepareStatement("INSERT INTO LaptopsTable (Make, Model, [Service Tag], Datein, Notes, Type) VALUES (?,?,?,?,?,?)");
st.setString(1, LaptopMake);
st.setString(2, LaptopModel);
st.setString(3, LaptopServicetag);
st.setString(4, LaptopDatein);
st.setString(5, LaptopNotes);
st.setString(6, LaptopType);
st.executeUpdate();
//This is SWING - and would at best popup a Dialog ON YOUR SERVER
//JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,
// JOptionPane.PLAIN_MESSAGE);
//Alternative: Show some HTML.
%>
<h1>Your Data has been inserted.</h1>
<%
st.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
} //END of Method.equals("POST")
%>
<div id="header">
<div class="logo">
<span> Resident Screening</span> Jinventory
</div>
</div>
<div id="container">
<div class="content">
<h1>Add New Laptop</h1>
<p>Make sure all Service Tag Enter in here are Laptops</p>
<div id="box">
<form name="LaptopsForm" method="POST" class="contentfonts"
action="" method="POST">
<table>
<tbody>
<tr>
<td>Service Tag</td>
<td><input type="text" name="iServiceTag" size="40"></td>
</tr>
<tr>
<td>Make</td>
<td><input type="text" name="iMake" size="40"></td>
</tr>
<tr>
<td>Model</td>
<td><input type="text" name="iModel"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="iDate"></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" name="iTyped" Value="Laptop"
disabled="disabled"></td>
</tr>
<tr>
<td>Notes</td>
<td><input Type="text" name="iNotes" size="30" height="40"></td>
</tr>
<tr>
<td><input type="reset" name="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>

refreshing mysql table in jsp with a button

I am trying to retrieve the data from a mysql database on a jsp page, When the page loads, it loads the latest data (which is what i want), but then when i click on the refresh button i made it refreshes the table with older data and then the button doesnt work after that (wont refresh the table).
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<h1>
<strong>test page</strong>
</h1>
<hr />
<canvas id="mycanvas" width="400" height="186"></canvas>
<script src="JavaScript/smoothie.js"></script>
<script src="JavaScript/chart.js"></script>
<script src="JavaScript/basic.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#refresh").click(function(){
$("#heart_rate").load("basic2.jsp")
});
});
</script>
</head>
<body>
<br>
<br>
<button id="refresh">Refresh table</button>
<br>
<br>
<form method="post" name="form">
<table id="heart_rate" border="1">
<tr>
<th>Sensor id</th>
<th>Time stamp</th>
<th>Heart rate</th>
<th>Event time</th>
</tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "Avantidrome";
String driver = "com.mysql.jdbc.Driver";
String un ="root";
String pw="root";
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, un, pw);
String sql = "select * from avantidrome.heartratedata order by timestamp DESC limit 10";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
</tr>
<%
}
%>
<%
} catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
once the button is clicked it calls basic.jsp which is just:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br>
<br>
<form method="post" name="form">
<table id="heart_rate" border="1">
<tr>
<th>Sensor id</th>
<th>Time stamp</th>
<th>Heart rate</th>
<th>Event time</th>
</tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "Avantidrome";
String driver = "com.mysql.jdbc.Driver";
String un ="root";
String pw="root";
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, un, pw);
String sql = "select * from avantidrome.heartratedata order by timestamp DESC limit 10";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
</tr>
<%
}
%>
<%
} catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
all it needs to do is for the button to select the newest data from the database and return it to the table whenever it is clicked.
There are two ways to do what you want:
When the user press the refresh button, you simple refresh the page (this should be so fast that he wont notice that the page changed)
Using ajax. So, if choose this option you need to understand that to do this you only need one jsp (the one that loads the page in the begin and has the refresh button), a scrip of javascript that handles the refresh button and uses ajax to get the new data, and a servlet that receives the ajax request and returns an ajax response in json/xml containing the updates.
In my opinion, I prefer the first option, but if you choose to go for the second one, heres another SO post that may help you: How to use Servlets and Ajax?

Why no files found using file uploading in Struts 2

I am using org.apache.commons.*, org.apache.commons.disk.*, org.apache.commons.fileupload.servlet.* packages for file uploading in JSP program and there was no need of Struts and it was working great, data easily worked with this, but when I added Struts 2 core libraries into my web project using MyEclipse 8.5 it is not working and have no fields found. May be the program is with upload.parseRequest.
Frankly, I am unable to understand the problem, so I share my program too
AddCategory.jsp:
<html>
<head>
<meta http-equiv="refresh" content="30">
</head>
<script type="text/javascript">
function blank() {
if (document.cate.cat.value == "Enter New Category") {
alert(" Category must not be blanked !!!");
document.cate.cat.focus();
return false;
}
else if (!document.getElementById("file1").value) {
alert("No file selected");
return false;
}
else {
return true;
}
}
</script>
<form name="cate" action="CategoryAdded.jsp" method="post" enctype="multipart/form-data" onsubmit="return blank()">
<table width="100%" border="0">
<tr>
<th colspan="2" scope="col">
<div align="center">Create New Category</div>
</th>
</tr>
<tr>
<td width="50%">
<div align="right">Enter New Category:</div>
</td>
<td width="50%">
<input name="cat" type="text" id="cat" value="Enter New Category"
onFocus="if(this.value== 'Enter New Category'){ this.value='' ; this.style.background='white';}"
onBlur="if(this.value==''){this.value='Enter New Category'; this.style.background='lightyellow'}">
</td>
</tr>
<tr>
<td width="50%">
<div align="right">Upload photo:</div>
</td>
<td width="50%"><input name="file1" type="file" id="file1"></td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Add Category">
</div>
</td>
</tr>
</table>
</form>
</html>
CategoryAdded.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%#page import="java.io.*" %>
<%# page language="java" errorPage="" %>
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.io.*" %>
<%#page import="java.util.Iterator,java.util.List" %>
<%#page import="org.apache.commons.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.*" %>
<%# page import="java.util.*" %>
<%#page import="org.apache.commons.fileupload.FileItemFactory" %>
<%#page import="org.apache.commons.fileupload.FileItem" %>
<%#page import="org.apache.commons.fileupload.FileUploadException" %>
<%#page import="p1.DBInfo" %>
<%#page import="p1.Identy" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<%
String pname = "";
Identy id = new Identy();
String cod = id.code();
boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
if (!isMultipartContent) {
System.out.println("No multipart found");
return;
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
System.out.println("No fields found");
return;
}
DBInfo obj = new DBInfo();
Connection cn = obj.getConn();
PreparedStatement ps = cn.prepareStatement("insert into category values(?,?,?)");
while (it.hasNext()) {
FileItem fileItem = it.next();
if (fileItem.getFieldName().equals("cat")) {
pname = fileItem.getString();
System.out.println("category name is " + pname);
}
boolean isFormField = fileItem.isFormField();
if (!isFormField) {
String s = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
fileItem.write(new File("D:\\Practice\\ShoppingCart\\WebRoot\\images\\" + s));
System.out.println(s);
fileItem.getOutputStream().close();
ps.setString(3, "D:\\Practice\\ShoppingCart\\WebRoot\\images\\" + s);
}
}
ps.setString(1, pname);
ps.setString(2, pname + cod);
int i = ps.executeUpdate();
if (i == 1) {
%>
<head>
<script type="text/javascript">
function myFunction() {
var r = confirm("New Category Added Successfully!!!\nIf you Want to Add more New Category then Press Ok!!!");
if (r == true) {
window.location = "AddCategory.jsp";
}
else {
window.location = "Tryy.jsp";
}
}
</script>
</head>
<body onload="myFunction()">
</body>
<%
}
cn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</html>
The best thing is to rewrite the JSPs to remove scriptlets and move business logic to the action classes.
You could also use Struts2 <s:if> and <s:else> tags to render content conditionally.
The commons-fileUpload is the default implementation for uploading files in Struts2, to use it correctly you could run an example Struts2 project like struts-2-upload-multiple-files-example.

Categories

Resources