insert update delete in Struts 2 but showing NullPointerException - java

Here I come up with problem with Operation like update,delete and view so now insert is working but other operation like update, delete, view showing error like. Could some one can guide to go right direction? This what I have tried up to now
Error:
HTTP Status 500 - java.lang.NullPointerException
type Exception report
message java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.NullPointerException
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
root cause
java.lang.NullPointerException
Action.Testiue.view(Testiue.java:115)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml" />
<package name="a" extends="struts-default">
<action name="adduser" class="Action.Testiue" method="add">
<result name="success">/insert.jsp</result>
<result name="success">/ssuccess.jsp</result>
</action>
<action name="viewuser" class="Action.Testiue" method="view">
<result name="success">/view.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="updateuser" class="Action.Testiue" method="update">
<result name="success">/edit.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="deleteuser" class="Action.Testiue" method="delete">
<result name="success">/dsuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
TestIUE.java
package Action;
import com.opensymphony.xwork2.ActionSupport;
import dao.UserDao;
import dbBean.UseBean;
public class Testiue
{
private String Name;
private String Password;
private String EmailID;
private String Phoneo;
private int ID;
public String getName()
{
return Name;
}
public void setName(String name)
{
Name = name;
}
public String getPassword()
{
return Password;
}
public void setPassword(String password)
{
Password = password;
}
public String getEmailID()
{
return EmailID;
}
public void setEmailID(String emailID)
{
EmailID = emailID;
}
public String getPhoneo()
{
return Phoneo;
}
public void setPhoneo(String phoneo)
{
Phoneo = phoneo;
}
public int getID()
{
return ID;
}
public void setID(int i)
{
ID = i;
}
#Override
public String toString()
{
return "UseBean [id=" + ID + ", Name=" + Name+ ", Password=" + Password + ", EmailID=" + EmailID + ", Phoneo="+ Phoneo + "]";
}
private UserDao dao;
private UseBean bean;
public String add()
{
dao=new UserDao();
bean=new UseBean();
System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.addUser(bean);
return ActionSupport.SUCCESS;
}
public String update()
{
dao=new UserDao();
bean=new UseBean();
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.updateUser(bean);
return ActionSupport.SUCCESS;
}
public String delete()
{
int userId =0;
dao.deleteUser(userId);
return ActionSupport.SUCCESS;
}
public String edit()
{
int userId =0;
bean = dao.getUserById(userId);
return ActionSupport.SUCCESS;
}
public String view()
{
dao.getAllUsers();
return ActionSupport.SUCCESS;
}
}
Index.jsp
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=viewuser.action">
view.jsp;
<%# taglib prefix="s" uri="/struts-tags"%>
<%#page import="java.util.*,dbBean.*,Dbconnect.*,java.util.*"%>
Insert
<table border=1>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>password</th>
<th>phoneno</th>
<th>emailid</th>
<th colspan=2>Action</th>
</tr>
</thead>
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
<tbody>
<tr>
<td><%= user.getID() %></td>
<td><%= user.getName() %></td>
<td><%= user.getPassword() %></td>
<td><%= user.getEmailID() %></td>
<td><%= user.getPhoneo() %></td>
<td>Update</td>
<td>Delete</td>
</tr>
<%
}
%>
</tbody>
</table>
edit.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="updateuser">
id:<input type="text" name="ID" ><br/>
Name:<input type="text" name="Name" ><br/>
Password:<input type="text" name="password" ><br/>
phoneno:<input type="text" name="Phoneo" ><br/>
Emailid:<input type="text" name="Emailid" > <br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
UserDao.java
package dao;
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 java.util.List;
import dbBean.UseBean;
import Dbconnect.*;
public class UserDao
{
private Connection conn;
public UserDao()
{
conn=Dbconnect.getConnection();
}
public void addUser(UseBean bean)
{
try
{
String sql="insert into senthil (name,pass,phoneno,emailid) values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,bean.getName());
ps.setString(2,bean.getPassword());
ps.setString(3,bean.getPhoneo());
ps.setString(4,bean.getEmailID());
ps.executeUpdate();
}
catch (Exception e)
{
// TODO: handle exception
}
}
public void deleteUser(int userId)
{
try
{
PreparedStatement ps = conn.prepareStatement("delete from senthil where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void updateUser(UseBean bean)
{
try
{
PreparedStatement preparedStatement = conn.prepareStatement("update senthil set name=?, pass=?, phoneno=?, emailid=?"+ "where id=?");
// Parameters start with 1
preparedStatement.setString(1, bean.getName());
preparedStatement.setString(2, bean.getPassword());
preparedStatement.setString(3, bean.getPhoneo());
preparedStatement.setString(4, bean.getEmailID());
preparedStatement.setInt(5, bean.getID());
preparedStatement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public List<UseBean> getAllUsers()
{
List<UseBean> users = new ArrayList<UseBean>();
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from senthil");
while (rs.next())
{
UseBean user = new UseBean();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public UseBean getUserById(int userId)
{
UseBean user = new UseBean();
try
{
PreparedStatement preparedStatement = conn.prepareStatement("select * from senthil where id=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
{
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
}
} catch (SQLException e)
{
e.printStackTrace();
}
return user;
}
}

In the JSP the users should be available to the request scope.
public String view() {
UserDao userDao = new UserDao();
List<UseBean> users = userDao.getAllUsers();
ServletActionContext.getRequest().setAttribute("users", users);
return Action.SUCCESS;
}
public String update() {
UserDao dao = new UserDao();
UseBean bean=new UseBean();
HttpServletRequest request ServletActionContext.getRequest();
bean.setID(request.getParameter("ID");
bean.setName(request.getParameter("Name");
bean.setPassword(request.getParameter("Password");
bean.setPhoneo(request.getParameter("Phoneo");
bean.setEmailID(request.getParameter("EmailID");
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
dao.updateUser(bean);
return Action.SUCCESS;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("ID");
dao.deleteUser(userId);
return Action.SUCCESS;
}
for delete action
<s:param name='ID'><%=user.getID()%></s:param></s:url>">Delete

Inside view method you haven't initialized the dao object(i.e reference is null), add the following code :
In TestIUE.java add one more member variable :
List<UseBean> users = new ArrayList<UseBean>();
Also add Accessor method :
public List<UseBean> getUsers()
{
return users;
}
Now modify your view method as follows :
public String view()
{
dao = new UseDao();
users = dao.getAllUsers();
return ActionSupport.SUCCESS;
}

Related

Registration form using JDBC and Servlet in java

I have problem accessing database with servlet java. I want to add users with an html registration form. this is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Registration Page</title>
<!---Custom CSS File--->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<header>Registration Form</header>
<form action="register" method="post" class="form">
<div class="input-box">
<label>Full Name</label>
<input type="text" name="txtUname" placeholder="Enter full name" required />
</div>
<div class="input-box">
<label>Email Address</label>
<input type="email" name="Email" placeholder="Enter email address" required />
</div>
<div class="input-box">
<label>Password</label>
<input type="password" name="Pass" placeholder="Password" required />
</div>
<button>REGISTER</button>
</form>
</body>
</html>
This is the servlet (RegistrationControllerServlet.java)
package com.loginpagedemo.controller;
import java.io.IOException;
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 com.loginpagedemo.dao.UserDao;
import com.loginpagedemo.daoimpl.UserDaoImpl;
import com.loginpagedemo.pojo.User;
#WebServlet("/register")
public class RegistrationControllerServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uname = request.getParameter("txtUname");
String password = request.getParameter("Pass");
String email = request.getParameter("Email");
User u = new User(uname,password,email);
UserDao daoImpl = new UserDaoImpl();
if(daoImpl.addNewUser(u)) {
response.sendRedirect("Success?msg=regsuccess");
}
else {
response.sendRedirect("error?msg=regerror");
}
}
}
This is the java class (User.java):
package com.loginpagedemo.pojo;
public class User {
private String username;
private String emailaddress;
private String password;
public User() {
}
public User(String username,String emailaddress,String password){
this.username = username;
this.emailaddress =emailaddress;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
This is the java Interface (UserDao.java):
package com.loginpagedemo.dao;
import com.loginpagedemo.pojo.User;
public interface UserDao {
boolean checkUserCredentials(User user);
boolean addNewUser(User user);
}
This is the java class (DbConnection.java):
package com.loginpagedemo.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
public static Connection getDatabaseConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/28thnovadv",
"root","ROOT#123");
return con;
}
catch(ClassNotFoundException | SQLException exc) {
exc.printStackTrace();
return null;
}
}
}
This is the java class (UserDaoImpl.java):
package com.loginpagedemo.daoimpl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.loginpagedemo.connection.DbConnection;
import com.loginpagedemo.dao.UserDao;
import com.loginpagedemo.pojo.User;
public class UserDaoImpl implements UserDao {
#Override
public boolean checkUserCredentials(User user) {
try(Connection con =
DbConnection.getDatabaseConnection()){
PreparedStatement st = con.prepareStatement(
"SELECT * FROM userdata WHERE username=? AND email=? AND password=?");
st.setString(1, user.getUsername());
st.setString(2, user.getEmailaddress());
st.setString(3, user.getPassword());
ResultSet rs =st.executeQuery();
if(rs.isBeforeFirst())
return true;
else
return false;
}
catch(SQLException | NullPointerException exc){
exc.printStackTrace();
return false;
}
}
#Override
public boolean addNewUser(User user) {
try(Connection con =
DbConnection.getDatabaseConnection()){
PreparedStatement st = con.prepareStatement(
"INSERT INTO userdata VALUES(?,?,?)");
st.setString(1, user.getUsername());
st.setString(2, user.getEmailaddress());
st.setString(3, user.getPassword());
int count = st.executeUpdate();
if(count > 0)
return true;
else
return false;
}
catch(SQLException | NullPointerException exc){
exc.printStackTrace();
return false;
}
}
}
This is the Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>LoginpageJDBC</display-name>
<welcome-file-list>
<welcome-file>RegistartionFrom.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>registration</servlet-name>
<servlet-class>com.loginpagedemo.controller.RegistrationControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registration</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
Folder Structure
error after updated
I'm sorry that is a long question, but I am in despair
Looks like your implementation of method dopost() is wrong.
It should be doPost().
https://jenkov.com/tutorials/java-servlets/httpservlet.html
Like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
You can also try to configure manually the servlet in WEB-INF/web.xml.
Something like:
<web-app>
<servlet>
<servlet-name>registration</servlet-name>
<servlet-class>com.loginpagedemo.controller.RegistrationControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registration</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
https://javapapers.com/servlet/what-is-servlet-mapping/

Custom debugging interceptor with JSP in Struts 2

I'm using Struts 2.
I want to create a custom interceptor debug class to display in interceptor debugging mode browser all attributes field value when user click save button.
ProduitDto:
public class ProduitDto {
private String reference;
private String designation;
private double prix;
private int quantite;
private boolean promo;
public ProduitDto(String reference, String designation, double prix, int quantite, boolean promo) {
this.reference = reference;
this.designation = designation;
this.prix = prix;
this.quantite = quantite;
this.promo = promo;
}
public ProduitDto() {
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
public int getQuantite() {
return quantite;
}
public void setQuantite(int quantite) {
this.quantite = quantite;
}
public boolean isPromo() {
return promo;
}
public void setPromo(boolean promo) {
this.promo = promo;
}
}
ProduitAction:
import com.id.dto.ProduitDto;
import com.id.entites.Produit;
import com.id.service.ICatalogueService;
import com.id.service.SingletonService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class ProduitAction extends ActionSupport implements ModelDriven<Produit> {
private ProduitDto produitDto = new ProduitDto();
private Produit produit = new Produit();
private List<Produit> produits;
private String ref;
private boolean editMode = false;
private ICatalogueService service = SingletonService.getService();
public String index( ) {
produits = service.listProduit();
return SUCCESS;
}
public String save() {
if (!editMode)
service.ajouterProduit(produit);
else
service.miseAjourProduit(produit);
produits = service.listProduit();
return SUCCESS;
}
public String delete() {
service.supprimerProduit(ref);
produits = service.listProduit();
return SUCCESS;
}
public String edit() {
editMode = true;
produit = service.recupererProduit(ref);
service.miseAjourProduit(produit);
produits = service.listProduit();
return SUCCESS;
}
public Produit getProduit() {
return produit;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
public List<Produit> getProduits() {
return produits;
}
public void setProduits(List<Produit> produits) {
this.produits = produits;
}
public ProduitDto getProduitDto() {
return produitDto;
}
public void setProduitDto(ProduitDto produitDto) {
this.produitDto = produitDto;
}
public boolean isEditMode() {
return editMode;
}
public void setEditMode(boolean editMode) {
this.editMode = editMode;
}
#Override
public Produit getModel() {
return produit;
}
}
JSP:
<%#taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Produits</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div>
<s:form action="save" method="post">
<s:textfield label="REF" name="produit.reference"></s:textfield>
<s:textfield label="Designation" name="produit.designation"></s:textfield>
<s:textfield label="Prix" name="produit.prix"></s:textfield>
<s:textfield label="Quantite" name="produit.quantite"></s:textfield>
<s:checkbox label="Promo" name="produit.promo"></s:checkbox>
<!-- <s:textfield name="editMode"></s:textfield> permet de voir une valeur du model -->
<s:hidden name="editMode"></s:hidden>
<s:submit value="Save"></s:submit>
</s:form>
</div>
<div>
<table class="table1">
<tr>
<th>REF</th>
<th>DES</th>
<th>PRIX</th>
<th>QUANTITE</th>
<th>PROMO</th>
</tr>
<s:iterator value="produits">
<tr>
<td><s:property value="reference"/></td>
<td><s:property value="designation"/></td>
<td><s:property value="prix"/></td>
<td><s:property value="quantite"/></td>
<td><s:property value="promo"/></td>
<s:url namespace="/" action="delete" var="lien1">
<s:param name="ref">
<s:property value="reference"/>
</s:param>
</s:url>
<s:url namespace="/" action="edit" var="lien2">
<s:param name="ref">
<s:property value="reference"/>
</s:param>
</s:url>
<td><s:a href="%{lien1}">Suppr</s:a></td>
<td><s:a href="%{lien2}">Edit</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</body>
</html>
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index"></default-action-ref>
<action name="index">
<result>views/index.jsp</result>
</action>
<action name="produits" class="com.id.web.ProduitAction" method="index">
<result name="success">views/Produits.jsp</result>
</action>
<action name="save" class="com.id.web.ProduitAction" method="save">
<result name="success">views/Produits.jsp</result>
<result name="input">views/Produits.jsp</result>
</action>
<action name="delete" class="com.id.web.ProduitAction" method="delete">
<result name="success">views/Produits.jsp</result>
</action>
<action name="edit" class="com.id.web.ProduitAction" method="edit">
<result name="success">views/Produits.jsp</result>
</action>
</package>
</struts>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Interceptor product :
public class ProductCustomInterceptor implements Interceptor
{
private static final long serialVersionUID = 1L;
#Override
public String intercept(ActionInvocation invocation) throws Exception
{
System.out.println("ProductCustomInterceptor intercept() is called...");
System.out.println(invocation.getAction().getClass().getName());
return invocation.invoke();
}
}
How can I intercept all filed value of my class product when I click save button in my jsp page by using interceptor class with debugging mode browser?

ArrayList from server not being displayed on JSP

Making a web application that search and sorts through Arraylists that were made by loading the csv, reading the data and storing it in DAO. For some reason when im trying to test if the data can be retrieved and displayed on the JSP.
MajorImportersbycity.csv
"CITY-VILLE","COMPANY-ENTREPRISE","PROVINCE_ENG","PROVINCE_FRA","POSTAL_CODE-CODE_POSTAL","DATA_YEAR-ANNÉE_DES_DONNÉES"
"100 Mile House","BRAD PADDISON CONTRACTING LTD","British Columbia","Colombie-Britannique","V0K 2E0",2014
"100 Mile House","CENTRAL CHEVROLET GMC BUICK LTD.","British Columbia","Colombie-Britannique","V0K 2E0",2014
"100 Mile House","LONE BUTTE SUPPLY LTD.","British Columbia","Colombie-Britannique","V0K 2E0",2014
"100 Mile House","SARVAIR AVIATION LTD.","British Columbia","Colombie-Britannique","V0K 2E0",2014
"Abbotsford","4 SEASON KING MUSHROOMS LTD.","British Columbia","Colombie-Britannique","V4X 1C9",2014
"Abbotsford","A & P FRUIT GROWERS LTD.","British Columbia","Colombie-Britannique","V4X 2M4",2014
"Abbotsford","ABBOTSFORD CONCRETE PRODUCTS LIMITED PARTNERSHIP","British Columbia","Colombie-Britannique","V2S 7W8",2014
....
Listener.java:
public class Listener implements javax.servlet.ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent context) {
try {
LoadCsvData.importersByCity();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}
Listener calls LoadCsvData to load data from csv, parse it and store into global arraylist to be used as global arraylist(populated with the data from csv), LoadCsvData.java:
public class LoadCsvData {
public static ArrayList<Importer> importersByCanCity;
public static ArrayList<Importer> getImportersByCanCity() {
return importersByCanCity;
}
public static void setImportersByCanCity(ArrayList<Importer> importersByCity) {
importersByCanCity = importersByCity;
}
public static ArrayList<HSCode> productHSCode;
public static void importersByCity() throws FileNotFoundException{
try {
ArrayList<Importer> importersByCity = new ArrayList<Importer>();
String data;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream url = classLoader.getResourceAsStream("/MajorImportersbycity.csv");
BufferedReader csv = new BufferedReader(new InputStreamReader(url));
String line = csv.readLine();
System.out.println("before while");
while ((line = csv.readLine()) != null){
String[] importer = line.split(",");
String city = importer[0];
String companyName = importer[1];
String province_eng = importer[2];
String province_fr = importer[3];
String postal_code = importer[4];
String year = importer[5].toString();
Importer importers = new Importer(city, companyName, province_eng, province_fr, postal_code);
if (importer != null) {
//System.out.println(importer.toString() + "in while");
importersByCity.add(importers);
}
}
csv.close();
System.out.println(importersByCity.size());
setImportersByCanCity(importersByCity);
} catch (IOException f ) {
System.out.println("in catch clause");
f.printStackTrace();
}
}
}
Created a class that is used as a generic, to load the csv data into objects, Importer.java:
public class Importer {
private String city;
private String companyName;
private String province_eng;
private String province_fr;
private String postal_code;
public Importer(String city, String companyName, String province_eng, String province_fr, String postal_code) {
this.city = city;
this.companyName = companyName;
this.province_eng = province_eng;
this.province_fr = province_fr;
this.postal_code = postal_code;
}
public String getCity() {
return city;
}
private void setCity(String city) {
this.city = city;
}
public String getCompanyName() {
return companyName;
}
private void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getProvince_eng() {
return province_eng;
}
private void setProvince_eng(String province_eng) {
this.province_eng = province_eng;
}
public String getProvince_fr() {
return province_fr;
}
private void setProvince_fr(String province_fr) {
this.province_fr = province_fr;
}
public String getPostal_code() {
return postal_code;
}
public void setPostal_code(String postal_code) {
this.postal_code = postal_code;
}
#Override
public String toString(){
return "Importer [name =" + getCompanyName() + ", province=" + getProvince_eng() + " city=" + getCity() + " postal code=" + getPostal_code() + "]";
}
}
I created a test class to be a servlet to test if i can now use my loaded arraylist in my jsp, Test.java:
public class Test extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try {
System.out.println("gets to test servlet");
List<Importer> beans = LoadCsvData.getImportersByCanCity();
request.setAttribute("beans", beans);
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println(beans.size());
} catch (Throwable theException) {
System.out.println(theException);
}
}
}
My jsp loads, but it only loads the table header. The table isnt populate with the data from the CSV, index.jsp:
<%# page import="com.importersconnect.importersdata.Importer"
import="com.importersconnect.listener.LoadCsvData" language="java"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Importers Connect</title>
</head>
<body>
<h1>Importers List</h1>
<center>
<table width="100 % " id='table1' border="1" cellspacing="2"
cellpadding="2">
<tr class="tab-highlighted-2">
<td class="tab-highlighted-2" width="15">
<div align="left">city</div>
</td>
<td class="tab-highlighted-2" width="20">
<div align="left">companyName</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">province_eng</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">province_fr</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">postal_code</div>
</td>
</tr>
<c:forEach items="${beans}" var="view">
<tr>
<td><c:out value="${view.city}" /></td>
<td><c:out value="${view.companyName}" /></td>
<td><c:out value="${view.province_eng}" /></td>
<td><c:out value="${view.province_fr}" /></td>
<td><c:out value="${view.postal_code}" /></td>
</tr>
</c:forEach>
</table>
</center>
</body>
</html>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ImportConnect</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.importersconnect.listener.Listener</listener-class>
</listener>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>com.importersconnect.sort.Test</servlet-class>
</servlet>
</web-app>

How to fetch data from dynamically generated JSP page in Struts 2?

I am generating below page using Struts2. It is generating properly.
My question is how fetch the value from generated page when I click on delete button so I can further process for delete data from database and regenerate page with remaining data?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s" %>
<!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>
<h3>All Records:</h3>
<table>
<s:form action="upload">
<s:iterator value="list">
<tr>
<td ><s:property value="id"/></td>
<td ><s:property value="name"/></td>
<td><s:property value="password"/></td>
<td><s:property value="email"/></td>
<td><s:property value="gender"/></td>
<td><s:checkbox name="checked" label="isChecked" theme="simple" /></td>
</tr>
</s:iterator>
<s:submit value="delete" name="delete" />
</s:form>
</table>
</body>
</html>
RegisterAction.java
package com.javatpoint;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class RegisterAction {
private String name,password,email,gender,country;
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
public String execute(){
int i=RegisterDao.save(this);
if(i>0){
Connection con=RegisterDao.con;
try {
PreparedStatement ps=con.prepareStatement("select * from STRUTSUSER");
ResultSet rs=ps.executeQuery();
// rs = ps.getGeneratedKeys();
while(rs.next()){
User user=new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(1));
user.setPassword(rs.getString(2));
user.setEmail(rs.getString(3));
user.setGender(rs.getString(4));
list.add(user);
// System.out.println("yo");
}
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
return "error";
}
you can try something as below:
public class RegisterAction {
....
public String execute(){
...
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
Connection con=RegisterDao.con;
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from STRUTSUSER");
while (rs.next())
{
User user = new User();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("id");
deleteUser(userId);
return SUCCESS;
}
private void deleteUser(int userId)
{
Connection con=RegisterDao.con;
try
{
PreparedStatement ps = conn.prepareStatement("delete from STRUTSUSER where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
JSP page : view.jsp
<s:iterator value="list">
...
</s:iterator>
<s:hidden name="id" value="%{#list.id}" />
<s:submit value="delete" name ="delete" action="deleteUserAction"/>
In Struts.xml
<action name="deleteUserAction" class="example.RegisterAction" method="delete">
<result name="success">view.jsp</result>
</action>
After deleting user, you can call getAllUsers() from action
Hope this Helps

SelectOneMenu doesn't have any value to choose from

when I try to display employee.jsp page I am not able to select employee.
It looks like SelectOneMenu doesn't work. Am I missing something in that tag (line 20)?
I checked and the database has table employee with some employee data.
I have connection to database. I use mysql database. You can see connection to this database in persistance.xml file.
<%# page language="java" contentType="text/html;
charset=US-ASCII" pageEncoding="US-ASCII"%>
<%# taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%# taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!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>Employee Details</title>
</head>
<body>
<f:view>
<h2><center>Welcome to Employee Home Page</center></h2>
<br><br>
<h:form>
<h2>
Select an Employee Number from the drop down:
</h2>
<br><br>
<h:selectOneMenu id="selEmpNo"
valueChangeListener="#{employee.employeeReport}"
onchange="submit()">
<f:selectItem itemLabel="select" />
<f:selectItems value="#{employee.empNoList}" id="emp"/>
</h:selectOneMenu>
</h:form>
<br><br>
<h2>
<h:outputText value="Employee Name: "></h:outputText>
<h:outputText value="#{employee.empName}"/>
<br><br>
<h:outputText value="Employee Number: "/>
<h:outputText value="#{employee.empNo}"/>
<br><br>
<h:outputText value="Name of the IBU: "/>
<h:outputText value="#{employee.ibu}"/>
<br><br>
<h:outputText value="Designation: "/>
<h:outputText value="#{employee.designation}"/> </h2>
</f:view>
</body>
</html>
<%# page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%# taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!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=US-ASCII">
<title>Home</title>
</head>
<body>
<f:view>
<h2>
<center>
<h:outputLabel> Welcome!!!</h:outputLabel>
</center>
<h:outputLink value="employee.jsp">Employee Details</h:outputLink>
</h2>
</f:view>
</body>
</html>
</html>
package employee;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
public class EmployeeBean {
private String empName;
private String ibu;
private String designation;
private int empNo;
//This is used to dynamically populate the drop down with employee numbers
List<SelectItem> empNoList;
List<EmployeeEntity>empList;
public EmployeeBean(){
this.empNoList = new ArrayList<SelectItem>();
/*Populating Employee Number in the drop down - Dynamic */
empList = new EmployeeService().getEmployeeList();
Iterator<EmployeeEntity>iterator = empList.iterator();
while(iterator.hasNext()){
EmployeeEntity employee = iterator.next();
SelectItem item = new SelectItem(employee.getEmpNo());
empNoList.add(item);
}
System.out.println(empNoList);
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getIbu() {
return ibu;
}
public void setIbu(String ibu) {
this.ibu = ibu;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public List<SelectItem> getEmpNoList() {
return empNoList;
}
public void setEmpNoList(List<SelectItem> empNoList) {
this.empNoList = empNoList;
}
public List<EmployeeEntity> getEmpList() {
return empList;
}
public void setEmpList(List<EmployeeEntity> empList) {
this.empList = empList;
}
/*Eventlistener - for fetching an employee record based on the selection of employee
number from the drop down*/
public void employeeReport(ValueChangeEvent event){
int empNo = Integer.parseInt((String)event.getNewValue());
EmployeeEntity employee = new EmployeeService().getEmployee(empNo);
this.empNo = employee.getEmpNo();
this.empName = employee.getEmpName();
this.ibu = employee.getIbu();
this.designation = employee.getDesignation();
}
}
package employee;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class EmployeeEntity {
#Id
private int empNo;
private String empName;
private String ibu;
private String designation;
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getIbu() {
return ibu;
}
public void setIbu(String ibu) {
this.ibu = ibu;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
package employee;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class EmployeeService {
public List<EmployeeEntity> getEmployeeList(){
List<EmployeeEntity> empList = new ArrayList<EmployeeEntity>();
EntityManager em = null;
try{
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("Employee-
Details");
em = emf.createEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
Query query = em.createQuery("select empNo from employee ");
empList = query.getResultList();
}
catch(Exception e){
//log the exception
}
return empList;
}
public EmployeeEntity getEmployee(int empNo){
EmployeeEntity employee = new EmployeeEntity();
EntityManager em = null;
try{
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("Employee-Details");
em = emf.createEntityManager();
EntityTransaction et = em.getTransaction();
employee = em.find(EmployeeEntity.class, empNo);
}
catch(Exception e){
//log the exception
}
finally{
if( em != null){
em.clear();
}
}
return employee;
}
}
<faces-config version="1.2"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
<navigation-rule>
<display-name>Employee</display-name>
<from-view-id>/index.jsp</from-view-id>
</navigation-rule>
<managed-bean>
<managed-bean-name>employee</managed-bean-name>
<managed-bean-class>employee.EmployeeBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Generating Employee Report</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
you should add the value to the selectOneMenu, the valueChangeListener attribute accepts a method-binding expression representing a value change listener method to be notified when a new value has been set for this input component. A value change listener method must be a public method that takes a ValueChangeEvent parameter, with a return type of void. It's not the same as the value property.
Your page.
<h:selectOneMenu id="selEmpNo"
valueChangeListener="#{employee.employeeReport}"
onchange="submit()" value="#{employee.myvalue}">
<f:selectItem itemLabel="select" />
<f:selectItems value="#{employee.empNoList}" id="emp"/>
</h:selectOneMenu>
EmployeeBean
package employee;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
public class EmployeeBean {
private String myValue;
private String empName;
private String ibu;
private String designation;
public String getMyValue() {
return myValue;
}
public void setMyValue(String myValue) {
this.myValue = myValue;
}
Regards
Source here

Categories