I have a servlet that should update a record from my database.
There must be something wrong with my code because tomcat shows error: java.lang.NumberFormatException: null #package_ergasia.EditProtein.doPost(EditProtein.java:36) which is this line: int i = Integer.parseInt(request.getParameter("i"));
Here is my Servlet:
package package_ergasia;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EditProtein extends HttpServlet
{
Connection connection;
Statement statement;
ResultSet resultset;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
Connection connection= null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "ergasia";
String user = "root";
String password = "password";
String id = request.getParameter("id");
String name = request.getParameter("pname");
String desc = request.getParameter("desc");
String seq = request.getParameter("seq");
int i = Integer.parseInt(request.getParameter("i"));
try {
connection = DriverManager.getConnection(url + dbName, user, password);
PreparedStatement ps = connection.prepareStatement("UPDATE protein SET pdb_id=?,proteinName=?,description=?,proteinSequence=? WHERE i=?");
ps.setString(1, id);
ps.setString(2, name);
ps.setString(3, desc);
ps.setString(4, seq);
ps.setInt(5, i);
ps.executeUpdate();
RequestDispatcher view = request.getRequestDispatcher("/InsertProtein");
view.forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Here is the jsp with the form where the user can update the data:
<%#page import="java.util.Iterator"%>
<%#page import="java.util.ArrayList"%>
<%# page language="java" import="java.sql.*"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../CSS/mystyle.css">
</head>
<body>
<h1>Welcome</h1>
<form method="post" action="/EditProtein">
<fieldset style="width: 100px">
<legend>Update protein table</legend>
<table border="1">
<%
int count = 0;
if (session.getAttribute("EditData") != null) {
ArrayList al1 = (ArrayList) session.getAttribute("EditData");
Iterator itr = al1.iterator();
while (itr.hasNext()) {
count++;
ArrayList pList = (ArrayList) itr.next();
%>
<tr>
<td>pdb_id</td>
<td><input type="text" disabled="disabled" font="Verdana" name="id" value="<%=pList.get(0)%>"</td>
</tr>
<tr>
<td>Protein Name</td>
<td><input type="text" font="Verdana" name="pname" value="<%=pList.get(1)%>"</td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" font="Verdana" name="desc" value="<%=pList.get(2)%>"</td>
</tr>
<tr>
<td>Sequence</td>
<td><input type="text" font="Verdana" name="seq" value="<%=pList.get(3)%>"</td>
</tr>
<tr>
<td>i</td>
<td><input type="number" disabled="disabled" font="Verdana" name="i" value="<%=pList.get(4)%>"</td>
</tr>
<tr>
<td><input type="submit" value="Update"></td>
<td><input type="reset" value="Reset"></td>
</tr>
<% }} %>
</table>
</fieldset>
</form>
</body>
</html>
I'd appreciate your help!
here possible error line is
int i = Integer.parseInt(request.getParameter("i"));
request.getParameter("i") is not properly set on your previous page.
in this servlet parameter value is get as null,or other then number(like i76 - i is not number).
check your previous page there i is set.
Check if the parameter i is sent. Becaus if it is not set, request.getParameter("i") will return null, and when you try to convert it to an int you get the error
Related
I have a List in my controller which is being of type Student(class in the model)
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
List<Student> obj = new List<Student>() {
new Student() { ID=1,Name="titi",Address="bbsr"},
new Student() { ID=1,Name="titi1",Address="bbsr"},
new Student() { ID=1,Name="titi2",Address="bbsr"}
};
ViewBag.data = obj;
return View();
}
}
I am using Angular JS (Beginner to Angular JS)
<html>
<head>
<title>Index</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="EFView">
#{ var a = ViewBag.data;}
<div ng-init="init(#Html.Raw(a)">
<table>
<tr ng-repeat="x in a">
<td >
{{x.ID}}
</td>
<td>
{{x.Name}}
</td>
<td>
{{x.Address}}
</td>
</tr>
</table>
</div>
</body>
</html>
Not getting the output as expected.. where & what I am missing, I tried with all trial
I am try to get count of row of a web page table but I am getting dimension of the table.
I have file called TableRow class and this class using properties file "webelement.properties" .In properties file i have kept the path of web element
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TableRow {
protected static WebDriver driver;
#BeforeClass
public static void setup() {
driver = new FirefoxDriver();
driver.get("some url");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
public Properties getWebElementDetails() throws IOException {
Properties p = new Properties();
// Read object repository file
InputStream stream = new FileInputStream(
new File(System.getProperty("user.dir") + "//src//com//properties//webelement.properties"));
p.load(stream);
return p;
}
public WebElement getElementByXPath(String Key) throws IOException {
Properties propertiesValue = getWebElementDetails();
try {
return driver.findElement(By.xpath(propertiesValue.getProperty(Key)));
} catch (Throwable t) {
// If element not found on page then It will return null.
return null;
}
}
#Test()
void testLogincase1() throws Exception{
Thread.sleep(2000);
System.out.println(getElementByXPath("tab")).getsize());
}
}
webelement.properties
tab=.//*[#id='LinkedForm_Organization_OfficeChild']/div[2]/div[1]/div/table/tbody/tr
HTML COde.
<div class="row">
<div class="column">
<table class="linked-record-table data-table">
<thead>
<tr>
<th>Details</th>
<th>Name</th>
<th>Address 1</th>
<th>Address 2</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
</tr>
</thead>
<tbody>
<tr class="data-row" data-is-new="false">
<input id="Organization_OfficeChild_R1_" type="hidden" value="1" name="Organization_OfficeChild_R1_"/>
<input id="Organization_OfficeChild_R1__pky" type="hidden" value="4223" name="Organization_OfficeChild_R1__pky"/>
<td>
<a class="link darker" href="/Office/Details/4223?mode=Edit&_fcl=Organization&_fky=2291">
</td>
<td>
<td>
<td>
<td>
<td>
<td>
</tr>
<tr class="data-row" data-is-new="false">
<tr class="data-row new-row-template" data-is-new="true">
<tr class="data-row new-row-template" data-is-new="true">
<tr class="data-row new-row-template" data-is-new="true">
</tbody>
</table>
</div>
What i am doing wrong . Please provide solutions.
Hi please identify the row and column of the table as below
List<WebElement> myrowcount = driver.findElements(By.xpath("//*[#class='linked-record-table data-table']/tbody/tr"));
System.out.println("Size of the row is : " + myrowcount.size());
List<WebElement> mycolumncount = driver.findElements(By.xpath("//*[#class='linked-record-table data-table']/tbody/tr/td"));
System.out.println("Size of the column is : " + mycolumncount.size());
I have a form that ask for user to enter ID. This form is send to a servlet which checks database to see if user exist. If the user exists then it sends me back their ordered items. The ordered items are returned as an array list. Then this array list is redirect to jsp file to display it on the webpage. The user can have more then one order, therefore the array list size can vary. How do I get the array list size so i can display each item in the array list? I do not want to use JSTL.
index.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
/*function signin(id, id2) {
document.getElementById(id).style.display = 'block';
document.getElementById(id2).style.display = 'none';
//document.getElementById(id3).style.display = 'none';
}*/
</script>
<form id="Signin" method="post" action="FindUser">
<h2>Login </h2>
<input type="text" name="txtCustID"
placeholder="UserID"><br>
<br><input type="submit" value="Find">
</form>
<%--!<form id="Signup" method="post" action="FindUser"
style="display:none;">
<h2>Sign Up </h2>
<input type="text" name="UserId"
placeholder="User ID"><br>
<br><input type="text" name="FirstaName"
placeholder="First Name"><br>
<br><input type="text" name="LastName"
placeholder="Last Name"><br>
<br><input type="text" name="Street"
placeholder="Street"><br>
<br><input type="text" name="City"
placeholder="City"><br>
<br><input type="submit" value="Sign Up">
</form> --%>
</body>
FindUser.java:
public class FindUser extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String sID = request.getParameter("txtCustID");
String url = ("admin/UserFound.jsp");
try {
Users one = UserDAO.findUser(sID);
request.setAttribute("theCustomer", one);
if (one.getFirstName().equals("none")) {
url = "admin/UserNotFound.jsp";
}
ArrayList user_order = UserDAO.findOrder(sID);
request.setAttribute("theOrder", user_order);
response.sendRedirect(url);
//RequestDispatcher rd = request.getRequestDispatcher(url);
//rd.forward(request, response);
} catch (ClassNotFoundException e) {
System.err.print("Failed to load Driver");
System.err.print(e);
} catch (SQLException e) {
System.err.print("SQL Error" + e);
System.err.print("SQL State: " + e.getSQLState());
System.err.print("Error Code: " + e.getErrorCode());
} catch (Exception e) {
System.err.println(e);
}
}
UserFound.jsp:
<%--
Document : CustomerFound
Created on : Nov 15, 2014, 9:40:47 PM
Author : mississauga
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<p>First word is: ${theOrder[x].getBoxes()}</P>
<%--<form id="Signin" method="post" action="FindUser"
style="display:none;">
<h2>Login </h2>
<input type="text" name="txtCustID"
placeholder="UserID"><br>
<br><input type="submit" value="Find">
</form> --%>
</body>
</html>
}
Use fn:length function.
Declare fn namespace on the begining of the JSP file
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Later in the code
${fn:length(collection)}
Newer versions of EL accept using the methods defined in the class of the object in EL expressions, so you can simply call the size() method:
<span>Size: ${list.size()}</span>
you should set scope of your UserFound.jsp to request.
ArrayList orderList = (ArrayList ) request.getAttribute("theOrder");
<ul>
<% If(orderList != null) {%>
<% for(String orderName : orderList ) { %>
<li> <%= orderName %> </li>
<% } %>
<% }else{ %>
No Order Found
<% } %>
</ul>
OR
ArrayList orderList = (ArrayList ) request.getAttribute("theOrder");
<ul>
<% If(orderList != null) {%>
<% for(int orderNum =0;i< orderList.size();++orderNum ) { %>
<li> <%= orderList.get(orderNum )%> </li>
<% } %>
<% }else{ %>
No Order Found
<% } %>
</ul>
ArrayList orderList = (ArrayList ) request.getAttribute("theOrder");
//Unchecked cast from Object to ArrayList
I am a newbiee to Struts2 tiles. I want to write website having multiple pages and having support for multiple languages. Many pages will have same layout (so using tiles) only login page will have different layout.
I have searched in for reading the language specific Data from Database and have a method ready for it. I have the base layout ready but I am not able to understand how to integrate internationalization and tiles.
Attaching base layout and Database method
DBResourceBundle.java
package com.ruukki.webui.util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import com.ruukki.webui.vo.ConnectionType;
import com.ruukki.webui.vo.User;
public class DbResourceBundle extends ResourceBundle
{
private Properties properties;
public DbResourceBundle(Properties inProperties)
{
properties = inProperties;
}
#Override
#SuppressWarnings(value = { "unchecked" })
public Enumeration<String> getKeys()
{
return properties != null ? ((Enumeration<String>) properties.propertyNames()) : null;
}
#Override
protected Object handleGetObject(String key)
{
return properties.getProperty(key);
}
public static ResourceBundle.Control getMyControl()
{
return new ResourceBundle.Control()
{
#Override
public List<String> getFormats(String baseName)
{
if (baseName == null)
{
throw new NullPointerException();
}
return Arrays.asList("db");
}
#Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException,
InstantiationException, IOException
{
if ((baseName == null) || (locale == null) || (format == null) || (loader == null))
throw new NullPointerException();
ResourceBundle bundle = null;
if (format.equals("db"))
{
Properties p = new Properties();
Connection con = null;
Statement s = null;
ResultSet rs = null;
try
{
con = LocalDbManager.getConnectionForUser(new User("sa","")) ;
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM Language_Text");
int value =3;
if (locale != null)
{
System.out.println("locale has vlue " + locale.getLanguage());
if(locale.getLanguage().equals("en")){
value = 3;
}else if(locale.getLanguage().equals("fi")){
value = 4;
}
}
s = con.createStatement();
System.out.println("stmt:" + s);
rs = s.executeQuery(query.toString());
System.out.println("Executed Query and got data:" + query);
System.out.println("Column count" );
while (rs.next())
{
p.setProperty(rs.getString(1), rs.getString(value));
}
System.out.println("Is property Filleked" + p.isEmpty());
}
catch (Exception e)
{
System.out.println("failed to build properties file");
e.printStackTrace();
throw new RuntimeException("Can not build properties: " + e);
}
finally
{
ConnectionManager.closeQuietly(con, s, rs);
}
bundle = new DbResourceBundle(p);
}
return bundle;
}
#Override
public long getTimeToLive(String baseName, Locale locale)
{
return 1000 * 60 * 30;
}
#Override
public boolean needsReload(String baseName, Locale locale, String format, ClassLoader loader, ResourceBundle bundle, long loadTime)
{
return true;
}
};
}
}
tiles.xml
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="baseLayout" template="/baseLayout.jsp">
<put-attribute name="title" value="Template"/>
<put-attribute name="header" value="/header.jsp"/>
<put-attribute name="menu" value="/menu.jsp"/>
<put-attribute name="body" value="/body.jsp"/>
<put-attribute name="footer" value="/footer.jsp"/>
</definition>
</tiles-definitions>
header.jsp
<%# page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<head>
<link type="text/css" rel="stylesheet" href="ruukki.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="header">
<table width="100%">
<tr>
<td width="10%"><div id="Logo" > <img src="logo.png"> </div></td>
<td width="50%"><div id="Welcome_Portal"> Welcome to Portal !!! </div>
<td width="15%"><p align="left" style="vertical-align: bottom;">Welcome, <s:property value="username"/></p></td>
<td width="2%" align="center"><img alt="" src="Image/flag_en.png"></a></td>
<td width="2%" align="center"><img alt="" src="Image/flag_fin.png"></td>
<td width="2%" align="center"><img alt="" src="Image/flag_sw.png"></td>
<td width="5%"><s:url id="logout" action="logout"/>
<s:a href="%{logout}" target="_parent">Logout </s:a>
</td>
</tr>
</table>
</div>
</body>
strtus.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="*Link" method="{1}" class="com.tutorials4u.actions.LinkAction">
<result name="welcome" type="tiles">welcome</result>
<result name="struts" type="tiles">struts</result>
</action>
</package>
</struts>
baseLayout.jsp
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<!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=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
</head>
<body>
<table border="0" cellpadding="2" cellspacing="2" align="center" width="100%" height="100%">
<tr>
<td height="10%" colspan="2">
<tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td width="20%" height="80%">
<tiles:insertAttribute name="menu" />
</td>
<td width="80%" height="80%" style="min-height: 120px">
<tiles:insertAttribute name="body" />
</td>
</tr>
<tr>
<td height="10%" colspan="2">
<tiles:insertAttribute name="footer" />
</td>
</tr>
</table>
</body>
</html>
With change in language I want to display the Contents from header as per the language selected.
Currently tried with this in the page to have the language contents
<%
ResourceBundle lbls = null;
ResourceBundle msgs = null;
try {
String value = Globals.LOCALE_KEY.toString();
System.out.println("value: " + value);
Locale locale = new Locale("fi","");
lbls = ResourceBundle.getBundle("AwesomeBundle", locale, DbResourceBundle.getMyControl());
} catch (Exception ex) {
}
%>
But I want it to be used in all pages...So a bit confused. And Sorry if it is too stupied question.
i would like to authenticate user and password which the data store in database. I'm using Netbeans IDE in my decelopment. The problem I faced is it keep show an error page with content internal server error. Can someone one help me to check my code. I have some code like this:
LoginForm.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Form</title>
</head>
<body bgcolor="#D8CEF6">
<h1>Login Page</h1>
<fieldset>
<center>
<legend><h2>Sign in Details</h2> </legend>
<form action="LoginCheck.jsp" method="post">
<br/>Username:<input type="text" name="username"/>
<br/>Password:<input type="password" name="password"/>
<br/>
<tr>
<td>usertype</td>
<td>
<select name="usertype">
<option value="student">student</option>
<option value="faculty">faculty</option>
</select>
</td>
</tr>
<tr>
<td>
<br/><input type="submit" value="Submit" name="bt"/>
</td>
</tr>
</form>
</center>
</fieldset>
</body>
</html>
LoginCheck.jsp:
<%#page import ="java.sql.*" %>
<%#page import ="java.io.IOException" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.io.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Check</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String userType = request.getParameter("usertype");
String dbURL = "jdbc:derby://localhost:1527/learningApp";
String dbuser = "learningApp";
String dbpassword = "p#ssw0rd";
Connection theConnection = null;
PreparedStatement theStatement = theConnection.prepareStatement("select * from USERNAME where username=? and password=?");
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}catch(Exception ex){
System.out.println("Class Not Found");
}
try{
theConnection = DriverManager.getConnection(dbURL, dbuser, dbpassword);
}catch(Exception ex){
System.out.println("Connection Error");
}
try{
theStatement.setString(1,request.getParameter("username"));
theStatement.setString(2,request.getParameter("password"));
ResultSet theResult = theStatement.executeQuery();
if(theResult.next()){
response.sendRedirect("Home.jsp");
}
}catch(Exception ex){
System.out.println("Statement Error");
}
%>
</body>
</html>
My database name is learningApp with password p#ssw0rd
and have a table named USERNAME with a user(username = alice, password = alice)
You might want to place the derbyclient.jarand derby.jar in the WebContent/WEB-INF/Lib and also include the same in the build path.
Update:
I changed your code (LoginCheck.jsp) to this , (I'm using Oracle DB). Seems to be working fine for me.
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String userType = request.getParameter("usertype");
String driver = "oracle.jdbc.driver.OracleDriver";
String dbURL = "jdbc:oracle:thin:#10.113.130.22:1521:ORCL";
String dbuser = "user";
String dbpassword = "password";
Connection theConnection = null;
PreparedStatement theStatement = null;
try{
Class.forName(driver);
theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
theStatement = theConnection.prepareStatement("select * from USERNAME where username=? and password=?");
theStatement.setString(1,request.getParameter("username"));
theStatement.setString(2,request.getParameter("password"));
ResultSet theResult = theStatement.executeQuery();
if(theResult.next())
System.out.println("Success");
else
System.out.println("Failed");
}catch(Exception e){
System.out.println("Exception occured! "+e.getMessage()+" "+e.getStackTrace());
}
%>
</body>