I am trying to make an Ajax call from my JSP to Servlet and then get the data from the servlet and embed it to the html view. For now the data is not even being added to my tags after the ajax call. What could I be doing wrong ? Is there a better way to do it? Any suggestions or advise is really appreciated.
HomeServlet.java
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import com.google.gson.Gson;
/**
* Servlet implementation class Home
*/
#WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HomeServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String, String> options = new LinkedHashMap<>();
String text = "some text";
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from apiinfo");
// out.println("<table border=1 width=50% height=50%>");
// out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("apiname");
String nm = rs.getString("apiendpoint");
options.put("value1", n);
options.put("value2", nm);
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
// out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");
}
// out.println("</table>");
// out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
String c = request.getParameter("source");
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
System.out.println("Connection created");
PreparedStatement ps= ((java.sql.Connection) con).prepareStatement("insert into apiinfo(apiname,apiendpoint,apiversion,accessibility) values (?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3, e);
ps.setString(4,c);
ps.execute();
out.close();
System.out.println("Inserted");
}
catch(Exception e1)
{
System.out.println(e1);
}
}
}
Home.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>
<div id="ajaxresponse">
</div>
<form>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<!--
<br><br>
<input type="submit" formaction="Home" method="post" value="Submit"> -->
<br>
<input type="submit" id="check" name="check" value="Check">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
console.log("I was clicked");
$.get("HomeServlet", function(responseText) {
// Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
var $select = $("#ajaxresponse"); // Locate HTML DOM element with ID "someselect".
$select.find("option").remove(); // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
$.each(responseJson, function(key, value) {
// Iterate over the JSON object.
$("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
}); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</body>
</html>
When I click on the check button. This is what shows up in the url.
http://localhost:8080/TestApplication/Home.jsp?apiname=&apiendpoint=&apiversion=&check=Check
Related
I'm very new to FullCalendar and I seriously don't know how to adapt it according to my project requirements. Chose it because my Lecturer wants me to. I am aware that fullcalendar is drag and drop function. What i'm trying to do is have an add button for each cell in my fullcalendar page then when I click add it will go to another jsp page (Add Events). Then I have date inputs (java.sql.Date) so this dates must match to full calendar date.I'm So sure that it's some logic here in index.jsp that needs to be done like if and else statement. If mysql date match to fullcalendar date,you display in that cell. Now what it's doing is print out date in every cell from database.And I just need to display the Title. Refer to the pictures attached :)
RetrieveServlet: Retrieve from AddEventsServlet (for adding events)
ackage servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import database.DBAO;
import model.AddEvents;
/**
* Servlet implementation class RetrieveServlet
*/
#WebServlet("/RetrieveServlet")
public class RetrieveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RetrieveServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
doPost(request,response); //dispatcher sents deget request, since ur code is in dopost, u will need to all it.
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
DBAO myDatabase = new DBAO();
ArrayList <AddEvents> myEventList = myDatabase.getAddEvents();
System.out.println(myEventList.size());
request.setAttribute("EventList",myEventList);
request.getRequestDispatcher("index.jsp").forward(request, response);
}catch(Exception ex)
{
System.out.println("Error Accessing Database:" +ex.getMessage());
}
}
}
AddEventsServlet:
package servlet;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.ListIterator;
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;
import javax.servlet.http.HttpSession;
import database.DBAO;
import model.AddEvents;
/**
* Servlet implementation class AddEventsServlet
*/
#WebServlet("/AddEventsServlet")
public class AddEventsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddEventsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
AddEvents myEvent = new AddEvents();
//create an object based on the Java class customers
//DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
//Assignment of data
myEvent.setTitle(request.getParameter("Title"));
myEvent.setEventDesc(request.getParameter("EventDesc"));
myEvent.setStartTime(request.getParameter("StartTime"));
myEvent.setEndTime(request.getParameter("EndTime"));
myEvent.setBudget(Double.valueOf(request.getParameter("Budget")));
myEvent.setStartDate(java.sql.Date.valueOf(request.getParameter("StartDate")));
myEvent.setEndDate(java.sql.Date.valueOf(request.getParameter("EndDate")));
myEvent.setEnvironment(request.getParameter("Environment"));
System.out.println(request.getParameter("Title"));
System.out.println(request.getParameter("EventDesc"));
System.out.println(request.getParameter("StartTime"));
System.out.println(request.getParameter("EndTime"));
System.out.println(request.getParameter("Budget"));
System.out.println(request.getParameter("StartDate"));
System.out.println(request.getParameter("EndDate"));
System.out.println(request.getParameter("Environment"));
System.out.println("Title="+myEvent.getTitle());
System.out.println("EventDesc="+myEvent.getEventDesc());
System.out.println("StartTime="+myEvent.getStartTime());
System.out.println("EndTime="+myEvent.getEndTime());
System.out.println("Budget="+myEvent.getBudget());
System.out.println("StartDate="+myEvent.getStartDate());
System.out.println("EndDate="+myEvent.getEndDate());
System.out.println("Environment="+myEvent.getEnvironment());
try
{
DBAO myDatabase = new DBAO();
ArrayList <AddEvents> myEventList = myDatabase.getAddEvents(); //not needed
//AddEvents myEventDetails =myDatabase.isEvent(myEvent,title, eventDesc, StartTime, EndTime, Budget); //not needed
HttpSession myRequest = request.getSession(true); //not needed
request.setAttribute("EventList",myEventList); //not needed
System.out.println(myEventList.size()); //not needed
// you comment out the method that insert data to database
myDatabase.AddEvents(myEvent);
// the dispatcher can go to RetrieveServlet and let it handle the retrieve
//myDatabase.delete(myEvent,title,eventDesc,StartTime,EndTime,Budget,StartDate,EndDate);
//name of delete database
request.getRequestDispatcher("index.jsp").forward(request, response);
}catch(Exception ex)
{
System.out.println("Error Accessing Database:" +ex);
}
}
}
index.jsp: Displaying the full calendar
<%# 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>
<%#page import="model.AddEvents,java.util.ArrayList,java.util.ListIterator" %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src= "https://code.jquery.com/jquery-3.2.1.min.js">
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var events_array = [
{
title: 'Test1',
start: new Date(2012, 8, 20),
tip: 'Personal tip 1'},
{
title: 'Test2',
start: new Date(2012, 8, 21),
tip: 'Personal tip 2'}
];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
dayClick: function(date, jsEvent, view) {
alert('Clicked on: ' + date.format());
alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
alert('Current view: ' + view.name);
// change the day's background color just for fun
$(this).css('background-color', 'red');
},
selectable: true,
events: events_array,
eventRender: function(event, element) {
element.attr('title', event.tip);
}},
$('#datepicker').datepicker({
inline: true,
onSelect: function(dateText, inst) {
var d = new Date(dateText);
$('#fullcalendar').fullCalendar('gotoDate', d);
}
}));
function changeDate() {
var StartDate = $('#datepicker').val();
$('#calendar').fullCalendar('gotoDate', startDate);
}
});
</script>
<title>Calendar</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<a class= "add_event_label" href="https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea"></a>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1>Calendar</h1>
<div id="bootstrapModalFullCalendar"></div>
</div>
</div>
</div>
<!-- this is the pop up window when you press the button -->
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span> <span class="sr-only">close</span></button>
<h4 id="modalTitle" class="modal-title"></h4>
</div>
<div id="modalBody" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a class="btn btn-primary" id="eventUrl" target="_blank">Event Page</a>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#bootstrapModalFullCalendar').fullCalendar({
header: {
left: '',
center: 'prev title next',
right: ''
},
//action after calendar loaded
eventAfterAllRender: function(view){
if(view.name == 'month')
{
//loop all .fc-day elements
$('.fc-day').each(function(){
//jQuery styling
$(this).css({ 'font-weight': 'bold', 'font-size': '100%'});
$(this).css('position','relative');
//add elements to each .fc-day, you can modify the content in append() with your own html button code
$(this).append('<a class="add_event_label" onclick="changeDate()" href ="AddEvent.jsp" style="position:absolute;bottom:0;left:0;right:0;display:block;font-size:12px;color:blue;cursor:pointer;">(+)</a>' );
<%!ArrayList<AddEvents> myEventList; //have to declear in a declaration tag for access in the page %>
<% myEventList = (ArrayList<AddEvents>) request.getAttribute("EventList");
if(myEventList.size() == 0)
{
%>
<h2>No events</h2>
<%
}
else
{
%>
<%
ListIterator<AddEvents> li = myEventList.listIterator();
while(li.hasNext())
{
AddEvents myEvent = new AddEvents();
myEvent= (AddEvents)li.next();
%>
//This part it should add data according to date, now it's just adding all the data of title.
$(this).append('<p><font size="1">Title:</font></p><p><font size="1"><%= myEvent.getTitle() %></font></p></p>');
<%}
%>
<%
}
%>
});
}
},
eventClick: function(event, jsEvent, view) {
//$(".fc-day-number").prepend("(+) ");
$('#modalTitle').html(event.title);
$('#modalBody').html(event.description);
$('#eventUrl').attr('href',event.url);
$('#fullCalModal').modal();
return false;
}
})
})
</script>
</body>
</html>
I need help in forwarding the result set values from servlet to jsp without using JSTL implementation
Work flow :
The user enters a value in text box and clicks search button
On clicking search the servlet is called.
The servlet focuses on the database implementation and forward the result set values to the same jsp page from where the request comes.
Issue:
My result set size is 3, but the value which is in the top of my table alone is getting printed in my jsp page. The remaining 2 values are missing.I want all the values to be printed in my jsp page.
This is my code:
Productlist.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Products</title>
</head>
<body>
<form method="post" align="center" action="ProductList">
Company Name:<input type="text" size="20" id="company" name="company" />
<input type="submit" value="search"/>
<%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<br/>" + prod.getProductname());
}
}
%>
</form>
</body>
</html>
Products.java
public class Products {
private String productname;
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname=productname ;
}
}
ProductList.java(servlet-code)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class ProductList extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs = null;
Connection connection = null;
List<Products> pdt = new ArrayList<Products>();
try{
String company =request.getParameter("company");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="select product_pck from comp_pdt_list where company_name='"+company+"'";
PreparedStatement prep = connection.prepareStatement(sql);
rs=prep.executeQuery();
while(rs.next()) {
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
return;
}
prep.close();
} catch(Exception E) {
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
} finally {
try {
connection.close();
} catch (Exception ex) {
System.out.println("The error is" + ex.getMessage());
}
}
}
}
You set the attribute to request in your while loop. So the "list" contains only one product. (method returns on first iteration)
Add products to the list in while loop and set your list (request attribute) only after while loop.
Following should fix it:
while(rs.next()){
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
}
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
So I want to learn AJAX and I wanted to make identical app like the one in here
and I pretty much copied it but it doesn't work. I don't know why, I was trying to solve it on my own but can't find any solution.
My .js file is :
function ajaxAsyncRequest(reqURL) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", reqURL, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// How to get message
alert('It\'s K');
document.getElementById("message").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
} else {
alert('Something is wrong !');
}
}
};
xmlhttp.send(null);
}
The index .jsp is:
<%# 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="javascript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="Show Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>
</html>
and my servlet code is:
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
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("/getTime")
public class GetTimeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetTimeServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
PrintWriter out = response.getWriter();
LocalDate currentTime= LocalDate.now();
String message = "Currently time is "+currentTime.toString();
out.write(message);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
But when I click on the button I get the message which I pointed in the title in the line document.getElementById("message").innerHTML = xmlhttp.responseText;
in .js file.
I'm running it through http://localhost:8080/HelloAjax/, so no local, It loads later than the page, so I have no idea what can it be.
document.getElementById("message") is null because there is no element with id 'message' in the DOM. Try changing your HTML:
<body>
<div id="message"></div>
<input type="button" value="Show Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>
I have created a Login page with three fields Usertype, Username and Password. Usertype has select box (or select tag), Username has textfield and Password also has textfield. To login every field has to be correct. The problem is I am successfully able to validate username and password but unable to do with usertype, username and password. I have login.java and index.jsp.
Login.java
package roseindia.net;
import java.io.*;
//import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
/*** Servlet implementation class Login
***/
#WebServlet(description = "Login Servlet", urlPatterns = { "/login" })
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("We are service method of servlet");
/*
String username="user";
String password="root";
*/
String un=request.getParameter("username");
String pw=request.getParameter("password");
String ut=request.getParameter("usertype");
String msg=" ";
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="userlogindb";
String driver="com.mysql.jdbc.Driver";
String dbUserName="root";
String dbPassword="root";
try{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,dbUserName,dbPassword);
String strQuery="select * from registerutable where username='" + un + "' and password1='" + pw + "' and usertype='" + ut + "'";
Statement st= conn.createStatement();
ResultSet rs= st.executeQuery(strQuery);
if(rs.next())
{
msg="Hello " + un + "! Your login is successful";
request.setAttribute("msg", msg);
RequestDispatcher req=request.getRequestDispatcher("/successful.jsp");
req.forward(request, response);
} else
{
msg="Hello " + un + "! Your login failed";
request.setAttribute("msg", msg);
RequestDispatcher req=request.getRequestDispatcher("/failed.jsp");
req.forward(request, response);
}
rs.close();
st.close();
}
catch(Exception e)
{
e.printStackTrace();
}
/*
if(un.equals(username) && pw.equals(password))
{
msg="Hello " + un + "! Your login is successful";
}
else
{
msg="Hello " + un + "! Your login failed";
}
*/
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<font size='6' color=red>" + msg + "</font>");
}
}
index.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>Login Example</title>
</head>
<body>
<form name="loginform" action="login" method="post">
<div style="width:300px;margin:0 auto;">
<p>User Type: <select>
<option value="employee">Employee</option>
<option value="proj-coordinator">Project Co-ordinator</option>
<option value="proj-manager">Project Manager</option>
<option value="admin">Admin</option>
</select>
</p>
<p>User Name: <input type="text" name="username"></p><br>
<p>Password: <input type="password" name="password"></p><br>
<center><input type="submit" value="Login"></center>
</div>
</form>
</body>
</html>
When I m running this program and validating it with correct values then also it is showing Login unsuccessful/failed page.
Please resolve this issue
Change your Select Type in jsp as follows
User Type: <select name="usertype">
<option value="employee">Employee</option>
<option value="proj-coordinator">Project Co-ordinator</option>
<option value="proj-manager">Project Manager</option>
<option value="admin">Admin</option>
</select>
#Atiq : the code which you have putted above, it seems that you have not set the name property of <select> tag to usertype in the jsp.
Try to add this and then check, it should work.
hi i am uploading images in to data base using servlets. when i submit my form i am getting a exception "NULL" here is my code any help are accepted.And can any one suggest me which way to be used to upload files in to database such that there wont be much of load on database and lessen httprequest. thank you in advance.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="requirementlogic.*,java.util.*"%>
<!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>
<body>
<form method="post" action="../InsertImage">
<table>
<tr><TD ><B>Upload Image</B></TD>
<td><input type="file" name="Image" size="20" value=""></TD>
</tr>
<tr>
<td><input type="submit" height="30" width="62"> </td>
</tr>
<tr>
</table>
</form>
</body>
</html>
here is my JDBC:
package requirementlogic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DataBase {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbname= "deshopa";
String driver ="com.mysql.jdbc.Driver";
String Username="root";
String Password ="";
public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+dbname,Username,Password);
return con;
}
}
here is my servlet:
package requirementlogic;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class InsertImage
*/
#WebServlet("/InsertImage")
public class InsertImage extends HttpServlet {
private static final long serialVersionUID = 1L;
DataBase db;
/**
* #see HttpServlet#HttpServlet()
*/
public InsertImage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
db = new DataBase();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
try
{
String strpath=request.getParameter("image");
String filepath=strpath.substring(strpath.lastIndexOf(".")+1);
pw.println(filepath);
File imgfile = new File(strpath);
FileInputStream fin = new FileInputStream(imgfile);
String sql = "insert into upload_image(image,image_name,image_length)";
PreparedStatement pre = db.getConnection().prepareStatement(sql);
pre.setBinaryStream(1,fin,(int)imgfile.length());
pre.setString(2,filepath);
pre.setLong(3,imgfile.length());
pre.executeUpdate();
pre.close();
pw.println("done");
}
catch(Exception e){
pw.println("direct exception");
pw.println("Exception is "+ e.getMessage());
}
}
}
Sql query used to create table:
CREATE TABLE `upload_image` (
`Image_id` int(11) NOT NULL AUTO_INCREMENT ,
`IMAGE` longblob NULL DEFAULT NULL ,
`Image_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`image_length` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
PRIMARY KEY (`Image_id`)
)
change to this
String strpath=request.getParameter("Image");
as in your html form the name of the file field is Image not image
<td><input type="file" name="Image" size="20" value=""></TD>
also you are dealing with multipart request so you have to chenge your code
if(ServletFileUpload.isMultipartContent(request)){
private final String UPLOAD_DIRECTORY = "C:/uploads";
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}
See the below link for further details
http://javarevisited.blogspot.in/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html
You are trying this:
String strpath=request.getParameter("image");
Try this:
String strpath=request.getParameter("Image");
Error is name which you are trying. Name in capital letter.
<input type="file" name="Image" size="20" value="">
In case
File file = new File("yourPath");
file.mkdirs();
You can try this Link1 and Link2