So I have been reading on this topic for a couple of days now, and every time I think I understand it I get confused again.
So what I have: A MySQL data base, eclipse, tomcat apache, the beginnings of a GUI using STRUTS2
I am setting up a gui for said database and I want to display one of the data tables in my JSP page. So my problem... well I have a lot of problems but initially, I have a form that is I have an action sending me to the JSP page I want to display my table in. I thought I would use another action to connect to the database and obtain all my information, but I'm not sure if that makes sense anymore, should I just use the same action?
Well... here are bits of my code:
Action to get the data:
package net.upsmon.struts2.action;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.opensymphony.xwork2.ActionSupport;
public class Table extends ActionSupport {
List tableRows=new ArrayList();
public String execute() throws InstantiationException, IllegalAccessException, ClassNotFoundException{
List tableInfo=new ArrayList();
Properties props = new Properties();
props.setProperty("user", "user");
props.setProperty("password", "pass");
props.setProperty("databaseName", "db");
String dbUrl="jdbc:mysql://db:3306/db";
String ret = ERROR;
Connection myCon = null;
try{
Class.forName ("com.mysql.jdbc.Driver").newInstance();
myCon = DriverManager.getConnection("jdbc:mysql://dburl:3306/mqmonitordb",props);
String dbQuery = "SELECT * FROM table";
PreparedStatement ps = myCon.prepareStatement(dbQuery);
ResultSet result=ps.executeQuery(dbQuery);
while(result.next()){
tableInfo.add(result.getString("raisedAlertId"));
tableInfo.add(result.getString("alertHostIP"));
tableInfo.add(result.getString("portNumber"));
tableInfo.add(result.getString("qMgrName"));
tableInfo.add(result.getString("alertType"));
tableInfo.add(result.getString("alertGroupName"));
tableInfo.add(result.getString("alertEntity"));
tableInfo.add(result.getString("maintMode"));
tableInfo.add(result.getString("alertCreatedTime"));
tableInfo.add(result.getString("alertRaisedTime"));
tableInfo.add(result.getString("alertAckFlag"));
tableRows.add(tableInfo);
tableInfo.clear();
}
//request.setAttribute("tableRows",tableRows);
}catch(SQLException sqe){
}catch(Exception e){
}
return "yay";
}
public List tableRows() {
return tableRows();
}
public void setTableRows(List tableRows) {
this.tableRows = tableRows;
}
}
JSP page:
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<title>Welcome</title>
</head>
<body>
<h2>
Welcome
</h2>
<table>
<thead>
<tr>
<th></th>
<th>column1</th>
<th>column2</th>
</tr>
</thead>
<tbody>
<s:iterator status="stat" value="tableRows">
<tr>
<td><s:property value="#stat.index+1"></s:property></td>
<td><s:property value="%{column1}"></s:property></td>
<td><s:property value="%{column2}"></s:property></td>
</tr>
</s:iterator>
</tbody>
</table>
<s:form action="logout" method="post" margin="auto">
<s:submit method="authenticate" key="label.logout" align="center" />
</s:form>
<s:form action="tolevelselector" method="post" margin="auto">
<s:submit method="authenticate" key="label.levelthree" align="center" />
</s:form>
</body>
</html>
Any advice would be great, thanks....
Related
This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 3 years ago.
I am trying to populate an html data with data from my arraylist, but i am having some difficulties. I already loaded the data and stored it inside my arraylist but when launching my program the table is empty. Could someone help me with this? I already tried googling my problem, but i cant seem to find an answer.
This is where i'm loading my data and populating it inside my arraylist
import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
#WebServlet("/registered-class")
public class myRegist extends HttpServlet{
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
getInfo registerStu = new findInfo();
String ssn = request.getParameter("ssn");
String fullName = registerStu.getFullName(ssn);
String phone = registerStu.getPhone(ssn);
List<StudentClass> classList = registerStu.loadClass(ssn);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
StudentClass stu = new StudentClass();
request.setAttribute("message", classList);
request.getRequestDispatcher("/table.jsp").forward(request,response);
//ptints out info about course
//out.println(classList.get(0));
/*StudentInfo info = new StudentInfo(ssn, fullName, phone);
HttpSession session = request.getSession();
session.setAttribute("student", info);
String address = null;
if (fullName == null) {
address = "/myRegist.jsp";
}
else if (fullName != null) {
address = "/myRegist.jsp";
}
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward(request, response);*/
}
}
My html table
<html>
<body>
<head>
<title>
View Books
</title>
</head>
<body>
<table border=2>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Author</th>
<th>No. of copies AVAILABLE</th>
<th>Number of favourites</th>
</tr>
<tr>
<td><%=b.bookID%></td>
<td><%=b.bookTitle%></td>
<td><%=b.bookAuthor%></td>
<td><%=b.bookCopies%></td>
<td><%=b.bookFavs%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
Although #olivakyle's answer is correct, I prefer the use of jstl tags instead of scriplets: it keeps the JSP less messy:
<!DOCTYPE html>
<%#page contentType="text/html"%>
<%#page pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<head>
<title>
View Books
</title>
</head>
<body>
<table border=2>
<tr>
<th>Student ID</th>
<th>Name</th>
</tr>
<c:forEach var="stu" items="${message}">
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
It's quite simple actually – given that you're familiar in passing objects to your JSP. Here is an example using the object you passed and named message and I'm just assuming it has a String property named name.
<%for (StudentClass sc: message) {%>
<span><%=sc.name%></span><br>
<%}%>
I am trying to call a java method('method1') that runs some r code(using RCaller) when a specific button is clicked on a JSP page('button1'), but when i click on the button it doesn't do anything and I am getting no errors in the output. I'm trying to use a servlet to run the java method from a JSP file. I'd appreciate any help.
Analysis.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Analysis Page</title>
</head>
<body>
<center><h2>
Final year Prototype
</h2></center>
<center> <table border="0">
<thead>
<tr>
<th>Disabilities Analysis</th>
</tr>
</thead>
<tbody>
<tr>
<center><td></td></center>
</tr>
<tr>
<td>
<center>
Current HSE Support Centre Locations
</center>
</td>
</tr>
<tr>
<td>
<center>
New HSE Support Centre Locations
</center>
</td>
</tr>
<tr>
<td>
<center>
<form action="${pageContext.request.contextPath}/myservlet" method="POST">
<button type="submit" name="button" value="button1">Button 1</button>
<button type="submit" name="button" value="button2">Button 2</button>
<button type="submit" name="button" value="button3">Button 3</button>
</form>
</center>
</td>
</tr>
<tr>
<td>
<center>
Return
</center>
</td>
</tr>
</tbody>
</table></center>
</body>
</html>
myServlet.java:
package webJava;
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;
#WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TestMethods t = new TestMethods();
String button = request.getParameter("button");
if ("button1".equals(button)) {
t.method1();
} else if ("button2".equals(button)) {
t.method2();
} else if ("button3".equals(button)) {
t.method3();
} else {
}
request.getRequestDispatcher("/Analysis.jsp").forward(request, response);
}
}
TestMethods.java:
package webJava;
import java.io.File;
import javax.swing.ImageIcon;
import rcaller.RCaller;
import rcaller.RCode;
public class TestMethods {
public void method1() {
try {
RCaller caller = new RCaller();
RCode code = new RCode();
caller.setRscriptExecutable("/Library/Frameworks/R.framework/Versions/3.3/Resources/Rscript");
caller.cleanRCode();
caller.setRCode(code);
// load the ggplot2 library into R
code.R_require("ggplot2");
// create a data frame in R using x and y variables
code.addRCode("df <- data.frame(x,y)");
// plot the relationship between x and y
File file = code.startPlot();
code.addRCode("ggplot(df, aes(x, y)) + geom_point() + geom_smooth(method='lm') + ggtitle('y = f(x)')");
caller.runOnly();
ImageIcon ii = code.getPlot(file);
code.showPlot(file);
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void method2() {
//some code
}
public void method3() {
//some code
}
}
My project directory:
Screenshot
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
At beggining. There is a application structure.
I have 3 MySQL tables ( Obiekt, Termin, Rezerwacja). In project i have jsp page (here is code) :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<%# page import="test.Obiekt"%>
<%# page import="test.ListaObiektow"%>
<%# page import="test.Termin"%>
<%# page import="test.ListaTerminow"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>menu główne</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<meta name="android-mobile-web-app-capable" content="yes">
<meta name="android-mobile-web-app-status-bar-style" content="black">
<link href="css/ratchet.css" rel="stylesheet">
<link href="css/ratchet-theme-android.css" rel="stylesheet">
<script src="js/ratchet.js"></script>
<script type="text/javascript">
function Refresh(idObiekt){
location.href="pilkaNozna.jsp?idObiekt=" + idObiekt;
}
</script>
</head>
<body>
</br>
</br>
</br>
<header class="bar bar-nav">
<a class="icon icon-left-nav pull-left" href="wyszukaj.jsp"></a>
<h1 class="title">Wybierz obiekt</h1>
</header>
<div id="content">
<div class="tabelawybor">
<b>Wybierz obiekt:</b>
<%
ArrayList<Obiekt> list = new ListaObiektow().getObiekty();
%>
<form>
<select name="obiekt" onChange="Refresh(this.value)">
<option value="0" selected>Wybierz Obiekt</option>
<%
String selectedObiekt = request.getParameter("idObiekt");
int counter=0;
for (Obiekt obiekt : list) {
if(selectedObiekt == null && counter==0)
{
selectedObiekt = Integer.toString(obiekt.idObiekt);
}
%>
<option value="<%=obiekt.idObiekt%>"
<%= ((Integer.toString(obiekt.idObiekt)).equals(selectedObiekt))?"selected":""%>><%=obiekt.nazwa%>
<%=obiekt.adres%></option>
<%
}
%>
</select>
</form>
</div>
<div class="tabelawybor">
<td><b>Wpisz liczbę uczestników:</b><input type="text"
name="uczest" /></td>
<% String liczbaUczestnikow = request.getParameter("liczbaUczestnikow"); %>
</div>
<div class="tabelawybor">
<form action="Rezerwacja?action=doPost" method="post">
<table class="center">
<tr>
<td>Nazwa obiektu:</td>
<td>Data:</td>
<td>Godzina</br> rozpoczęcia:
</td>
<td>Godzina</br> zakończenia:
</td>
<td></td>
</tr>
<%
ListaTerminow listaterminow = new ListaTerminow();
listaterminow.setId(selectedObiekt);
ArrayList<Termin> lista =listaterminow.getTerminy();
String idTermin = request.getParameter("idTermin");
for (Termin termin : lista) {
%>
<tr>
<td><%=termin.nazwaObiektu%> <%=termin.adresObiektu%></td>
<td><%=termin.dzien%></td>
<td><%=termin.odKtorej%></td>
<td><%=termin.doKtorej%></td>
<td>
<button class="btn btn-primary">Zarezerwuj</button>
</td>
</tr>
<%
}
%>
</table>
</form>
</div>
</div>
</body>
</html>
In this jsp page i have select form which have List of Obiekt (this list is created in ListaObiektow.java), but it works. I also have table form which contains List of Termin (created in ListaTerminow.java). It works too. But, in this table form there is button to make Rezerwacja.
I made Rezerwuj servlet. Here is code:
package test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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 test.ConnectionClass;
import test.Rezerwacja;
import test.Termin;/**
* Servlet implementation class Rezerwuj
*/
#WebServlet("/Rezerwacja")
public class Rezerwuj extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection conn;
private int idTermin;
private int liczbaUczestnikow;
public Rezerwuj() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
if(liczbaUczestnikow > 0 && liczbaUczestnikow < 20)
{
rs = st.executeQuery();
}
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
}
public void setIdTermin(String id)
{
idTermin = Integer.parseInt(id);
}
public void setliczbaUczestnikow(String liczba)
{
liczbaUczestnikow = Integer.parseInt(liczba);
}
}
When i click on the button, it returns error like this:
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
test.Rezerwuj.doPost(Rezerwuj.java:63)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
What i want:
I select one of option in select form, then type value (0-20) into text input, then click on button and create a record in MySQL table Rezerwacja. Any suggestions ?
<form action="Rezerwacja?action=doPost" method="post">
In this line the action is where you are sending the request, so it should be action="Rezerwacja" and method should be method="POST"
I think you have problem with liczbaUczestnikow after initialization is always 0. As result rs always null, therefore exception thrown.
I am new to java.I am creating dynamic web Application in eclipse EE IDE with MYSQL database. I want to connect my database to app so far I have created JSP page for view. Below is my JSP code and Servlet for connection. I am not able to connect to database with this. My JSP page work fine. But I think problem is with Servlet. And also advice to I need to made the two java file one for Servlet and other for getting data from JSP page.
Thanks in advance.
Servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get user_name and pass_word from the JSP page
String toolfirst=request.getParameter("tname1");
String toolsecond=request.getParameter("tname2");
String toolvalue=request.getParameter("tvalue");
//Print the above got values in console
System.out.println("The username is" +toolfirst);
//Setting connection Parameters
String connectionparams=”jdbc:mysql://localhost:3306/tool”;
//database name
String db=”tool”;
//Mysql user name and password whichever you have given during installation
String uname=”root”
String psword=””
//Declaring classes required for Database support
Connection connection=null;
ResultSet rs;
try {
// Loading the available driver for a Database communication
Class.forName("org.gjt.mm.mysql.Driver");
//Creating a connection to the required database
connection = DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
//Add the data into the database
String sql = "insert into usertable values (?,?)";
PreparedStatement prep =
connection.prepareStatement(sql);
//Setting the values which we got from JSP form
prep.setString(1, tname1);
prep.setString(2, tname2);
prep.executeUpdate();
prep.close();
}catch(Exception E){
//Any Exceptions will be caught here
System.out.println(“The error is==”+E.getMessage());
}
finally{
//After the entire execution this block will execute and the connection with database gets closed
connection.close();
}
}
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="NewServlet">
<a id="add" href="javascript:void(0)">Add another Credit card</a>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr class="person">
<td><input type="text" name="tname1" id="name" /></td>
<td><input type="button" value="name" /></td>
<td><select name="tvalue">
<option>value1</option>
<option>value2</option></select>
<td><input type="text" name="tname2" id="name" /></td>
</tr>
</tbody>
</table>
<input type="submit" value="submit" >
</form>
Logout
</body>
</html>
without having a detailed errormessage I would say that you have a compile error here:
connection = DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
it should be at least:
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tool", root, psword);
btw remove the ResultSet. You dont use it.
You have a comma at the end of this statement with no value after it. I think your number of arguments are incomplete. I also assume the userID and password needs to be somewhere in the argument list.
DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
Whoops - someone answered the question before I could post this. Guess I need to type faster.
i tried to make this work .
But still give me error
I still new in this
My .jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Staff Page - Add Book</title>
</head>
<body>
<center>
<h2 style="text-align: center;">Return Book Form.</h2>
<form name="uForm" method="get" action="addbookServlet" enctype="multipart/form-data">
<table align="center" width="300px" style="background-color:#f5f5f5;border:1px solid #e5e5e5; padding:5px;">
<tr><td colspan=2 align="center" height="10px"></td></tr>
<tr>
<td><b>Book ID</b></td>
<td><input type="text" name="book_id" size="50"></td>
</tr>
<tr>
<td><b>Book Title</b></td>
<td><input type="text" name="book_title" size="50"></td>
</tr>
<tr>
<td><b>Book Author</b></td>
<td><input type="text" name="book_author" size="50"></td>
</tr>
<tr>
<td><b>Book Quantity</b></td>
<td><input type="text" name="book_quantity" size="50"></td>
</tr>
<tr>
<td><b>Book Location</b></td>
<td><input type="text" name="book_location" size="50"></td>
</tr>
<tr>
<td><b>Book Image</b></td>
<td><input type="file" name="book_image" accept="image/x-png, image/gif, image/jpeg" size="50"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="g-button" value="Submit"></td>
</tr>
<tr><td colspan=2 align="center" height="10px"></td></tr>
</table>
</form>
</center>
</body>
</html>
My .java file
package caal;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import caal.DbConnection.*;
public class AddBook extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.setContentType("text/html");
// PrintWriter out = response.getWriter();
Connection con = null; // connection to the database
String message = null; // message will be sent back to client
// Statement stmt;
String book_id = request.getParameter("book_id");
String book_title = request.getParameter("book_title");
String book_author = request.getParameter("book_author");
String book_quantity = request.getParameter("book_quantity");
String book_location = request.getParameter("book_location");
//String book_image = request.getParameter("book_image");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("book_image");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = DbConnection.getConn();
String query = "INSERT INTO booktable(bookId, bookTitle, bookAuthor, bookQuantity, bookLocation, bookimage) VALUES (?,?,?,?,?,?)";
System.out.println("query " + query);
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, book_id);
statement.setString(2, book_title);
statement.setString(3, book_author);
statement.setString(4, book_quantity);
statement.setString(5, book_location);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(6, inputStream);
}
//stmt = con.createStatement();
//stmt.executeUpdate(query);
response.sendRedirect("login.jsp");
con.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
// closes the database connection
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My web.xml become error . if i put like this
<!-- SERVLET FOR ADD BOOK -->
<servlet>
<servlet-name>addBookServlet</servlet-name>
<servlet-class>caal.AddBook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addBookServlet</servlet-name>
<url-pattern>/addbookServlet</url-pattern>
</servlet-mapping>
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
The error is
Error occurred during deployment: Exception while deploying the app [fpx] : org.xml.sax.SAXParseException; lineNumber: 52; columnNumber: 23; Deployment descriptor file WEB-INF/web.xml in archive [web]. cvc-complex-type.2.4.a: Invalid content was found starting with element 'multipart-config'. One of '{"http://java.sun.com/xml/ns/j2ee":description, "http://java.sun.com/xml/ns/j2ee":display-name, "http://java.sun.com/xml/ns/j2ee":icon, "http://java.sun.com/xml/ns/j2ee":distributable, "http://java.sun.com/xml/ns/j2ee":context-param, "http://java.sun.com/xml/ns/j2ee":filter, "http://java.sun.com/xml/ns/j2ee":filter-mapping, "http://java.sun.com/xml/ns/j2ee":listener, "http://java.sun.com/xml/ns/j2ee":servlet, "http://java.sun.com/xml/ns/j2ee":servlet-mapping, "http://java.sun.com/xml/ns/j2ee":session-config, "http://java.sun.com/xml/ns/j2ee":mime-mapping, "http://java.sun.com/xml/ns/j2ee":welcome-file-list, "http://java.sun.com/xml/ns/j2ee":error-page, "http://java.sun.com/xml/ns/j2ee":jsp-config, "http://java.sun.com/xml/ns/j2ee":security-constraint, "http://java.sun.com/xml/ns/j2ee":login-config, "http://java.sun.com/xml/ns/j2ee":security-role, "http://java.sun.com/xml/ns/j2ee":env-entry, "http://java.sun.com/xml/ns/j2ee":ejb-ref, "http://java.sun.com/xml/ns/j2ee":ejb-local-ref, "http://java.sun.com/xml/ns/j2ee":service-ref, "http://java.sun.com/xml/ns/j2ee":resource-ref, "http://java.sun.com/xml/ns/j2ee":resource-env-ref, "http://java.sun.com/xml/ns/j2ee":message-destination-ref, "http://java.sun.com/xml/ns/j2ee":message-destination, "http://java.sun.com/xml/ns/j2ee":locale-encoding-mapping-list}' is expected.. Please see server.log for more details.
I also have try using #MultipartConfig but it still not working . I need some help .
In web.xml, you must have correct and corresponding DOCTYPE and DTD/XSD setting, otherwise you may get xml invalidation error.
Try check your web.xml XSD setting refer here and try again.
The XSD version is preferred since JSP 2.0 / Servlets 2.4 (eg: Tomcat 5.5). Note that the XML encoding can be specified as ISO-8859-1, UTF-8, or any other valid encoding in either version, and should match the actual encoding of your text file.