Servlet and JSP connection in eclipse EE IDE with MYSQL database - java

I am new to java.I am creating dynamic web Application in eclipse EE IDE with MYSQL database. I want to connect my database to app so far I have created JSP page for view. Below is my JSP code and Servlet for connection. I am not able to connect to database with this. My JSP page work fine. But I think problem is with Servlet. And also advice to I need to made the two java file one for Servlet and other for getting data from JSP page.
Thanks in advance.
Servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get user_name and pass_word from the JSP page
String toolfirst=request.getParameter("tname1");
String toolsecond=request.getParameter("tname2");
String toolvalue=request.getParameter("tvalue");
//Print the above got values in console
System.out.println("The username is" +toolfirst);
//Setting connection Parameters
String connectionparams=”jdbc:mysql://localhost:3306/tool”;
//database name
String db=”tool”;
//Mysql user name and password whichever you have given during installation
String uname=”root”
String psword=””
//Declaring classes required for Database support
Connection connection=null;
ResultSet rs;
try {
// Loading the available driver for a Database communication
Class.forName("org.gjt.mm.mysql.Driver");
//Creating a connection to the required database
connection = DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
//Add the data into the database
String sql = "insert into usertable values (?,?)";
PreparedStatement prep =
connection.prepareStatement(sql);
//Setting the values which we got from JSP form
prep.setString(1, tname1);
prep.setString(2, tname2);
prep.executeUpdate();
prep.close();
}catch(Exception E){
//Any Exceptions will be caught here
System.out.println(“The error is==”+E.getMessage());
}
finally{
//After the entire execution this block will execute and the connection with database gets closed
connection.close();
}
}
JSP
<%# 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>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="NewServlet">
<a id="add" href="javascript:void(0)">Add another Credit card</a>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr class="person">
<td><input type="text" name="tname1" id="name" /></td>
<td><input type="button" value="name" /></td>
<td><select name="tvalue">
<option>value1</option>
<option>value2</option></select>
<td><input type="text" name="tname2" id="name" /></td>
</tr>
</tbody>
</table>
<input type="submit" value="submit" >
</form>
Logout
</body>
</html>

without having a detailed errormessage I would say that you have a compile error here:
connection = DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
it should be at least:
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tool", root, psword);
btw remove the ResultSet. You dont use it.

You have a comma at the end of this statement with no value after it. I think your number of arguments are incomplete. I also assume the userID and password needs to be somewhere in the argument list.
DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
Whoops - someone answered the question before I could post this. Guess I need to type faster.

Related

How do you populate an html with data from an array list using servlet? [duplicate]

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>
<%}%>

JSP hand over text to java and another jsp [duplicate]

This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 7 years ago.
I have a JSP page with a textarea and a button, a servlet and a new jsp:
My 3 problems are:
My analysis.jsp is empty. My borwser opens a new tab but without the text "Hello World"
The variable "sql" in my java class is empty too. It should contain the text from my textarea
How can I hand over after my variable sql isn't empty (after analyze) new new code to a new jsp
index.jsp
<form action="ServletName" method="post" target="_blank">
<div class="form-group">
<label for="codeEditor" style="margin-top: 15px;">Code:</label>
<textarea name="codeEditor" class="form-control" id="codeEditor" rows="15" style="resize: none;"></textarea>
</div>
<div class="analysisButton">
<button type="submit" id="startAnalysis" class="btn btn-default btn-block" style="margin-top: 10px;">Start analysis</button>
</div>
</form>
ServletName.java
protected void doPost(...) ...{
String sql = request.getParameter("codeEditor");
response.sendRedirect("/analysis.jsp");
}
analysis.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
Many thanks in advance
UPDATE: nevermind the variable sql isn't empty <(^,^<) but the other 2 questions are open :)
Yes, this may be as simple as
JSP
<form action="some_url" method="post" >
<inputarea name="sqlQuery" >
<input type="submit" value="Sql query" >
<form >
In your servlet, you'll have something like
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
...//check that the request is correct
String query = request.getParameter("sqlQuery");//name of textarea
try{
Connection conn = getConnection();//Search SO for how to get a connection
PreparedStatement stmt = conn.prepareStatement(query);
//if your query has any arguments(?) (e.g select * from tbl where id=?), then you should set them too
//stmt.setInt(1, 1000);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
//get database dana here
int someIntVal = rs.getInt("intColumn");
String someStr = rs.getString("someStringColumn");
}catch(SQLException e){
//handle exception
}
}
You could do this using a simple form submit:
<form method="POST" action="/myServletPath">
<inputarea name="sqltext" ...
Your servlet (with url mapping 'myServletPath') can then, in the doPost method:
String sql = request.getParameter("sqltext")...
And then do whatever you want.
WARNING: If this is code for your production application, then be aware of SQL injection attacks. This is typically code you wouldn't write for any application that trusts users other than yourself.

Using JSP to store images in Mysql and upload the images online

I am still wondering what it is that i am doing wrong,my problem is i dont know if it is my entire sample code which has na error or my connection to the database which has an issues, as of where i stand i am not sure what is making me get this error. (displayed below).I have tried to look here at stack overflow but all i get is loading images using JSP but not adding them to the database. If we have one i couldnt trace please help me with the link. I have included all the libraries needed and my code has no error apart from this output. I came here because i am stranded and need a short review of what you proffesionals think is wrong with my code as done below. I will really appreciate anyhelp given as i am working on a deadline.
my Database name is
AppDB
I was wondering should i use the name of the table? to INSERT INTO? which is
'contacts'
Error Message
HTTP Status 404 - /UploadImageOnWeb/uploadServlet type Status report
message /UploadImageOnWeb/uploadServlet description The requested
resource is not available. Apache Tomcat/8.0.23
Thank you
Java Servlet Code
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class FileUploadDBServlet
*/
#MultipartConfig(maxFileSize = 16177215)
#WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// database connection settings
/*private String dbURL = "jdbc:mysql://localhost/AppDB";
private String dbUser = "root";
private String dbPass = "mypassword";*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// connects to the database
/*DriverManager.registerDriver("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My .Jsp class
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="firstName" size="20"/></td>
</tr>
<tr>
<td>Enter Last Name: </td>
<td><input type="text" name="lastName" size="20"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="20"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Display Jsp
<%# 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>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The 404 error indicates that the form is not even getting to the servlet.
You defined the action attribute in the form as uploadServlet which doesn't seem to be a valid URL for your application.
The servlet's URL is defined in the #WebServlet annotation as FileUploadDBServlet.
So you can fix it by changing the action in the form or changing the URL for the servlet.

How to display a data table in a JSP page Struts2

So I have been reading on this topic for a couple of days now, and every time I think I understand it I get confused again.
So what I have: A MySQL data base, eclipse, tomcat apache, the beginnings of a GUI using STRUTS2
I am setting up a gui for said database and I want to display one of the data tables in my JSP page. So my problem... well I have a lot of problems but initially, I have a form that is I have an action sending me to the JSP page I want to display my table in. I thought I would use another action to connect to the database and obtain all my information, but I'm not sure if that makes sense anymore, should I just use the same action?
Well... here are bits of my code:
Action to get the data:
package net.upsmon.struts2.action;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.opensymphony.xwork2.ActionSupport;
public class Table extends ActionSupport {
List tableRows=new ArrayList();
public String execute() throws InstantiationException, IllegalAccessException, ClassNotFoundException{
List tableInfo=new ArrayList();
Properties props = new Properties();
props.setProperty("user", "user");
props.setProperty("password", "pass");
props.setProperty("databaseName", "db");
String dbUrl="jdbc:mysql://db:3306/db";
String ret = ERROR;
Connection myCon = null;
try{
Class.forName ("com.mysql.jdbc.Driver").newInstance();
myCon = DriverManager.getConnection("jdbc:mysql://dburl:3306/mqmonitordb",props);
String dbQuery = "SELECT * FROM table";
PreparedStatement ps = myCon.prepareStatement(dbQuery);
ResultSet result=ps.executeQuery(dbQuery);
while(result.next()){
tableInfo.add(result.getString("raisedAlertId"));
tableInfo.add(result.getString("alertHostIP"));
tableInfo.add(result.getString("portNumber"));
tableInfo.add(result.getString("qMgrName"));
tableInfo.add(result.getString("alertType"));
tableInfo.add(result.getString("alertGroupName"));
tableInfo.add(result.getString("alertEntity"));
tableInfo.add(result.getString("maintMode"));
tableInfo.add(result.getString("alertCreatedTime"));
tableInfo.add(result.getString("alertRaisedTime"));
tableInfo.add(result.getString("alertAckFlag"));
tableRows.add(tableInfo);
tableInfo.clear();
}
//request.setAttribute("tableRows",tableRows);
}catch(SQLException sqe){
}catch(Exception e){
}
return "yay";
}
public List tableRows() {
return tableRows();
}
public void setTableRows(List tableRows) {
this.tableRows = tableRows;
}
}
JSP page:
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<title>Welcome</title>
</head>
<body>
<h2>
Welcome
</h2>
<table>
<thead>
<tr>
<th></th>
<th>column1</th>
<th>column2</th>
</tr>
</thead>
<tbody>
<s:iterator status="stat" value="tableRows">
<tr>
<td><s:property value="#stat.index+1"></s:property></td>
<td><s:property value="%{column1}"></s:property></td>
<td><s:property value="%{column2}"></s:property></td>
</tr>
</s:iterator>
</tbody>
</table>
<s:form action="logout" method="post" margin="auto">
<s:submit method="authenticate" key="label.logout" align="center" />
</s:form>
<s:form action="tolevelselector" method="post" margin="auto">
<s:submit method="authenticate" key="label.levelthree" align="center" />
</s:form>
</body>
</html>
Any advice would be great, thanks....

forward from servlet to jsp causes form submission errors

I'm forwarding to a jsp that shows a table and a form for comments populated by jstl sql tags.
The problem is that the form works fine if I use response.sendRedirect("comments.jsp");
But since I need to retain session info between pages I want to use request.getRequestDispatcher("comments.jsp").forward(request, response);
which triggers the post form and redirects subsequent posts to the servlet url.
LoginServlet
public class LoginServlet extends HttpServlet {
Connection connection = null;
PreparedStatement ptmt = null;
ResultSet resultSet = null;
User user = null;
boolean fail = true;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if (null != email && null != password) {
try {
connection = ConnectionFactory.getInstance().getConnection();
user = new User();
String queryString = "SELECT * FROM USERINFO WHERE EMAIL=?";
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, email);
resultSet = ptmt.executeQuery();
resultSet.next();
user.setEmail(resultSet.getString("EMAIL"));
...
user.setSecret3(resultSet.getString("SECRET3"));
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
}
}
if (null != user.getPassword() && user.getPassword().equals(password)) {
request.setAttribute("user",user);
request.getRequestDispatcher("comments.jsp").forward(request, response);
// response.sendRedirect("comments.jsp");
}
comments.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Comments</title>
</head>
<body>
<sql:setDataSource var="dataSource" driver="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/mp1"
user="app" password="app"/>
<sql:setDataSource var="dataSource2" driver="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/mp1"
user="app" password="app"/>
<H2>Comments</H2>
<sql:query dataSource="${dataSource}" sql="SELECT * FROM COMMENTS" var="comments" />
<table border=1>
<c:forEach var="row" items="${comments.rows}">
<tr>
<c:forEach var="col" items="${row}">
<td><c:out value="${col.value}" /></td>
</c:forEach>
</tr>
</c:forEach>
</table>
<form method="post">
<table>
<tr>
<td>Enter Email</td>
<td><input type="text" name="EMAIL"></td>
</tr>
<tr>
<td>Enter Comment</td>
<td><input type="text" name="COMMENT"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
<c:if test="${pageContext.request.method=='POST'}">
<c:catch var="exception">
<sql:update dataSource="${dataSource2}" var="updatedTable">
INSERT INTO
COMMENTS (EMAIL,COMMENT)
VALUES (?, ?)
<sql:param value="${param.EMAIL}" />
<sql:param value="${param.COMMENT}" />
</sql:update>
<c:if test="${updatedTable>=1}">
<c:redirect url="/comments.jsp"/>
</c:if>
</c:catch>
<c:if test="${exception!=null}">
<c:out value="Unable to add comment." />
</c:if>
</c:if>
</body>
</html>
BTW, this is a homework assignment were the teacher wants us learn how it was done the old way. So security and better technologies to use are not real concerns.
PS. I've solved this by separating the comments and add comment into separate pages. Perhaps a better solution would be to use the session instead of the request for object transfer.
Both redirect and forward should retain session since session is supported by cookies (in most cases).
Your form doesn't have action parameter thus its behavior depends on the browser current URL (form gets posted to current URL instead of defined in action), and current URL is different in case of redirect and forward.

Categories