This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 8 years ago.
I am uploading more images using single upload button such as below code,
Updated based on Answer :
package TeachChapter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.sql.*;
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.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
/**
* Servlet implementation class ImageUploadToDB
*/
#WebServlet("/ImageUploadToDB")
public class ImageUploadToDB extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ImageUploadToDB() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Entered successfully:");
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
// get the request content and iterate through
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (items != null) {
System.out.println("if0 successfully:");
final Iterator iter = items.iterator();
while (iter.hasNext()) {
System.out.println("while successfully:");
final FileItem item = (FileItem) iter.next();
// this is for non-file fields
if (item.isFormField()) {
System.out.println("if1 successfully:");
// logic for setting non-file fields
} else {
// item.getName() - gives file name
fileMap.put(item.getName(), item.getInputStream());
System.out.println("else successfully:");
}
}
}
}
try {
System.out.println("try connection successfully:");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
System.out.println("for successfully:");
String sql ="INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setString(1, "mani");
statement.setString(2, "vasu");
statement.setBlob(3, fileMap.get(fileName));
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
}
}
OP :
Entered successfully:
try connection successfully:
I know above code totally wrong but i want to get that all uploaded images in servlet page for insert into mysql.
Please Help me out.
Had faced a similar issue - probably you could build upon it further.
This is a generic solution - where you don't know the number of attachments in the input request. It caters to a multi-part request as below.
// imports
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
// code flow
// HttpServletRequest request
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
private Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
// get the request content and iterate through
items = fileUpload.parseRequest(request);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
// this is for non-file fields
if (item.isFormField()) {
// logic for setting non-file fields
} else {
// item.getName() - gives file name
fileMap.put(item.getName(), item.getInputStream());
}
}
}
}
//Here i will insert that images on by one to DB
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
String sql = "INSERT INTO contacts (photo) values (?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setBlob(1, fileMap.get(fileName));
int row = statement.executeUpdate();
}
fileMap will contain all the files you have sent in the request.
If you don't bother for file names, you can change the implementation from HashMap to ArrayList and modify the for loop accordingly.
Related
I wanted to create a servlet that shows Studentlist which is from SQL Server. However, when I click show button the server returns:
HTTP Status 500 - Cannot invoke "model.StudentList.getList()" because "list" is null
controller.StudentServlet.java
package controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Student;
import model.StudentList;
/**
* Servlet implementation class StudentServlet
*/
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public StudentServlet() {
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
StudentList list = null;
try {
list = new StudentList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Student> myStudents = list.getList();
request.setAttribute("MYSTUDENTS", myStudents);
RequestDispatcher dispatcher = request.getRequestDispatcher("list.jsp");
dispatcher.forward(request, response);
}
/**
* #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);
}
}
model.StudentList.java
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class StudentList {
private static ArrayList<Student> list = new ArrayList<>();
public StudentList() throws SQLException {
Connection conn = null;
PreparedStatement p = null;
ResultSet rs = null;
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=Workshop1";
String user = "quan167";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
int id = 0;
String name = "";
String gender = "";
String date = "";
String sql = "select * from Student";
try {
p = conn.prepareStatement(sql);
rs = p.executeQuery();
// Condition check
while (rs.next()) {
id = rs.getInt("id");
name = rs.getString("name");
gender = rs.getString("gender");
date = rs.getString("dob");
list.add(new Student(id, name, gender, date));
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
public ArrayList<Student> getList() {
return list;
}
}
and model.Student.java which has: id(int), name(String), gender(String), dob(String) stands for date of birth.
But this works out just fine in this test class
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class tst {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement p = null;
ResultSet rs = null;
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=Workshop1";
String user = "quan167";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
StudentList list = null;
try {
list = new StudentList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Student> myStudents = list.getList();
System.out.println(myStudents);
}
}
Anyone knows the solution? Thank you.
Edit: I knew where the problem is. So basically I have not put the sqlijdbc4.jar in WEB-INF.lib
Change the following lines:
public class StudentList {
private static ArrayList<Student> list = new ArrayList<>();
to these lines:
public class StudentList {
public ArrayList<Student> list = new ArrayList<>();
now i'm making login activity using REST API.
we get column values from table in sqldeveloper.
but when I click the button(login_btn), it doesn't work.
here is the code below.
This is LoginRequest.
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class LoginRequest extends StringRequest {
final static private String URL = "http://localhost:8080/Termproject/employees";
private Map<String, String> map;
public LoginRequest(String empEml, String pass, Response.Listener<String> listener) {
super(Method.POST, URL, listener, null);
map = new HashMap<>();
map.put("EMAIL", empEml);
map.put("PASSWORD", pass);
}
#Override
protected Map<String, String>getParams() throws AuthFailureError {
return map;
}
}
And this code below is MainActivity.java.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText inputEmail = findViewById(R.id.email_txt);
EditText inputPass = findViewById(R.id.pw_txt);
Button login_btn = findViewById(R.id.login_btn);
String InputEml = inputEmail.getText().toString();
String InputPwd = inputPass.getText().toString();
login_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject( response );
String empEml = jsonObject.getString( "EMAIL" );
String pass = jsonObject.getString( "PASSWORD" );
if(empEml.equals(inputEmail)&&pass.equals(inputPass)) {
System.out.println(empEml);
System.out.println(pass);
Intent intent = new Intent( getApplicationContext(),menu_select.class );
//intent.putExtra( "EMAIL", empEml );
//intent.putExtra( "PASSWORD", pass );
//intent.putExtra( "UserName", UserName );
startActivity( intent );
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest( InputEml, InputPwd, responseListener );
RequestQueue queue = Volley.newRequestQueue( MainActivity.this );
queue.add( loginRequest );
}
});
}
}
and this code below is servlet code to get data from table(jdbc).
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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 org.json.JSONObject;
/**
* Servlet implementation class RESTEmployees
*/
#WebServlet(description = "database employees table", urlPatterns = { "/employees" })
public class RESTEmployees extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RESTEmployees() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log("doGet");
int empNbr = getId(request);
log(String.format("EMPLOYEE_ID=%d \n", empNbr));
try {
Connection conn = getConnection();
PreparedStatement st;
if (empNbr > 0) {
st = conn.prepareStatement("select * from employees where EMPLOYEE_ID = ?");
st.setInt(1, empNbr);
} else {
st = conn.prepareStatement("select * from employees");
}
ResultSet rs = st.executeQuery();
JSONArray arr = new JSONArray();
while (rs.next()) {
JSONObject o = new JSONObject();
o.put("EMPLOYEE_ID", rs.getInt("EMPLOYEE_ID"));
o.put("FIRST_NAME", rs.getString("FIRST_NAME"));
o.put("LAST_NAME", rs.getString("LAST_NAME"));
o.put("EMAIL", rs.getString("EMAIL"));
o.put("PHONE", rs.getString("PHONE"));
o.put("HIRE_DATE", rs.getDate("HIRE_DATE")); //date type을 string으로 받아야 함
o.put("MANAGER_ID", rs.getInt("MANAGER_ID"));
o.put("JOB_TITLE", rs.getString("JOB_TITLE"));
arr.put(o);
}
rs.close();
st.close();
conn.close();
JSONObject body = new JSONObject();
body.put("DATA", arr);
log(body.toString());
PrintWriter out = response.getWriter();
out.print(body);
out.flush();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log("doPost");
try {
JSONObject obj = new JSONObject(readBody(request.getInputStream()));
String sql = "update EMPLOYEES set FIST_NAME=?, LAST_NAME=?, EMAIL =? PHONE = ? HIRE_DATE = ? JOB_TITLE = ? ROLE = ? where EMPLOYEE_ID=?";
Connection conn = getConnection();
PreparedStatement st = conn.prepareStatement(sql);
String empFNm = obj.getString("FIRST_NAME");
String empLNm = obj.getString("LAST_NAME");
String empEml = obj.getString("EMAIL");
String empPho = obj.getString("PHONE");
String hireDt = obj.getString("HIRE_DATE"); //String 타입으로 받음
String job = obj.getString("JOB_TITLE");
String role = obj.getString("ROLE");
System.out.format("Updating EMPLOYEES(%s, %s, %s, %s, %s, %s, %s)\n", empFNm, empLNm, empEml, empPho, hireDt, job, role);
st.setString(1, empFNm);
st.setString(2, empLNm);
st.setString(3, empEml);
st.setString(4, empPho);
st.setDate(5, Date.valueOf(hireDt)); //타입 date로 변환함
st.setString(6, job);
st.setString(7, role);
st.executeUpdate();
conn.close();
} catch (ClassNotFoundException | SQLException | ParseException e) {
throw new ServletException(e);
}
}
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log("doPut");
try {
JSONObject obj = new JSONObject(readBody(request.getInputStream()));
System.out.println("New Employee: "+obj);
String sql = "insert into EMPLOYEES(FIRST_NAME,LAST_NAME,EMAIL, PHONE, HIRE_DATE, JOB_TITLE, ROLE) values (?, ?, ?, ?,?,?,?)";
Connection conn = getConnection();
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, obj.getString("FIRST_NAME"));
st.setString(2, obj.getString("LAST_NAME"));
st.setString(3, obj.getString("EMAIL"));
st.setString(4, obj.getString("PHONE"));
st.setString(5, obj.getString("HIRE_DATE"));
st.setDate(5, Date.valueOf("HIRE_DATE"));
st.setString(6, obj.getString("JOB_TITLE"));
st.setString(7, obj.getString("ROLE"));
st.executeUpdate();
conn.close();
} catch (ClassNotFoundException | SQLException | ParseException e) {
throw new ServletException(e);
}
}
/**
* REST API for deleting specified EMPLOYEE data
* employee number를 auto increment로 할 지 어떻게 할 지
*/
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log("doDelete");
int empNbr = getId(request);
log("DELETE: EMPLOYEE_ID = " + empNbr);
// Delete tuple from EMPLOYEE table
try {
String sql = "delete from EMPLOYOEE where EMPLOYEE_ID=?";
Connection conn = getConnection();
PreparedStatement st = conn.prepareStatement(sql);
st.setInt(1,empNbr);
st.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
/**
* Extract ID from the request URL
*
* #param request Servlet request parameter
* #return integer representation of ID in URL
*/
private int getId(HttpServletRequest request) {
String uri = request.getRequestURI();
log("Request URI:" + uri);
Pattern reId = Pattern.compile("/employees/([0-9]+)");
Matcher matcher = reId.matcher(uri);
return matcher.find() ? Integer.parseInt(matcher.group(1)) : -1;
}
/**
* Read the content of the HTTP request and convert it into a string
*
* #param is HTTP Body에 대한 InputStream
* #return String representation of the HTTP request content
* #throws IOException thrown when any error occurs while I/O operations
*/
private String readBody(InputStream is) throws IOException {
char[] buffer = new char[1024];
StringBuilder content = new StringBuilder();
Reader in = new InputStreamReader(is, StandardCharsets.UTF_8);
for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0;) {
content.append(buffer, 0, numRead);
}
System.out.println("HTTP Body: " + content.toString());
return content.toString();
}
private Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:url", "username", "userpass");
}
}
I want the code work - compare the value of EMPLOYEES table and input string, and then if the value of email and inputemail equals and the value of password and inputpassword equals, make login succeed and go to next activity(menu_select).
But when I click the login_btn, it does nothing.
What is wrong with this code?
I am working with servlets as a newbie i have been trying to get desktop application and trying to see how they could come out when i use servlets,with the system.getproperty method if i hit my submit button i'm getting a blank message.
this is my jsp code.
<form action="checkservlet" method="get">
<input type="submit" value="submit"/><br/>
</form>
this is my servlet code
package com.check.pack;
import java.io.IOException;
import java.io.PrintWriter;
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 checkservlet
*/
#WebServlet("/checkservlet")
public class checkservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public checkservlet() {
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
response.setContentType("text/html");
PrintWriter write = response.getWriter();
Mulizwa Mcheck = new Mulizwa();
}
}
this is my class code
package com.check.pack;
import java.util.*;
public class Mulizwa {
public static void main(String[] args) {
Properties prop = System.getProperties();
Set<Object> keySet = prop.keySet();
for(Object obj : keySet){
System.out.println("System Property: {"+obj.toString()+","+System.getProperty(obj.toString())+"}");
}
}
}
i'm no expert but i'm here to learn,what i'm expecting from the code above if i hit the submit button i need to see the response in the browser about the system properties like os name java version etc.
First you need to write a function in your Mulizwa class that might return a String of your system properties instead of its main method that prints the properties on Standard out, some thing like this
public String getPropertyString (){
Properties prop = System.getProperties();
StringBuilder propertyString = new StringBuilder();
Set<Object> keySet = prop.keySet();
for(Object obj : keySet){
propertyString.append("System Property: {"+obj.toString()+","+System.getProperty(obj.toString())+"}");
}
return propertyString.toString();
}
Then in your servlet's doPost method,
PrintWriter write = response.getWriter();
Mulizwa mCheck = new Mulizwa();
write.write(mCheck.getPropertyString());
change
package com.check.pack;
import java.util.*;
public class Mulizwa {
public String getDetails(){
ResourceBundle rb = ResourceBundle.getBundle("System", Locale.getDefault());
StringBuilder str = new StringBuilder(" ");
Enumeration<String> en = rb.getKeys();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = rb.getString(key);
str.append(key+":"+value +"\n");
}
return sb.toString();
}
}
and in servelet class change doPost like the following
PrintWriter out = response.getWriter();
out.println(new Mulizwa().getDetails());
Instead of writing this code in main,keep it in a method in Mcheck class like this
public void writeSystemPropertiesInResponse(HttpServletResponse response)) {
Properties prop = System.getProperties();
Set<Object> keySet = prop.keySet();
PrintWriter writer = response.getWriter();
for(Object obj : keySet){
writer.write("System Property: {"+obj.toString()+","+System.getProperty(obj.toString())+"}");
}
}
And call this method in your servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
//PrintWriter write = response.getWriter();no need of this
Mulizwa Mcheck = new Mulizwa();
Mcheck.writeSystemPropertiesInResponse(resonse);
}
UPDATE
If you don't wanna pass response as argument,you can use StringBuilder to build a string and write using PrintWriter as suggested in other answers.
Recently i have started working on Java Servlet Async functionality. I have written sample code shown below to check aysnc Functionality. I am running it on single core processor. I am submitting 100 requests (image requests) from jsp. I have added "Request Submmited:::" SOP in code. It is displaying SOP for first 0 to 6 requests then after some time it is displaying SOP for 6 to 11.... why it is not displaying SOP for all 100 requests.
package com.test;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.AsyncContext;
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(urlPatterns={"/Test"}, asyncSupported = true)
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
int counter = 0;
#Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
System.out.println("Request Submmited:::" + counter++);
final AsyncContext ctx = request.startAsync();
ctx.start(new Runnable() {
public void run() {
try {
String count = request.getParameter("test");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fin = new FileInputStream(
"D:/TESTImages/8_0_0_NUCLEI" + count + ".jpg");
byte[] data = new byte[fin.available()];
fin.read(data);
response.getWriter().print(new String(data));
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
ctx.complete();
}
});
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Seems that the default thread pool size is 5, for the pool that procesess async requests in your servlet container. Try providing init params as below:
#javax.servlet.annotation.WebServlet(urlPatterns={"/Test"}, asyncSupported = true,
initParams = { #WebInitParam(name = "threadpoolsize", value = "100") })
hi all I've typed out a page that queries the database then inputs something into the database but when I go to load the servlet/jsp page its comes back blank and am unsure what is happening or why? I'm coding in eclipse and after looking at the console and not getting anything printing out I figured there was something wrong with my code but I cannot see the problem.
Here is my servlet
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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;
/**
* Servlet implementation class TutorAssign
*/
#WebServlet("/TutorAssign")
public class TutorAssign extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TutorAssign() {
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
}
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
String sql = "SELECT l.id,s.name,l.day,l.time,l.room" +
" FROM subject s, lab l " +
" WHERE s.user_id="+(Integer)session.getAttribute("id");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got boobs");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
System.out.println(res);
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1));
list2.add(res.getString(2)+" "+res.getString(3)+" "+res.getString(4)+" "+res.getString(5));
}while(res.next());
System.out.println("Outside");
String[] arr1 = list1.toArray(new String[list1.size()]);
String[] arr2 = list2.toArray(new String[list2.size()]);
System.out.println(list1);
request.setAttribute("res1", arr1);
request.setAttribute("res2", arr2);
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("TutorAssign.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt(request.getParameter("id"));
int lab_id = 0;
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
System.out.println(user_id);
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successfully assigned a tutor.";
response.sendRedirect("Lecturer_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
// TODO Auto-generated method stub
}
I noticed that your doGet method has not been implemented.
I would assume that your sendBack code is not being called
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendBack(request,response);
}
You have several empty catch blocks. This means that if the program encounters some problem the error will be silently swallowed and you don't know what code got executed and what code was skipped, so the outcome is unknown. At least log the error in the catch block, like this (very basic example, using java.util.logging
} catch (SQLException e) {
logger.log(Level.INFO,"SQL Error encountered",e);
} catch (Exception e) {
logger.log(Level.INFO,"Other error encountered",e);
}
Start by getting your error handling right, and study the errors the program encounters.
Aside from that problem, as the others point out your doGet isn't implemented - so if you call the page with GET it won't do anything because doGet is empty. It should do something on POST though.