Values not being insert into Database from JSP form - html

I'm trying to get the doPost() method in my servlet to insert values from a JSP form into the database, however it doesn't seem to be working and I'd like to know if anyone here could help me out. Thank you. Here's the code below:
public boolean addOrder(Connection conn) {
boolean success = false;
// Declare JDBC objects
PreparedStatement ps = null;
try {
String sql = "INSERT INTO OrderInfo(SizeOfPizza, NumOfToppings, Quantity, "
+ " Delivery, Price) VALUES(?, ?, ?, ?, ?);";
ps = conn.prepareStatement(sql);
ps.setString(1, order.getPizzaSize());
ps.setInt(2, order.getNumToppings());
ps.setInt(3, order.getQuantity());
ps.setBoolean(4, order.isDelivery());
ps.setDouble(5, order.getPrice());
int count = ps.executeUpdate();
if (count > 0) {
success = true;
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
} finally {
DBConnection.closeJDBCObjects(conn, ps);
return success;
}
}
Servlet to insert into the database
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
OrderDAO dao = new OrderDAO();
DBConnection conn = (DBConnection)this.getServletContext().getAttribute("dbConn");
boolean ordersuccess = dao.addOrder(conn.getConnection());
HttpSession session = request.getSession();
session.setAttribute("ordersuccess", ordersuccess);
request.getRequestDispatcher("ReceiptPage.jsp").forward(request, response);
}
Page to fill in form and send off to the servlet
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Pizza Order Page</title>
<%
String fname = request.getParameter("firstName");
String lname = request.getParameter("lastName");
%>
<style>
body{
background-color: silver;
}
#title{
background-color: gray;
}
</style>
</head>
<body>
<h1 id="title" align="center">Hello <%out.print(fname + " " + lname);%></h1>
<p>Please fill out your order information</p>
<p><b>Delivery Options</b></p>
<form action="ReceiptServlet.do" method="POST">
<Select name="deliveryOption">
<option value="Pick Up">Pick Up</option>
<option value="Delivery">Delivery</option>
</Select>
<br>
<p><b>Size Options</b></p>
<input type="radio" name="size" value="Small">Regular ($5.00)<br><br>
<input type="radio" name="size" value="Large">Large ($7.00)
<br>
<p><b>Topping Choices</b></p>
<input type="radio" value="Pepperoni" name="topping">Pepperoni ($1.00)</option><br>
<input type="radio" value="Mushroom" name="topping">Mushroom ($1.00)</option><br>
<input type="radio" value="Olives" name="topping">Olives ($1.00)</option><br>
<input type="radio" value="Sausage" name="topping">Sausage ($1.00)</option><br>
<input type="radio" value="Pineapple" name="topping">Pineapple ($1.00)</option><br>
<br>
<p><b>Enter the amount of pizzas you would like to order</b></p>
<input type="text" name="pizzaQty">
<br><br>
<input type="submit" value="Place Order">
</form>
</body>

Related

MySQL database not updating values (JSP and Servlet project)

I am writing a JSP and Servlet project to register a user using their name, surname and password in Eclipse. When I enter the values in the webpage everything is ok, but when i check the database afterwards, the table values are not being updated(the table is still empty). Tomcat webserver was used. The code segments for MVC files used are as follows:
UserDAO.java
'''
public int registerUser(Users users) throws ClassNotFoundException{
String query = "INSERT INTO users" + "(id, name, surname, password) VALUES" + "(?, ?, ?, ?);"; int result = 0;
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/churchdb","root","");
//Step 2:Create a statement using connection object
PreparedStatement stmt = con.prepareStatement(query)){
stmt.setInt(1, 1);
stmt.setString(2, users.getUserName());
stmt.setString(3,users.getSurname());
stmt.setString(4, users.getPassword());
System.out.println(stmt);
//Step 3: Execute the query or update query
result = stmt.executeUpdate();
}
catch(SQLException e){
//process sql exception
e.printStackTrace();
}
return result;
}
'''
UserServlet.java
'''
private UserDAO userDao = new UserDAO();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/userregistration.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String surname = request.getParameter("surname");
String password = request.getParameter("password");
Users users = new Users();
users.setUserName(userName);
users.setSurname(surname);
users.setPassword(password);
try{
userDao.registerUser(users);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/userdetails.jsp");
dispatcher.forward(request, response);
}
}
'''
Userregistration.php
'''
<%# 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>Register</title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div align="center">
<h1>User Registration form</h1>>
<form action="<%= request.getContextPath() %>/register" method="post">
<table style="with: 80%">
<tr>
<td>Name</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" name="surname"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name=password/></td>
</tr>
</table>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
'''
NB: There is also javabean file

getting null value from request.getparameter("name"); com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException

getting exception whem i clicked on submit button
my all code works good but when i was add code for uploading image
then this error will occur
at these position i've done the changes
1. in html for enctype="multipart/form-data" newly added
2. in jsp added save image in project derectory
give me some solution......
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'name' cannot be null
my html form
<form method="post" enctype="multipart/form-data" >
<div class="intro">
<h1>Setup your Details</h1>
<h2></h2>
</div>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/slambook","root",
"");
Statement st = con.createStatement();
String user = (String) session.getAttribute("userid");
String qry = "select * from userdetails where `userid`='"+user+"'";
ResultSet result = st.executeQuery(qry);
while(result.next()){
//id = result.getInt("id");
%>
<input type="text" placeholder="Name" name="name" value="<%=result.getString("name")%>" required/>
<input type="number" placeholder="Contact No." name="cno" value="<%=result.getString("cno")%>" required/>
Choose File : <input type="file" name="file" required>
<textarea placeholder="Address" name="address" rows="4"><%=result.getString("address")%></textarea>
<input type="date" name="dob" value="<%=result.getString("dob")%>"/>
<input type="text" placeholder="Dream" name="dream" value="<%=result.getString("dream")%>" required/>
<input type="text" placeholder="Favorite Personality" name="favperson" value="<%=result.getString("favperson")%>" required/>
<input type="text" placeholder="Secret Crush" name="crush" value="<%=result.getString("crush")%>"/>
<%if(result.getString("userid").equals(null))
{
%><input type="submit" name="btnsave" value="Save Details" onclick="form.action='saveuserdetails.jsp';"/>
<input type="submit" name="btnupdate" value="update Details" onclick="form.action='updateuserdetails.jsp';"/>
<input type="reset" value="Clear" style="float: right;"><%
}
else
{%>
<input type="submit" name="btnupdate" value="update Details" onclick="form.action='updateuserdetails.jsp';"/>
<input type="reset" value="Clear" style="float: right;"><%
}
}
}
catch(Exception ex)
{
out.println(ex);
}
%>
this is my update jsp
<%#page import="java.io.*"%>
<%# page import ="java.sql.*,java.io.*,java.util.*" %>
<%
String uid = (String) session.getAttribute("userid");
String name = request.getParameter("name");
String cno = request.getParameter("cno");
//String picaddress = request.getParameter("file");
String address= request.getParameter("address");
String dob= request.getParameter("dob");
String dream= request.getParameter("dream");
String favperson= request.getParameter("favperson");
String crush= request.getParameter("crush");
String saveFile = "";
String contentType = request.getContentType();
if((contentType != null)&&(contentType.indexOf("multipart/form-data")>=0))
{
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength)
{
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead +=byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"")+10);
saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
saveFile =
saveFile.substring(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundry = contentType.substring(lastIndex
+1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n",pos)+1;
pos = file.indexOf("\n",pos)+1;
pos = file.indexOf("\n",pos)+1;
int boundryLocation = file.indexOf(boundry,pos)-4;
int startPos = ((file.substring(0,pos)).getBytes()).length;
int endPos = ((file.substring(0, boundryLocation)).getBytes()).length;
File ff =new File("C:/Users/Jarvis/Documents/NetBeansProjects/Slambook/web/ProfileImages/"+saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes,startPos,(endPos-startPos));
fileOut.flush();
fileOut.close();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/slambook",
"root", "");
out.println(address);
PreparedStatement ps = con.prepareStatement("update userdetails set name =?,cno = ?, address = ?,dob = ?,dream = ?,favperson = ?,crush = ?,imgstream = ? where userid = ?");
ps.setString(9, uid);
ps.setString(1, name);
ps.setString(2, cno);
ps.setString(3, address);
ps.setString(4, dob);
ps.setString(5, dream);
ps.setString(6, favperson);
ps.setString(7, crush);
ps.setString(8,ff.getPath());
ps.executeUpdate();
response.sendRedirect("userdetails.jsp");
}
catch(Exception e)
{
out.println(e);
}
}
%>
In order to catch specific SQLException, need to compare against SQl State using getSQLState() method. Ex: SQl State 23 for Data Integrity violation.
`catch (SQLException ex) {
if (ex.getSQLState().startsWith("23")) {
JOptionPane.showMessageDialog(null, "Duplicate");
}
}`
Found from here

I am getting error when i click submit button in jsp

I have taken reference from ->
https://www.quora.com/How-can-I-make-my-first-JSP-page-using-MySQL-database
At first jsp file is opening , i can input data but after clicking at submit , it gives error as in the image provided.
i m using tomcat v7.0 and it works correct for all other projects !
code->
Login.jsp file
<%# 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>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
Register.java file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");
PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}else{
out.println("Invalid User");
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
You forgot to add web.xml as in tutorial the servlet
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>

Action routing goes to same controller

I'm trying to link to a different controller with a HTTPPost action, however, when I try to it just appends my route values onto the current page's controller. For example, if I'm trying to link from Site/ViewIndex to Page/createPage with a form and a HTTPPOST, then it throws a 404 and says it can't access Site/Page/createPage. Why is it doing this and how can I stop it?
Here is my site/createPage:
public ActionResult createPage(int siteId, string title, string description, bool isBlog = false)
{
if (string.IsNullOrWhiteSpace(title) ||
string.IsNullOrWhiteSpace(description))
{
return RedirectToAction("ViewIndex", new { siteId = siteId, message = "Please fill out all fields" });
}
try
{
Ops.PageOps.createPage(title, description, siteId, isBlog);
return RedirectToAction("ViewIndex", "Site", new { siteId = siteId, message = "Page created!" });
}
catch (Exception e)
{
return RedirectToAction("ViewIndex", new { siteId = siteId, message = "Error occured: " + e.Message });
}
}
Here is my form:
<form method="post" action="Page/createPage">
<input class="form-field form-control" type="text" name="title" placeholder="Page Title" />
<input class="form-field form-control" type="text" name="description" placeholder="Page Description" />
<input class="form-field form-control" type="hidden" name="siteId" value="#site.Id" />
Blog page? <input class="form-field" type="checkbox" value="true" name="isBlog" /><br /><br />
<input class="btn btn-info" type="submit" value="Create" />
</form>
And I doubt it's any relevance but here's my Site controller:
public class SiteController : Controller
{
/// <summary>
/// The create page
/// </summary>
/// <returns></returns>
public ActionResult CreateIndex()
{
return View();
}
[HttpPost]
public ActionResult Create(string title, string description, bool privateSite = false)
{
Ops.SiteOps.createSite(Authenticated.AuthenticatedAs, title, description, privateSite);
return RedirectToAction("Index", "Home");
}
public ActionResult ViewIndex(int siteId, string message = null)
{
ViewBag.message = message;
ViewBag.siteId = siteId;
return View();
}
}
Use the Html.BeginForm helper method to render your form tag. This will render the correct relative path to your HttpPost action in your form's action attribute.
#using(Html.BeginForm("CreatePage","Page"))
{
<input class="form-field form-control" type="text" name="title" placeholder="Title" />
<input class="form-field form-control" type="text" name="description" " />
<input class="form-field form-control" type="hidden" name="siteId" value="#site.Id" />
Blog page? <input class="form-field" type="checkbox" value="true" name="isBlog" />
<input class="btn btn-info" type="submit" value="Create" />
}

Losing data (specifically, the apostrophes) from HTML form to Java Servlet

Reference: HTML forms, php and apostrophes
I've been trying to pass data from my HTML form to my servlet for processing. However, I noticed that I'd lose the apostrophes in the text inputs. I'm not sure if this is a client or server side processing error, but looking through the reference above, i think i need to do some processing on the servlet side? Tried looking for a servlet alternative to the above but couldn't find any.
Here's the code snippets:
Html form:
<form method="post" action="CreateThreadServlet">
<b>Title</b><br>
<input type="text" name="title" size="60%" placeholder="Enter your title here"/><br>
<br><b>Tags</b><br>
<input type="text" name="tags" placeholder="Additional Tags: comma separated, e.g. Gamification, Java" size="60%" /><br>
<br><b>Details</b><br>
<textarea name="content" style="width:100%;height:50%"></textarea>
<input type="hidden" name="nick" value=<%=nick%>>
<input type="hidden" name="userid" value=<%=userid%>>
<button type="button" style='float: right;' onClick="closeDimmer()">Cancel</button>
<input type="submit" name="Submit" value="Submit" text-align='center' style='float: right;'>
</form>
This is the servlet code that processes the form:
String userid = req.getParameter("userid");
String nick = req.getParameter("nick");
String title = null; //tried using the URLDecoder, doesn't work
try {
title = URLDecoder.decode(req.getParameter("title"), "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CreateThreadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
String tags = req.getParameter("tags");
String[] tagStr = tags.split(",");
String[] addTags = req.getParameterValues("addTags");
PLEASE HELP THE NEWBIE.
As this link explains you could simply config a filter
<filter>
<filter-name>HitCounterFilter </filter-name>
<filter-class>
net.my.filters.HitCounterFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
having this:
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
chain.doFilter(request, wrapper);
}
}
so you force an UTF-8 encoding.