NullPointer Exception in jsp [closed] - sql

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet UserController threw exception
java.lang.NullPointerException
at com.nic.sample.dao.UserDAO.getAllUsers(UserDAO.java:69)
at com.nic.sample.controller.UserController.doGet(UserController.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:709)
at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:680)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:64)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
I have the above error when I run the my application, am fetching data from database to jsp using dao, I don't know why am getting this error. Need help. My jsp and DAO code is below
My jsp file listuser.jsp
<%# page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#page errorPage="error.jsp" %>
<!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=EUC-KR">
<title>Show All Users</title>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>User Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Email</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.userid}" /></td>
<td><c:out value="${user.firstName}" /></td>
<td><c:out value="${user.lastName}" /></td>
<td><fmt:formatDate pattern="yyyy-MMM-dd" value="${user.dob}" /></td>
<td><c:out value="${user.email}" /></td>
<td>Update</td>
<td>Delete</td>
</tr>
</c:forEach>
</tbody>
</table>
<p>Add User</p>
My UserDAO.java
package com.nic.sample.dao;
public class UserDAO {
private Connection connection;
public UserDAO() {
connection = DbUtil.getConnection();
}
public void addUser(User user) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into users(firstname,lastname,dob,email) values (?, ?, ?, ? )");
// Parameters start with 1
preparedStatement.setString(1, user.getFirstName());
preparedStatement.setString(2, user.getLastName());
preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteUser(int userId) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("delete from users where userId=?");
// Parameters start with 1
preparedStatement.setInt(1, userId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateUser(User user) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("update users set firstname=?, lastname=?, dob=?, email=?" +
"where userid=?");
// Parameters start with 1
preparedStatement.setString(1, user.getFirstName());
preparedStatement.setString(2, user.getLastName());
preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.setInt(5, user.getUserid());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from users");
while (rs.next()) {
User user = new User();
user.setUserid(rs.getInt("userid"));
user.setFirstName(rs.getString("firstName"));
user.setLastName(rs.getString("lastName"));
user.setDob(rs.getDate("dob"));
user.setEmail(rs.getString("email"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
public User getUserById(int userId) {
User user = new User();
try {
PreparedStatement preparedStatement = connection.
prepareStatement("select * from users where userid=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
user.setUserid(rs.getInt("userid"));
user.setFirstName(rs.getString("firstName"));
user.setLastName(rs.getString("lastName"));
user.setDob(rs.getDate("dob"));
user.setEmail(rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
Please can anyone help me out, I am really stuck here...

In your getAllUsers method connection.createStatement(); may be connection is null.
Everything fine otherthan that .Debug it to make sure ..
And finally follow this link too
http://www.vogella.com/articles/EclipseDebugging/article.html

Related

Use and ArrayList to display data from an MVC Controller to a Razor Page

I'm pretty new to working with Array Lists and would like to learn how to display data from the Controller that has an Array in the method to the MVC Razor Page. I'm creating a login that works just fine, but would like to display captured data from Active Directory to the UserLoginData.CSHTML page. I read that the best way is through the model. Any help would be greatly appreciated! (I just want the ArrayList in a table on the Razor data Page.)
Controller:
enter code here
public ActionResult UserLoginData(string username, string LblUserName, string
UserName, ArrayList AuthorizationGroups)
{
UserLoginModel model = new UserLoginModel();
UserName = username;
ViewBag.UserName = UserName;
model.UserName = UserName;
model.LblUserName = model.UserName;
model.AuthorizationGroups = AuthorizationGroups;
foreach (var item in AuthorizationGroups)
{
// Console.WriteLine(item);
model.item = item;
}
return View(model);
}
Model (Properties):
//Labels for UserLoginData:
public string LblUserName { get; set; }
public string LblTitle { get; set; }
public string LblPlantLocation { get; set; }
public string LblUserLoggedInTimeStamp { get; set; }
public string LblUserLoggedOutTimeStamp { get; set; }
public string LblDisplayName { get; set; }
public string LblEmail { get; set; }
//For the ArrayList of MemberGroups.
public ArrayList AuthorizationGroups { get; set; }
public ArrayList YardDogUserGroupMembers { get; set; }
public ArrayList MemberOfUserGroups { get; set; }
public ArrayList YardDogAdminGroupMembers { get; set; }
public object item { get; set; }
Razor CSHTML:
enter code here
#model PW_Login.Models.UserLoginModel
#{
Layout = null;
/*
WebGrid webGrid = new WebGrid(source: Model, canPage: true, canSort: true,
sortDirectionFieldName: "PlantLocation", rowsPerPage: 50);
webGrid.Pager(WebGridPagerModes.All);
*/
}
<!DOCTYPE html>
<html>
<head>
<link href="~/Content/UserLogin.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
#using (Html.BeginForm("UserLoginData", "LoginController", FormMethod.Post, new { id =
"LoginDataForm", Class = "LoginDataForm" }))
{
//Html.ListBoxFor(model=>model.AuthorizationGroups, Model.AuthorizationGroups)
// string UserName = Session["UserName"].ToString();
<label></label>
//Html.LabelFor(model => model.UserName, #Model.UserName)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.UserName)
</th>
<th>
#Html.DisplayNameFor(model => model.UserPlantLocation)
</th>
</tr>
<tr>
<td>
<!--- Html.DisplayFor(modelItem => item.AuthorizationGroups) -->
#foreach ( var item in Model.AuthorizationGroups)
{
#Html.DisplayNameFor(Modelitem=>item)
}
</td>
</tr>
</table>
}
</body>
</html>
Method that gets the info from AD in the Controller:
private void ShowUserInformation(SearchResult rs, string UserName)
{
UserLoginModel model = new UserLoginModel();
Cursor.Current = Cursors.Default;
model.UserName = UserName;
Session["UserName"] = UserName;
Session["LblUserName"] = UserName;
DateTime now = DateTime.Now;
string UserLoggedInTimeStamp = now.ToString();
model.LblUserLoggedInTimeStamp = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
//Push the UserName into the Label via the model.
if (rs.GetDirectoryEntry().Properties["samaccountname"].Value != null)
model.LblUserName = "Username : " +
rs.GetDirectoryEntry().Properties["samaccountname"].Value.ToString();
if (rs.GetDirectoryEntry().Properties["title"].Value != null)
model.LblTitle = "Title : " +
rs.GetDirectoryEntry().Properties["title"].Value.ToString();
//description returns null... need to find out active directory folder/subfolder.
if (rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value != null)
//PhysicalDeliveryOfficeName returns 110.
model.LblPlantLocation = "PlantLocation : " +
rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString();
if (rs.GetDirectoryEntry().Properties["member"].Value != null)
model.LblMemberGroup = "Member : " +
rs.GetDirectoryEntry().Properties["member"].Value.ToString();
//DisplayName or DistinguishedName is what I do believe is in the security group
"YardDogUser" or "YardDogAdmin".
if (rs.GetDirectoryEntry().Properties["distinguishedName"].Value != null)
model.LblDistinguishedName = "distinguishedName : " +
rs.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString();
//NULL...
if (rs.GetDirectoryEntry().Properties["YardDogAdmin"].Value != null)
model.LblYardDogAdmin = "YardDogAdmin : " +
rs.GetDirectoryEntry().Properties["YardDogAdmin"].Value.ToString();
if (rs.GetDirectoryEntry().Properties["displayname"].Value != null)
model.LblDisplayName = "Display Name : " +
rs.GetDirectoryEntry().Properties["displayname"].Value.ToString();
if (rs.GetDirectoryEntry().Properties["email"].Value != null)
model.lblEmail = "Email Address : " +
rs.GetDirectoryEntry().Properties["email"].Value.ToString();
/*
//Member Of Office 365 Groups. Use if needed!
///ArrayList MemberOfGroups = new ArrayList();
var MemberOfGroups = new ArrayList(); //perfered way of writing.
string Ret1 = string.Empty;
foreach (object memberOf in rs.GetDirectoryEntry().Properties["memberOf"])
{
MemberOfGroups.Add(Ret1 += " Member Of : " + memberOf.ToString() + "\n");
}
*/
//Get Security Groups that User belongs to. Note: Doesn't show other groups (won't
show YardDogAdmin).
ArrayList SecurityGroups = new ArrayList();
foreach (IdentityReference group in
System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
{
SecurityGroups.Add(group.Translate(typeof(NTAccount)).ToString());
}
//model doesn't show the correct datetime on these.
model.LblUserLoggedInTimeStamp = model.UserLoggedInTimeStamp.ToString();
model.LblUserLoggedOutTimeStamp = model.UserLoggedOutTimeStamp.ToString();
/******************************************************************************/
//Search to see if this group exists that starts with "YardDog".
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
ArrayList FoundYardDogAdmin = new ArrayList();
ArrayList SecurityGroupsFound = new ArrayList();
// define a "query-by-example" principal - here, we search for a GroupPrincipal
// and with the name like some pattern
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
qbeGroup.Name = "YardDog*"; //Find all the User Groups for this User that is
logging in.
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
string Ret4 = string.Empty;
// find all matches
foreach (var found in srch.FindAll())
{
FoundYardDogAdmin.Add(Ret4 += " GroupFound : " + found.ToString() + "\n");
SecurityGroupsFound.Add(Ret4 += " GroupFound : " + qbeGroup.ToString() +
"\n");
}
//Count where the User's Display Name exists is needed next. We could do this here
or when we get all the Groups.
}
//Search for all User's of YardDogAdmin Group and list them in the ArrayList.
/*
using PrincipalContext ctxDomain = new PrincipalContext(ContextType.Domain);
{
// get the group you're interested in
GroupPrincipal GroupMembers = GroupPrincipal.FindByIdentity("YardDogAdmin");
ArrayList GroupMembersArray = new ArrayList();
// iterate over its members
foreach (Principal principal in GroupMembers.Members)
{
GroupMembersArray.Add(principal);
}
}
*/
/* Below works, finds all in YardDogAdmin's, YardDogUser's (Finds security groups by
string search). Use if needed.*/
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
//Groups to validate against for current User.
var GroupYardDogAdminPrincipalName = "YardDogAdmin";
var GroupYardDogUserPrincipalName = "YardDogUser";
//Find the current User's Groups.
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, UserName);
//Find all User's within these Groups.
GroupPrincipal YardDogAdminMembers = GroupPrincipal.FindByIdentity(ctx,
GroupYardDogAdminPrincipalName);
GroupPrincipal YardDogUserMembers = GroupPrincipal.FindByIdentity(ctx,
GroupYardDogUserPrincipalName);
//UserGroups that the User logged in belongs to.
if (user != null)
{
var MemberOfUserGroups = new ArrayList();
model.MemberOfUserGroups = MemberOfUserGroups;
var groups = user.GetAuthorizationGroups();
foreach (GroupPrincipal group in groups)
{
MemberOfUserGroups.Add(group);
}
if (MemberOfUserGroups.Contains("YardDogAdmin"))
{
//Pass to the model YardDogAdmin exists for this user (AdminFlag translates to
LocationData table).
model.LblYardDogAdmin = "Y";
model.AdminFlag = "Y";
}
else
{
model.LblYardDogAdmin = "N";
model.AdminFlag = "N";
}
//Get the Members of YardDogAdmin and their warehouse locations.
if (YardDogAdminMembers != null)
{
var YardDogAdminGroupMembers = new ArrayList();
model.YardDogAdminGroupMembers = YardDogAdminGroupMembers;
foreach (Principal principal in YardDogAdminMembers.Members)
{
rs = SearchUserByDisplayName(principal.DisplayName.ToString());
YardDogAdminGroupMembers.Add(principal.DisplayName + " " +
rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString() + "
YardDogAdmin");
}
}
//Get the Members of YardDogUser and their location.
if (YardDogUserMembers != null)
{
var YardDogUserGroupMembers = new ArrayList();
model.YardDogUserGroupMembers = YardDogUserGroupMembers;
foreach (Principal principal in YardDogUserMembers.Members)
{
rs = SearchUserByDisplayName(principal.DisplayName.ToString());
YardDogUserGroupMembers.Add(principal.DisplayName + " " +
rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString() + "
YardDogUser");
}
}
}
}
Just create TempData[] in the controller from one controller action result to another and then into the model also. After that you can access the TempData and keep it as needed for that session. Then on the Login Data Page, loop through the objects from the TempData or model properties to display in labels.
enter code here
#model PW_Login.Models.UserLoginModel
#{
Layout = null;
string UserName = TempData["UserName"].ToString();
string PlantLocation = TempData["UserPlantLocation"].ToString();
string UserLoggedInTimeStamp =
TempData["UserLoggedInTimeStamp"].ToString();
//Get the TempData Sessions and write them out.
var SecurityGroups = TempData["SecurityGroups"];
var MemberOfUserGroups = TempData["MemberOfUserGroups"];
var YardDogAdminGroupMembers = TempData["YardDogAdminGroupMembers"];
var YardDogUserGroupMembers = TempData["YardDogUserGroupMembers"];
TempData.Keep(UserLoggedInTimeStamp.ToString());
TempData.Keep(SecurityGroups.ToString());
TempData.Keep(MemberOfUserGroups.ToString());
TempData.Keep(YardDogAdminGroupMembers.ToString());
TempData.Keep(YardDogUserGroupMembers.ToString());
// PW_Login.Models.UserLoginModel LoginModel;
// LoginModel.SecurityGroups = SecurityGroups;
}
<!DOCTYPE html>
<html>
<head>
<link href="~/Content/UserLogin.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<asp:Panel runat="server" ID="Panel2" HorizontalAlign="Center">
<img id="PM_Logo" src="~/images/PremiumWatersLogo.PNG" />
</asp:Panel>
<h2>User Login Groups</h2><br /><br />
<div id="time"></div>
<SCRIPT LANGUAGE="Javascript">
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" +
s; //Get the time.
document.getElementById('time').innerHTML = "Date: " + today;
//Get the Date.
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
</SCRIPT>
#using (Html.BeginForm("UserLoginData", "LoginController", FormMethod.Post,
new { id = "LoginDataForm", Class = "LoginDataForm" }))
{
<dv id="FlexLoginDataTables" class="FlexLoginDataTables">
<table id="LoginDataTable" class="LoginDataTable">
<tr>
<th>
#Html.LabelForModel(UserName, "User Name: ")
</th>
</tr>
<tr>
<td>
#foreach (var group in #Model.SecurityGroups)
{
<label id="LoginDataLabel"
class="LoginDataLabel">#group.ToString()</label><br />
}
</td>
</tr>
</table>
<table id="LoginDataTable" class="LoginDataTable">
<tr>
<th>
#Html.LabelFor(m => m.YardDogAdminGroupMembers)
</th>
</tr>
<tr>
<td>
#foreach (var group in #Model.YardDogAdminGroupMembers)
{
<label id="LoginDataLabel"
class="LoginDataLabel">#group.ToString()</label><br />
}
</td>
</tr>
</table>
<table id="LoginDataTable" class="LoginDataTable">
<tr>
<th>
#Html.LabelFor(m => m.YardDogUserGroupMembers)
</th>
</tr>
<tr>
<td>
#foreach (var group in #Model.YardDogUserGroupMembers)
{
<label id="LoginDataLabel"
class="LoginDataLabel">#group.ToString()</label><br />
}
</td>
</tr>
</table>
</dv>
<table>
<tr>
<th>
#Html.LabelFor(model => model.UserLoggedInTimeStamp,
#Model.UserLoggedInTimeStamp)
</th>
<td>
#Html.Label(#Model.UserLoggedInTimeStamp.ToString())
</td>
</tr>
</table>
<table id="LoginDataTable" class="LoginDataTable">
<tr>
<th>
</th>
<td>
</td>
</tr>
</table>
}
</body>
</html>

Why session.getAttribute() always returning null inside JSP page textbox?

I am always getting null value in jsp page textbox. I have defined name attribute in index.jsp page and fetching value using <%=session.getAttribute()%>.
Here is index.jsp
<tr>
<td>First Name</td>
<td>
<input type="text" required="" name="firstname" value="<%=session.getAttribute("firstname")%>"/>
</td>
</tr>
In below UploadServletClass.java, session is defined
public class UploadServletClass extends HttpServlet{
PrintWriter out = null;
Connection con = null;
PreparedStatement ps = null;
HttpSession session = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/plain;charset=UTF-8");
try{
out = response.getWriter();
session = request.getSession();
...
}
}
}
This is loginScript.jsp
<%
String zfid = request.getParameter("zid");
String fname = request.getParameter("firstname");
...
if (rs.next()) {
session.setAttribute("zfid", zfid); //used ${sessionScope.zfid} to display value into textbox and it is successful.
session.setAttribute("firstname",fname); //failed to display value in textbox
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("home.jsp");
}

Java Program to View the file Diff

Result.jsp :
<%#page import="org.apache.commons.lang3.StringUtils"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.ArrayList"%>
<%#page import="util.Utility"%>
<%# 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>
<table cellpadding="3" cellspacing="3" border="3">
<tr>
<th align="center"><b>Current BootConf</b></th>
<th><b>New BootConf</b></th>
</tr>
<%
ArrayList<String> currentHacks = (ArrayList<String>) request.getAttribute("currentHacks");
ArrayList<String> newHacks = (ArrayList<String>) request.getAttribute("newHacks");
int size = currentHacks.size() > newHacks.size() ? currentHacks.size() : newHacks.size();
Iterator<String> current = currentHacks.iterator();
/* String cur[]=new String[currentHacks.size()];
String newBootconf[]=new String[newHacks.size()]; */
String cur[]=new String[size];
String newBootconf[]=new String[size];
int count=0;
while (current.hasNext()) {
cur[count]=(String)current.next();
count++;
}
count=0;
Iterator<String> new_hacks = newHacks.iterator();
while (new_hacks.hasNext()) {
newBootconf[count]=(String)new_hacks.next();
count++;
}
for(int i=0;i<size;i++){ %>
<tr>
<%
if(!Utility.replaceNull(cur[i]).equalsIgnoreCase(Utility.replaceNull(newBootconf[i]))){
%>
<td bgcolor="red"><%= Utility.replaceNull(cur[i])%></td>
<td bgcolor="red"><%= Utility.replaceNull(newBootconf[i])%></td>
<%}else{ %>
<td><%= Utility.replaceNull(cur[i])%></td>
<td><%= Utility.replaceNull(newBootconf[i])%></td>
<%}%>
</tr>
<%}
%>
</table>
</body>
</html>
ServletDiff.java
DoGet Method:
ArrayList<String> currentHacks = readFile(currentFolderPath, hacks);
ArrayList<String> newHacks = readFile(newFolderPath, hacks);
request.setAttribute("currentHacks",currentHacks);
request.setAttribute("newHacks",newHacks);
RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/result.jsp");
requestDispatcher.forward(request, response);
**Method to Read File**
public ArrayList<String> readFile(String folderPath, String fileName) {
File f =null;
FileInputStream fis = null;
String line = null;
ArrayList<String> result= new ArrayList<String>();
int count=0;
try {
f=new File(folderPath + "\\" + fileName);
fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((line = br.readLine()) != null) {
result.add(StringEscapeUtils.escapeXml(line));
count++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}`
Utility Class
public static String replaceNull(String input) {
return input == null ? "" : input;
}

Handling multiple submit buttons with JSP and Servlets

I have a table that is generated from the database. This table will be enclosed in a form. Below is the result on a browser:
http://i.imgur.com/NLZzgwP.png (Low rep problems)
Below is the JSP/JSTL code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Issues</title>
<style type="text/css">
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td {
padding: 10px;
}
</style>
</head>
<body>
<sql:setDataSource
var="myDS"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/pdfdb"
user="user" password="*******"
/>
<sql:query var="listIssues" dataSource="${myDS}">
SELECT BookId from Book;
</sql:query>
<form method="get" action="fileDownload">
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td><input name='<c:out value="${issue.BookId}" />' type="submit" value="Download"></td>
</tr>
</c:forEach>
</table>
</div>
</form>
</body>
</html>
Now, what I want is for the download button to be kind of linked with the id/Issue number that is placed on the same row as the button such that, when the user clicks the download button, it passes the id/magazine issue number to the url telling the browser that the user wants to download the corresponding magazine issue number of that button clicked. Below is the servlet I use to implement this:
package com.mypackage.fileDownload;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletContext;
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 FileDownloadServlet
*/
#WebServlet("/fileDownload")
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
//database connection settings
private String dbUrl = "jdbc:mysql://localhost:3306/pdfdb";
private String dbUser = "user";
private String dbPass = "******";
/**
* #see HttpServlet#doGet(HttpServletRequesrequest,HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get upload id from URL's parameters
String uploadId = request.getParameter("name");
Connection con = null; //connects to the database
try {
//connects to the database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
//queries the database
String sql = "SELECT * FROM Book WHERE BookId = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, uploadId);
ResultSet result = pstmt.executeQuery();
if(result.next()) {
//gets file name and file blob data
String fileId = result.getString("BookId");
Blob blob = result.getBlob("BookContent");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("File length = " + fileLength);
ServletContext context = getServletContext();
//Sets MIME type for the file download
String mimeType = context.getMimeType(fileId);
if(mimeType == null) {
mimeType = "application/octet-stream";
}
//set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileId);
response.setHeader(headerKey, headerValue);
//writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
} else {
//no file found
response.getWriter().print("File not found for the id: " + uploadId);
}
} catch(SQLException ex) {
ex.printStackTrace();
response.getWriter().print("SQL Error: " + ex.getMessage());
} catch(IOException ex) {
ex.printStackTrace();
response.getWriter().print("IO Error: " + ex.getMessage());
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
response.getWriter().print("Class Missing Error: " + ex.getMessage());
}
finally {
if(con != null) {
//closes the database connection
try {
con.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Well, from the way I have done this, it is not working the way I wanted it to. For example, if you run this code on the server and click any of the download buttons, the url will be something like
issue.jsp?1=Download
which is weird.It will also display on the browser
File not found for the id: null
I expect something like(on the url)
issue.jsp?Download=1
where 1 is the issue being downloaded. My database has two columns: the IssueId and fileContent(content of file stored in BLOB).
I think I have explained enough and the concept is clear. Any help will be appreciated and this is as far as I could go with my code & research. Thanks!
The simplest way is to just move the form inside the table and do multiple forms:
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td>
<form method="get" action="fileDownload">
<input type='hidden' name='bookid' value='<c:out value="${issue.BookId}" />' />
<input type="submit" value="Download">
</form>
</td>
</tr>
</c:forEach>
</table>
</div>
You also need to move the value out of the name attribute of the button and into the value attribute of a hidden input. That hidden input needs a name you will use to get the value in the servlet: request.getParameter("bookid");

RichFaces fileupload and h:message problem

I am using RichFaces 4. My problem is that the message does not appear at all. If I use rich:message the message appears briefly then dissapears.
This is the controller:
public void uploadListener(final FileUploadEvent event) throws IOException
{
final UploadedFile item = event.getUploadedFile();
final FacesContext context = FacesContext.getCurrentInstance();
final Application application = context.getApplication();
final String messageBundleName = application.getMessageBundle();
final Locale locale = context.getViewRoot().getLocale();
final ResourceBundle resourceBundle = ResourceBundle.getBundle(messageBundleName, locale);
final String msg = resourceBundle.getString("upload.failed");
final String detailMsgPattern = resourceBundle.getString("upload.failed_detail");
try
{
CSVImporter.doImport(item.getInputStream(), registry, item.getName());
}
catch (ParseException e)
{
final Object[] params = {item.getName(), e.getMessage()};
final String detailMsg = MessageFormat.format(detailMsgPattern, params);
final FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);
context.addMessage("uploadForm:uploader", facesMsg);
}
catch (TokenMgrError e)
{
final Object[] params = {item.getName(), e.getMessage()};
final String detailMsg = MessageFormat.format(detailMsgPattern, params);
final FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);
context.addMessage("uploadForm:uploader", facesMsg);
}
}
And this is the view:
<h:form id="uploadForm" enctype="multipart/form-data">
<h:message id="message" showDetail="true" for="uploader" errorClass="error" warnClass="warning" infoClass="info" fatalClass="fatal"/>
<rich:fileUpload id="uploader"
fileUploadListener="#{itemController.uploadListener}"
maxFilesQuantity="1"
acceptedTypes="csv">
<a4j:ajax event="uploadcomplete" execute="#none" render="items, message" />
</rich:fileUpload>
</h:form>
In both cases Firebug reports an empty message field being sent.
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="uploadForm:message"><![CDATA[<span id="uploadForm:message"></span>]]></update><update id="j_idt16:items"><![CDATA[<table id="j_idt16:items">
<thead>
<tr>
<th scope="col">
Titles
</th>
</tr>
</thead>
<tbody>
<tr><td></td></tr></tbody>
</table>
]]></update><update id="javax.faces.ViewState"><![CDATA[8859542538952100446:6041172679113548382]]></update></changes></partial-response>
The problem was the a4j:ajax tag. It was sending a second request, and the messages were cleared. This works:
<h:form id="uploadForm" enctype="multipart/form-data">
<h:message id="message" showDetail="true" for="uploader" errorClass="error" warnClass="warning" infoClass="info" fatalClass="fatal"/>
<rich:fileUpload id="uploader"
fileUploadListener="#{itemController.uploadListener}"
maxFilesQuantity="1"
acceptedTypes="csv"
render="items, message" />
</h:form>
Rich upload doesn't rerender messages:
https://community.jboss.org/message/55888
https://issues.jboss.org/browse/RF-3566