Returning a message to a JSP - java

I'm having some trouble returning a string to a component on a JSP page. I have built a very simple page as follows:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<div id="logindiv" class="centered">
<h1>DB Schema status</h1>
<form action="DBConnectionTester" method="post">
<input type="text" name="usr" placeholder="DB Username" style="text-align: center;">
<br>
<input type="password" name="pwd" placeholder="DB Password" style="text-align: center;">
<br>
<input type="submit" value="Get Schema" class="btn btn-default btn-xs">
<br>
<br>
<c:if test="${not empty rtnmsg}">
<h6>${message}</h6>
</c:if>
</form>
</div>
And the class behind it is as follows:
#WebServlet("/DBConnectionTester")
public class DBConnectionTester extends HttpServlet {
String rtnmsg = "";
DBConnection dbcon = new DBConnection();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
dbcon.usr = request.getParameter("usr");
dbcon.pwd = request.getParameter("pwd");
dbcon.sampletest();
rtnmsg = dbcon.rtnstr;
}
}
For clarification, DBConnection is as follows:
public class DBConnection {
public String usr;
public String pwd;
private static String mySQLCon = "jdbc:mysql://<REDACTED>zeroDateTimeBehavior=convertToNull";
public String err;
public String stmt;
public String rtnstr;
void sampletest()
{
try
{
Connection mCon = DriverManager.getConnection(mySQLCon, usr, pwd);
mCon.getSchema();
err = "No connection issues";
}
catch (SQLException e)
{
err = e.toString();
}
Date date = new Date();
rtnstr = err + date.toString();
}
}
Now, whenever I hit that submit button, my browser appears to access the class itself - that is to say, the URL in the browser is as follows: http://<REDACTED>elasticbeanstalk.com/DBConnectionTester
What am I missing here?

Related

Java error when using two submit buttons on two different forms in a jsp

I am having some trouble figuring out why I am getting an error with my code. Below is my JSP file (the problem is with the second form):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Book Drivers</title>
</head>
<body>
<h1>Book Demands</h1>
<form method="POST" action="BookDriver.do">
<br>View a table </br>
<input type="radio" name="tbl" value="ListTodaysDemands">List Todays Demands<br />
<input type="radio" name="tbl" value="ListAllDemands">List All Demands<br />
<input type=submit value="Go!"> <br />
</form>
</body>
<body>
<h2>Demands</h2>
<%=(String)(request.getAttribute("query"))%>
</body>
<body>
<h2>Journeys</h2>
<%=(String)(request.getAttribute("query1"))%>
</body>
<body>
<h2>Drivers</h2>
<%=(String)(request.getAttribute("query2"))%>
</body>
<body>
<h2>Book taxi</h2>
<form method="POST" action="BookDriver.do">
<table>
<tr>
<th></th>
<th>Please provide your following details</th>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td>Destination:</td>
<td><input type="text" name="destination"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" name="date"/></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" name="time"/></td>
</tr>
<tr>
<td> <input type="submit" value="Book"/></td>
</tr>
</table>
</form>
</body>
Below is my controller:
public class BookDriver extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
LocalDate date = LocalDate.now();
String qry1 = "select * from CUSTOMER";
String qry2 = "select * from DRIVERS";
String qry3 = "select * from DEMANDS where date = '"+date+"'";
String qry4 = "select * from DEMANDS";
String qry5 = "select * from JOURNEY";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Date = Journey.Date LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(false);
Jdbc dbBean = new Jdbc();
dbBean.connect((Connection)request.getServletContext().getAttribute("connection"));
session.setAttribute("dbbean", dbBean);
if((Connection)request.getServletContext().getAttribute("connection")==null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
else if (request.getParameter("tbl").equals("ListTodaysDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current journeys";
try {
msg = dbBean.retrieve(qry3);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
else if (request.getParameter("tbl").equals("ListAllDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current drivers";
try {
msg = dbBean.retrieve(qry4);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
///////////THIS PART NOT WORKING//////////////////////////
String [] query = new String[5];
query[0] = (String)request.getParameter("name");
query[1] = (String)request.getParameter("address");
query[2] = (String)request.getParameter("destination");
query[3] = (String)request.getParameter("date");
query[4] = (String)request.getParameter("time");
Jdbc jdbc = (Jdbc)session.getAttribute("dbbean");
if (jdbc == null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
if(query[0].equals("") ) {
request.setAttribute("msg", "Username cannot be NULL");
}
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
The first form in the JSP works absolutely fine, the issue is with the second form. Whenever I use the button "Book" I get a null pointer exception and I cannot figure out why and if I comment out all of the code to due with the first form in the servlet, then it no longer throws the exception and it works fine.
I would really appreciate some help with this as I have now spent hours searching for a solution online and i'm still very much struggling to solve the problem.
Cheers,
Use request.getParameterValues("name").. and same for others too maybe the current value be null

Why deos Weblogic log says bean can not be resolved when I try to use the bean class object in a jsp file?

I was trying to make a simple E-Commerce website using MVC architecture in java. Initially I made a controller servlet which is named TestingServlet,a web.xml file,a bean class in the package com.bean under classes folder named DbBean and a Default.jsp,Header.jsp,Menu.jsp to start with. I compiled bean and the servlet classes. Then finally when I deployed the application on WebLogic server and run it, I got the following error-
As you can see in the log that it says it failed to compile JSP JSP/Menu.jsp which means the problem must be with Menu.jsp. Moreover, it says that in line 28 bean cannot be resolved. So, I checked that part of the code but it looks fine to me. What is causing the problem?
Following are all the files that I made-
TestingServlet.java
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.bean.DbBean;
public class TestingServlet extends HttpServlet
{
public void init(ServletConfig conf)
{
System.out.println("Initiallizing ControllerServlet");
ServletContext ctx = conf.getServletContext();
ctx.setAttribute("base",conf.getInitParameter("base"));
System.out.println("base = " +conf.getInitParameter("base"));
ctx.setAttribute("imageUrl",conf.getInitParameter("imageUrl"));
System.out.println("imageUrl = " +conf.getInitParameter("imageUrl"));
DbBean bean = new DbBean();
bean.setDbUrl(conf.getInitParameter("dbUrl"));
bean.setDbUserName(conf.getInitParameter("userName"));
bean.setDbPassword(conf.getInitParameter("password"));
ctx.setAttribute("bean",bean);
System.out.println("bean object successfully made,its properties set
and set in app scope..");
try
{
Class.forName(conf.getInitParameter("jdbcDriver"));
System.out.println("Driver Class Loaded Successfully");
}
catch(Exception e)
{
System.out.println("Could not load the driver class");
}
}
protected void doGet(HttpServletRequest req , HttpServletResponse res)
throws ServletException,IOException
{
doPost(req,res);
System.out.println("in doGet method");
}
protected void doPost(HttpServletRequest req , HttpServletResponse res)
throws ServletException,IOException
{
System.out.println("in doPost method");
String base = "/jsp/";
String url = base + "Default.jsp";
String action = req.getParameter("action");
if(action!=null)
{
if(action.equals("search"))
url = base + "SearchResults.jsp";
else if(action.equals("browseCatalog"))
url = base + "BrowseCatalog.jsp";
if(action.equals("productDetails"))
url = base + "ProductDetails.jsp";
if(action.equals("addShoppingItem") ||
action.equals("updateShoppingItem") ||
action.equals("deleteShoppingItem") ||
action.equals("displayShoppingCart"))
url = base + "ShoppingCart.jsp";
if(action.equals("checkOut"))
url = base + "CheckOut.jsp";
if(action.equals("order"))
url = base + "Order.jsp";
}
System.out.println("if part successfully executed");
RequestDispatcher rd = req.getRequestDispatcher(url);
System.out.println("RD object made successfully..");
rd.forward(req,res);
System.out.println("forward successfully executed..");
}
}
DbBean.java
package com.bean;
import java.sql.*;
import java.util.Hashtable;
public class DbBean
{
public String dbUrl = "";
public String dbUserName = "";
public String dbPassword = "";
public void setDbUrl(String url)
{
dbUrl = url;
}
public void setDbUserName(String userName)
{
dbUserName = userName;
}
public void setDbPassword(String password)
{
dbPassword = password;
}
public Hashtable getCategories()
{
Hashtable categories = new Hashtable();
try
{
Connection conn =
DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
Statement stmt = conn.createStatement();
String sql = "select CategoryId,Category from Categories" +" ";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
categories.put(rs.getString(1),rs.getString(2));
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException e)
{}
return categories;
}
}
Default.jsp
<html>
<head>
<title>Welcome</title>
</head>
<body>
<table>
<tr>
<td colspan="2">
<jsp:include page="Header.jsp" flush = "true"/>
</td>
</tr>
<tr>
<td>
<jsp:include page="Menu.jsp" flush="true"/>
</td>
<td valign="top">
<H2>WELCOME TO MY E-MALL.</H2>
</td>
</tr>
</table>
</body>
</html>
Menu.jsp
<%# page import="java.util.*" %>
<jsp : useBean id = "bean" scope = "application" class="com.bean.DbBean" />
<%
String base = (String)application.getAttribute("base");
%>
<table cellspacing="0" cellpadding="5" width="150" border="0">
<tr>
<td bdcolor="F6F6F6">
<font face="Verdana">Search</font>
<form>
<input type="hidden" name="action" value="search">
<input type="text" name="keyword" size="10">
<input type="submit" value="Go">
</form>
</td>
</tr>
<tr >
<td bgcolor="F6F6F6">
<font face="Verdana">
Categories:
</font>
</td>
</tr>
<tr valign="top">
<td bgcolor="F6F6F6">
<%
Hashtable categories = bean.getCategories();
Enumeration categoryIds = categories.keys();
while(categoryIds.hasMoreElements())
{
Object categoryId = categoryIds.nextElement();
out.println("<a href=" +base +"?
action=browseCatalog&categoryId=" +categoryId.toString()
+">" +categories.get(categoryId) +"</a><br>");
}
%>
</td>
</tr>
</table>
The jsp : useBean is for use with Objects that are Java Beans.
Is it the case that DbBean does not adhere to the JavaBeans conventions i.e. have a look at What is a JavaBean exactly? and maybe you could change DBean to adhere to the conventions or you could just drop the use of jsp : useBean and just instansiate and manipulate it in the scriptlet?

CRUD web application in Java with Servlet,JSP and MySQL without DAO

I am working on a simple home library web application using Java EE, Servlets, JSP, and MySQL. My Create, Read, and Delete are working fine but Update is not working. I am not using any form of design patterns, just servlets and POJO. All examples i try to learn from seem to have used MVC and DAO design patterns. Is there any way to achieve the CRUD application without using MVC and DAO patterns? What is the recommended and best practice for such a simple application?
here is code:
UpdateBook.jsp
<%# page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<%# page import ="java.util.ArrayList"%>
<%#page import="book.Book"%>
<!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=gbk">
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
<title>Updated Library Collection</title>
</head>
<body>
<div id="container">
<div id="header"><h1 align="center" style="color:blue">Edit Library Collection</h1></div>
<div id="wrapper">
<div id="content" align="center">
<%
request.setCharacterEncoding("gbk");
String ISBN=request.getParameter("Isbn");
String BookTitle=request.getParameter("Title");
String BookAuthor=request.getParameter("Author");
String Category=request.getParameter("Category");
String Description=request.getParameter("Description");
%>
<table width="100%" border="0" cellspacing="0" cellpadding="4" align="center" >
<tr>
<td width="100%" bgcolor="#EAEAEA" colspan="2">
<form name="bookUpdate" action="/homelibrary/UpdateBookServlet" method="POST">
<p>
<label for="Isbn">ISBN: </label>
<input type="text"readonly name="Isbn" id="Isbn" value=<%=ISBN%> >
<br><br>
<label for="Title">Title: </label>
<input type="text" name="Title" id="Title" value=<%=BookTitle%>>
<br><br>
<label for="Author">Author: </label>
<input type="text" name="Author" id="Author" value=<%=BookAuthor%>>
<br><br>
<label for="Category">Category: </label>
<input type="text" name="Category" id="Category" value=<%=Category%>>
<br><br>
<label for="Description">Description: </label>
<input type="text" name="Description" id="Description" value=<%=Description%>>
<br><br>
<p>
<input type="submit" name="Submit" value="Submit" onclick="goto">
<input type="button" name="Cancel" value="Cancel" onclick="javascript:history.go(-1);">
</p>
</form>
</td>
</tr>
</table>
</div>
</div>
<div id="footer" align="center">
<p>© Home Library</p>
</div>
</body>
</html>
UpdateBookServlet.java
package book;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/UpdateBookServlet")
public class UpdateBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UpdateBookServlet(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//String forward="";
String action = request.getParameter("action");
if (action == ("edit")){
String Isbn = request.getParameter("Isbn");
Book book = null;
try {
book = this.getBookByIsbn(Isbn);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("book", book);
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/UpdateBook.jsp");
dispatcher.forward(request,response);
}
//#SuppressWarnings("unused")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Book book = new Book();
response.setContentType("text/html");
request.setCharacterEncoding("gbk");
//Get data from form data
String ISBN = request.getParameter("Isbn");
String BookTitle = request.getParameter("Title");
String BookAuthor = request.getParameter("Author");
String Category = request.getParameter("Category");
String Description = request.getParameter("Description");
//#SuppressWarnings("unused")
//PreparedStatement preStmt = null;
//Connection cn =null;
try {
//Create a java MySQL database connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/ebookstore";
Connection cn = DriverManager.getConnection(url, "admin", "admin");
PreparedStatement prepStmt= null;
if(ISBN != null)
// create the java MySQL update PreparedStatement
prepStmt = cn.prepareStatement("UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=?");
//String update = "UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=1111";
//prepStmt = cn.prepareStatement(update);
prepStmt.setString(1, book.getTitle());
prepStmt.setString(2, book.getAuthor());
prepStmt.setString(3, book.getCategory());
prepStmt.setString(4, book.getDescription());
prepStmt.setInt(5, Integer.parseInt(book.getISBN()));
//execute the java preparedStatment
prepStmt.executeUpdate();
cn.close();
prepStmt.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
//forwarding from Servlet to a JSP
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/QueryBook.jsp");
dispatcher.forward(request,response);
}
public Book getBookByIsbn(String isbn) throws ClassNotFoundException {
Book book = new Book();
try {
//Create a java MySQL database connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/homelib";
Connection cn = DriverManager.getConnection(url, "root", "admin");
PreparedStatement preparedStatement = cn.
prepareStatement("SELECT * FROM book where Isbn=?");
preparedStatement.setString(1, isbn);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
book.setISBN(rs.getString("Isbn"));
book.setTitle(rs.getString("Title"));
book.setAuthor(rs.getString("Author"));
book.setCategory(rs.getString("Category"));
book.setDescription(rs.getString("Description"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return book;
}
}
Button in QueryBook.jsp
<td>Update</td>
This example is for updating a book's information when a user is logged in on the session
Insert this at the top of your JSP to identify the user on the session
if (session!=null && request.getSession().getAttribute("loggedin") != null) {
if (request.getSession().getAttribute("role").equals("Student")) {
response.sendRedirect("index.jsp");
return;
}
} else {
response.sendRedirect("index.jsp");
return;
} %>
<% if (request.getSession().getAttribute("loggedin") == null) {
response.sendRedirect("index.jsp");
return;
}
BookDTO dto = (BookDTO) request.getSession().getAttribute("book");
Then insert this code below in the JSP to post new data to the servlet
<form method="POST" action="EditBookServlet">
<div class="form-submit">
My Information
<div class="submit">
<div class="form-row">
<div class="x">
<label>Name</label>
<input type="text" class="form" value="<%= dto.getName()%>" name="name">
</div>
<div class="x">
<label>Author</label>
<input type="author" class="form" value="<%= dto.getAuthor()%>" name="author">
</div>
<div class="form x">
<button class="btn" type="submit">Save Changes</button>
</div>
</div>
</div>
</form>
In the EditBookServlet, insert this code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
BookDB db = new BookDB();
BookDTO dto = db.getBookByID(((BookDTO)
request.getSession().getAttribute("book")).getId());
dto.setName(request.getParameter("name"));
dto.setAuthor(request.getParameter("author"));
db.updateBook(dto);
request.getSession().setAttribute("book", dto);
In the StudentDB java file insert this to find the book by Id and then to update the book sql file
public BookDTO getBookByID(int id) {
BookDTO obj = null;
String query = "Select * from book where id=?";
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = conn.prepareStatement(query);
pst.setInt(1,id);
rs = pst.executeQuery();
if (rs != null) {
if (rs.next()) {
obj = new BookDTO();
obj.setId(rs.getInt(1));
obj.setName(rs.getString(2));
obj.setAuthor(rs.getAuthor(3));
} catch (SQLException ex) {
Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
public boolean updateBook(BookDTO obj) {
int affectedRows = 0;
String query = "update `book` set name=? , author=lower(?) where id=?";
PreparedStatement pst = null;
try {
pst = conn.prepareStatement(query);
pst.setString(1,obj.getName());
pst.setString(2,obj.getAuthor());
pst.setInt(10, obj.getId());
System.out.println(pst);
affectedRows = pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
return affectedRows > 0;
}
You said in your comment:
The update page return with null for all the values.
That is, because you intantiate the Book object In UpdateBookServlet.java
Book book = new Book();
but you set the request parameters into separate string objects:
String ISBN = request.getParameter("Isbn");
String BookTitle = request.getParameter("Title");
String BookAuthor = request.getParameter("Author");
String Category = request.getParameter("Category");
String Description = request.getParameter("Description");
But never use them. Instead you add data from the empty Book object:
prepStmt.setString(1, book.getTitle());
prepStmt.setString(2, book.getAuthor());
prepStmt.setString(3, book.getCategory());
prepStmt.setString(4, book.getDescription());
prepStmt.setInt(5, Integer.parseInt(book.getISBN()));

Cannot pass multipart data to servlet when using jsp el

I am passing checkbox values, username , file as parameter to a servlet that uses MultipartRequest class from com.orielly.servlet package. I am using the jsp el in my jsp.
my jsp is
<c:set var="currentUser" value="${currentUser}" />
<div class="container">
<div class="panel panel-default" >
<div class="panel-body">
<div class="panel panel-default">
<div class="panel-body">
<form action="ProcessShareFileReq?username="${currentUser}" method="post" enctype="multipart/form-data">
<h4>Upload file here</h4>
<input type="file" class="form-control" required="required" name="file" value=""/>
<h4 class="page header">Share with</h4>
<ul class="list-group">
<c:forEach var="request" items="${requestList}">
<li class="list-group-item title">
<input type="checkbox" name="usersList" value="${request.senderFullName}" /><strong> ${request.senderFullName} </strong>
</li>
</c:forEach>
</ul>
<label class="label" for ="description">Description(Helps other users understand the content of file)</label>
<textarea id="description" name="fileDescription" rows="10" cols="5"></textarea>
<div class="break"></div>
<input type="submit" class="btn btn-default pull-left" value="Upload">
<input type="reset" class="btn btn-default pull-left" value="Reset">
</form>
</div>
</div>
</div>
</div>
</div>
my servlet
#WebServlet("/ProcessShareFileReq")
#MultipartConfig
public class ProcessShareFileReq extends HttpServlet {
private static final long serialVersionUID = 1L;
private String webTempPath;
public void init( ) {
webTempPath= "C://BEProject/Shared";
//webTempPath = getServletContext( ).getRealPath("/") + "data";
}
//Generates current time suitable for oracle timestamp
private static java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection currentCon =null;
PreparedStatement ps = null;
int result;
//list of users to share with
String[] UserList = request.getParameterValues("usersList");
//logged-in-user's username
String loggedInUser = request.getParameter("username");
//Shared file's description
String fileDescription = request.getParameter("fileDescription");
//adding path according to sharer's user-name
String userPath = webTempPath + "/" + loggedInUser;
//generate directory
boolean success =( new File(userPath)).mkdirs();
//make directory
if(success) {
System.out.println("Directory: " + webTempPath + " created");
}
//Renames file to the 'sharer_receipent_timestamp' pattern
//Get the uploaded file with multipartRequest
//file limit size of 50 MB
MultipartRequest mpr = new MultipartRequest(request,userPath,50 * 1024 * 1024);
//Database create operations.
Enumeration enum1 = null;
try {
currentCon = ConnectionManager.getConnection();
currentCon.setAutoCommit(true);
for(int i=0;i<UserList.length;i++)
{
String shareFileQuery = "insert into sharedfiles values(share_seq.NEXTVAL,?,?,?,?,?)";
ps = currentCon.prepareStatement(shareFileQuery);
//set the values to put in the query
ps.setString(1, loggedInUser);
ps.setString(2, UserList[i]);
enum1 = mpr.getFileNames( );
String filename = mpr.getFilesystemName((String) enum1.nextElement());
ps.setString(3, filename);
ps.setString(4, fileDescription);
ps.setTimestamp(5, getCurrentTimeStamp());
result=ps.executeUpdate();
if(result>0)
{
System.out.println("Database updated \n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
response.setContentType("text/html");
request.setAttribute("username", loggedInUser);
RequestDispatcher rd = request.getRequestDispatcher("/SharedFilesHistory");
rd.forward(request, response);
}
I have annotated the servlet with #MultipartConfig so that it can handle the file parameter.
But after adding this it goes upto to the last line and gives error as
java.io.IOException: Corrupt form data: premature ending
com.oreilly.servlet.multipart.MultipartParser.<init>(MultipartParser.java:207)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:223)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:110)
servlet.share.ProcessShareFileReq.doPost(ProcessShareFileReq.java:104)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
filter.authentication.AuthenticationFilter.doFilter(AuthenticationFilter.java:40)
When remvoving the MultipartConfig it gives a NullPointerException at the for loop since 'UserList' is null since no value is received in servlet from jsp.
Please help
I remember having some little issues when working with MultipartRequest (seems related to some bugs), which made me drop its usage in favor of the native Servelt 3.x Part and which may be a good alternative for you:
Inside your doPost method you can retrieve your file as a Part of the request using its name:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//...
Part filePart = request.getPart("file"); // Retrieves <input type="file" class="form-control" required="required" name="file" value=""/>
InputStream fileContent = filePart.getInputStream(); // Get an InputStream then let the file make its way to your storage location
}

passing value to a jsp page from a java class using DAO

I wanted to pass the value retrieved on a java class to a page.I am using DAO classes.
I have retrieved the values from the database and stored them on String variables.Now I want to set them to the text boxes in my view.jsp page.I am new to this area,can anyone help me out??
View.jsp is as
<%# 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>
<form action="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw"><br/><br/>
</form>
</body>
</html>
and My Activity ViewDAO.java is as
public static void view(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks...
If you are using a front controller[spring mvc] then you can pass the data by doing,
model.addAttribute("variable_name ", data);
and in the jsp you can access it by doing this ${variable_name};
You need to call the DAO method from your servlet like below:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// call DAO method to get the email and password
HashMap<String,String> map=ViewDAO.getDetails();
//from the map you will get the email and password.then you need to set them in the attributes and get them in your jsp
request.setAttribute("email", map.get("email"));
request.setAttribute("password", map.get("password"));
}
your DAO method should be like the below:
public static HashMap<String,String> getDetails(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
Map<String,String> map=new HashMap<>();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
map.put("email",email);
map.put("password",pass);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
Hope this will help you.
if you are using simple jsp and servelt, then make one ViewController.java.
You can two methods one for handling GET and other for POST
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String email = request.getParameter("email");
String password = request.getParameter("password");
request.setAttribute("email", email);
request.setAttribute("password", password);
request.getRequestDispatcher("view.jsp").forward(request, response);
}
catch(Exception e){
}
View.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>Insert title here</title>
</head>
<body>
<form action="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" value="<%=email%>" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw" value="<%=password%>"><br/><br/>
</form>
</body>
</html>
The Servlet decides which page must be loaded. So whatever you get from the DAO must go to the Servlet and through that, to the jsp. You can use a bean class to send values from DAO to Servlet.
Like this,
public class Details{
private String email;
private String password;
public void setEmail(String email){
this.email = email;
}
public void setPassword(String password){
this.password= password;
}
public String getEmail(){
return this.email;
}
public String getPassword(){
return this.password;
}
}
And you can make the following changes in DAO after getting the query results in the String. Add these
Details d = new Details();
d.setEmail(email);
d.setPassword(pass);
return d;
You can pass this object d to the servlet and retrieve the values using the getter methods of the bean. Also, the DAO must be called from the Servlet.
And now on the Servlet side.
On the Servlet you can put your code in the get or post method depending on your need. It may be like
public class ExampleServlet extends HttpServlet{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email"); //got from the jsp where "email" is the name attribute of the input field
Details d = new Details();
d = ViewDao.view(user_object); //the bean sent by DAO. "user_object" is parameter that your DAO method is taking in your code
if(d.getEmail()!=null){ //just an example
// your code that redirects desired page
}
}
}
Based on d returned by the DAO you may redirect to any page you want.
Something like that
Observe this import
dao.UserDao,bean.*,
dao is the package
UserDao is the class
bean is the method you want or is could an attribute from dao
remember that
jsp
<body>
<%#page import="dao.UserDao,bean.*,java.util.*"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Users List</h1>
<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>
<div class="table-responsive">
<table class="table">
<thread class="bg-info">
<th>Id</th><th>Name</th><th>Password</th><th>Edit</th><th>Delete</th>
</thread>
<c:forEach items="${list}" var="u">
<tr>
<td>${u.getId()}</td><td>${u.getUsername()}</td><td>${u.getPassword()}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</div>
<br/>Add New User
<br>
<br>
<form action="index.jsp">
<button type="submit">IndexUsers</button>
</form>
</body>
Bean or model
package bean;
// classe para as tables
public class User {
private int id;
private String username,password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
dao
public class UserDao {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql_database","root","14570");
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into login(username,password) values(?,?)");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update login set username=?,password=? where id=?");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
ps.setInt(3,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from login where id=?");
ps.setInt(1,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static List<User> getAllRecords(){
List<User> list=new ArrayList<User>();
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id){
User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}
Another Example this import import="dao.*"% makes available any methods from package dao, Bellow you see how to get the result of the method countid() in the dao.
<%#page import="dao.*"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<% int id = 0; %>
<%
DaoEvento daoEvento = new DaoEvento();
id = daoEvento.countId();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<body>
<br><br>
<form action="add_event_servletnew" method="POST">
<div class="form-group">
<td>
<font color='green' face = "Arial" size = "4">
<%= request.getParameter("message") %>
</font>
view
<td>
</div>
<div class="form-group">
<label>id</label>
<input type="text" name="id" value="<%= id%>" readonly="readonly" class="form-control"/>
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" value="" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<input type="date" name="start" value="" class="form-control"/>
</div>
<div class="form-group">
<label>End</label>
<input type="date" name="end" value="" class="form-control" />
</div>
<div class="form-group">
<td><input type="submit" value="submit" class="btn btn-success btn-block"/></td>
</div>
</form>
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
<script src="jquery.mask.min.js"> </script>
</html>

Categories