Null Pointer Exception is thrown - struts2

In my Struts Application, there is a Register form in a Jsp. The values enterd in it are then stored to mysql Db by means of an action class.
The action class (Register.java) for inserting values to mysql Db is:
package com.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.opensymphony.xwork2.ActionSupport;
public class Register extends ActionSupport {
String regname;
String regpass;
String regmail;
public String getRegname() {
return regname;
}
public void setRegname(String regname) {
this.regname = regname;
}
public String getRegpass() {
return regpass;
}
public void setRegpass(String regpass) {
this.regpass = regpass;
}
public String getRegmail() {
return regmail;
}
public void setRegmail(String regmail) {
this.regmail = regmail;
}
Connection con;
Statement st;
ResultSet rs;
public void connect(){
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay","root", "pwd");
//*.getConnection("jdbc:mysql://localhost:3307/shoppingmall","root", "vijay");
st=con.createStatement();*
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queree(){
try {
//*st.executeUpdate("insert into prodet (name,password,email) values('"+this.getRegname()+"','"+this.getRegpass()+"','"+this.getRegmail()+"');");*
st.executeUpdate("insert into prodet (name,caty) values('"+this.getRegname()+"','"+this.getRegpass()+"');");
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public String execute() throws Exception {
this.connect();
this.queree();
return SUCCESS;
}
}
The Jsp:
<s:form action="/loginns/register" cssStyle="float:right; background-color:lightgreen" method="POST">
<h5 align="center">Register here</h5> <br>
<s:textfield name="regname" label="UserName"></s:textfield>
<s:textfield name="regpass" label="Password"></s:textfield>
<s:textfield name="regmail" label="email"></s:textfield>
<s:submit align="center" value="Register"></s:submit>
</s:form>
Struts.xml:
<package name="Login" namespace="/loginns" extends="struts-default">
<action name="register" class="com.login.Register">
<result name="error">/index.jsp</result>
<result name="success">/Registered.jsp</result>
</action>
</package>
Everything works fine. On clicking the Register button, it succesfully displays the resultant page. No Exceptions are thrown.
But on Db the values are not updated. Tried in 2 Dbs but the same result. (The code in italics are for the Db in Mysql workbench 6.0) What do i miss?

You must call executeUpdate for updates and inserts, executeQuery only for selects.
http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html

Related

displaytag not working with struts 2 use tiles

In my application using struts 2 framework and tiles.
Now, I want to use displaytag to display the data in a database table. I did the following:
in my struts.xml:
<action name="users_admin" class="com.controller.admin.UserAction">
<interceptor-ref name="checkSession" />
<result name="login">/login.jsp</result>
<result type="tiles" name="none">/users_admin.tiles</result>
</action>
In file UserAction:
public class UserAction extends ActionSupport{
private List<Users> listUsers;
private String myActionName;
public String getMyActionName() {
return myActionName;
}
public void setMyActionName(String myActionName) {
this.myActionName = myActionName;
}
public List<Users> getListUsers() {
return listUsers;
}
public void setListUsers(List<Users> listUsers) {
this.listUsers = listUsers;
}
#Override
public String execute() throws Exception {
listUsers = UserServices.selectAll();
return NONE;
}
}
And In file user_admin.jsp(file use in tiles):
<s:actionerror cssStyle="color:red"/>
<div class="well">
<display:table name="listUsers" id="listUsers" requestURI="/UserAction" cellpadding="5px;"
cellspacing="5px;" style="margin-left:50px;margin-top:20px;">
<display:column property="EMAIL" title="Email"/>
<display:column property="NAME" title="Name"/>
</display:table>
</div>
File user model:
package com.model;
public class Users {
private String EMAIL;
private String NAME;
public String getEMAIL() {
return EMAIL;
}
public void setEMAIL(String EMAIL) {
this.EMAIL = EMAIL == null ? null : EMAIL.trim();
}
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME == null ? null : NAME.trim();
}
}
When I run the application error occurs in apache tomcat log
org.apache.catalina.core.ApplicationDispatcher.invoke Servlet.service() for servlet jsp threw exception
java.lang.ClassNotFoundException: org.apache.commons.collections.IteratorUtils
Who can help me point out why the error, in the solution to overcome it?
Add commons-collections-3.1.jar to your libraries.
Note that you are using only one Interceptor, unless checkSession is the name of your stack.
EDIT
Interceptor checkSession to check my log on the website. How should I use.
You can define a custom interceptor stack, and then reference it, or include your custom interceptor AND another stack (for example, the default one) for a single action, like this:
<action name="users_admin" class="com.controller.admin.UserAction">
<interceptor-ref name="checkSession" />
<interceptor-ref name="defaultStack" />
<result name="login">/login.jsp</result>
<result type="tiles" name="none">/users_admin.tiles</result>
</action>

Prepopulating form's textfields with bean default value in Struts2

In Struts 1.x , I have prepopulated the forms text fields using form bean's with default values as follows,
<html:form action="/actions/signup1">
First name: <html:text property="firstName"/><BR>
And in form bean, I have default value as follows...
public class ContactFormBean {
private String firstName = "First name";
But in Struts 2.x , when I tried with struts-tags textfield as follows, its not prepopulating the default value from the bean,
<s:form action="signup1">
<s:textfield name="formBean.firstName" label = "First Name" />
I have the formBean declared in my Action class as follows with appropriate getter and setter methods...
public class SignupAction1 extends ActionSupport {
private ContactFormBean formBean;
#Override
public String execute() throws Exception {
....
}
public ContactFormBean getFormBean(){
return formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
}
Please let me know if this can be accomplished at Request level and not at session level.
Thanks in advance.
<--Edited-->
struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="basicstruts2" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="signup">
<result>/SignUp.jsp</result>
</action>
<action name="signup1" class="coreservlets.action.SignupAction1" method="execute">
<result name="success">/SignUp-Confirmation.jsp</result>
<result name="error">/SignUp.jsp</result>
</action>
</package>
</struts>
SignUp.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sign UP</title>
</head>
<body>
<H1 ALIGN="CENTER">Sign Up</H1>
<s:form>
<s:textfield name="formBean.firstName" label = "First Name" />
<s:textfield name="formBean.lastName" label = "Last Name" />
<s:textfield name="formBean.email" label = "Email Address" />
<s:textfield name="formBean.faxNumber" label = "Fax Number" />
<s:submit action="signup1" method="loginAfterSubmit" value="Click here to Submit"/>
</s:form>
</body>
</html>
ContactFormBean.java
public class ContactFormBean {
private String firstName = "First name";
private String lastName = "Last name";
private String email = "user#host";
private String faxNumber = "xxx-yyy-zzzz";
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return(lastName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return(email);
}
public void setEmail(String email) {
this.email = email;
}
public String getFaxNumber() {
return(faxNumber);
}
public void setFaxNumber(String faxNumber) {
this.faxNumber = faxNumber;
}
public boolean isMissing(String value) {
if ((value == null) || (value.trim().equals(""))) {
return(true);
} else {
for(int i=0; i<defaultValues.length; i++) {
if (value.equals(defaultValues[i])) {
return(true);
}
}
return(false);
}
}
}
SignupAction1.java
public class SignupAction1 extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private ContactFormBean formBean;
#Override
public String execute() throws Exception {
this.formBean = new ContactFormBean();
return SUCCESS;
}
public String loginAfterSubmit() {
String firstName = formBean.getFirstName();
String lastName = formBean.getLastName();
String email = formBean.getEmail();
String faxNumber = formBean.getFaxNumber();
if (formBean.isMissing(firstName)) {
return ERROR;
} else if (formBean.isMissing(lastName)) {
return ERROR;
} else if ((formBean.isMissing(email)) ||
(email.indexOf("#") == -1)) {
return ERROR;
} else if (formBean.isMissing(faxNumber)) {
return ERROR;
} else {
return SUCCESS;
}
}
public ContactFormBean getFormBean(){
return this.formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
}
Change your signup action declaration to
<action name="signup" class="coreservlets.action.SignupAction1">
<result>/SignUp.jsp</result>
</action>
and signup1 to
<action name="signup1" class="coreservlets.action.SignupAction1" method="signup1">
create method signup1 in your SignupAction1 action class and move your logic from execute to it. In execute then create new instance of your ContactFormBean.
put your default value to the constructor:
public class ContactFormBean {
private String firstname;
public ContactFormBean (){
this.firstName = "First name";
}
}
You are returning a null formBean object with the getFormBean method,
then the constructor is never called and the attempt to acces the formBean attribute firstName is giving an error (that is not showed because it is wrapped by the Struts2 tag on the JSP.
You can
1) instantiate it on your execute method:
public String execute() throws Exception {
this.formBean = new ContactFormBean();
}
2) instantiate it lazily on your getter:
public ContactFormBean getFormBean(){
if (formBean==null)
this.formBean = new ContactFormBean();
return this.formBean;
}
EDIT (due to your comments):
I don't know how you've structured your web application;
But if you are on a JSP, an Action (and its execute() method, or another method if specified) was called BEFORE rendering the JSP.
So, regardless if you have ActionOne loading stuff and ActionTwo called after submit, or ActionOne loading stuff and another method of ActionOne called after submit, you can know if you are in a "pre-JSP" state or in a "post-submit" state...
That said, if you are exposing an Object, and you want its value or its attributes to be different from null, you have to instantiate it in one of the way described above.
Obviously, your object should contain getters and setters for its attributes, and they must have been bound to your JSP objects.
In your example, you could have:
ContactFormBean:
public class ContactFormBean {
private String firstName = "First name";
public String getFirstName(){
return this.firstName;
}
public String setFirstName(String firstName){
this.firstName = firstName;
}
}
Your Action:
public class SignupAction1 extends ActionSupport {
private ContactFormBean formBean;
public ContactFormBean getFormBean(){
return formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
#Override
public String execute() throws Exception {
/* this method is executed before showing the JSP */
/* first time initialization */
this.formBean = new ContactFormBean();
return SUCCESS;
}
public String loginAfterSubmit() throws Exception {
/* this method is executed after the submit button was pressed */
/* i don't initialize nothing here,
ContactFormBean is coming from the page */
System.out.println("ContactFormBean's firstName value is: " +
this.formBean.getFirstName());
return "goSomewhereElse";
}
}
and in Your JSP:
<s:form>
<s:textfield name="formBean.firstName" label = "First Name" />
<s:submit action="signup1" method="loginAfterSubmit" value="Press here to submit" />
</s:form>
You can do this with two Action by splitting the execute() and the loginAfterSubmit() methods into two execute() methods of two different Actions;
Then you must have your formBean in BOTH the Actions, with at least the getter in the first, and the setter in the second.
You can also set the Name value in your bean in execute method, it will populate it in your JSP page. Example is :
public String execute() throws Exception {
this.formBean = new ContactFormBean();
//Set your Name value here
formBean.setName("John Doe");
return SUCCESS;
}
Once JSP is populated you will find this value in Name text box.
Hope this will help.
Tapan

can not login when using Interceptor in struts2

I have a small application to learn Struts2 Application
I write a admin page and inside that , my code will check if user logged or not, if not it will redirect to login page.
I write interceptor to check for all pages that user try to access but not login, it will redirect this user to login page. Everything is work well, but when i enter username and password correct with database, it can not login, when i remove interceptor i can be logged into admin page
Cause maybe interceptor check session of user before and after login, but maybe some cases i dont know why my application, session get null althought my username and password is true but it till null when i set session.
My code bellow will show you what i said:
Login Action
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.dejavu.software.view;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import org.dejavu.software.dao.UserDAO;
import org.dejavu.software.model.GroupMember;
import org.dejavu.software.model.User;
/**
*
* #author Administrator
*/
public class AdminLoginAction extends ActionSupport {
private static final long serialVersionUID = -1457633455929689099L;
private User user;
private String username, password;
private String role;
private UserDAO userDAO;
private GroupMember group;
public AdminLoginAction() {
userDAO = new UserDAO();
}
#Override
public String execute() {
String result = null;
System.out.println(getUsername());
if (getUsername().length() != 0 && getPassword().length() != 0) {
setUser(userDAO.checkUsernamePassword(getUsername(), getPassword()));
if (getUser() != null) {
for (GroupMember g : getUser().getGroups()) {
boolean admincp = g.getAdminpermission().contains("1");
if (admincp == true) {
Map session = ActionContext.getContext().getSession();
session.put("userLogged", getUsername());
session.put("passwordLogged", getPassword());
result = "success";
} else {
result = "error";
}
}
}
}
return result;
}
#Override
public void validate() {
if (getUsername().length() == 0) {
addFieldError("username", "Username is required");
}
if (getPassword().length() == 0) {
addFieldError("password", getText("Password is required"));
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public GroupMember getGroup() {
return group;
}
public void setGroup(GroupMember group) {
this.group = group;
}
}
My custom interceptor Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.dejavu.software.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import java.util.Map;
import org.apache.struts2.StrutsStatics;
/**
*
* #author Anministrator
*/
public class LoginInterceptor extends AbstractInterceptor implements StrutsStatics {
private static final long serialVersionUID = -3874262922233957387L;
#Override
public void destroy() {
}
#Override
public void init() {
}
#Override
public String intercept(ActionInvocation ai) throws Exception {
Map<String, Object> session = ai.getInvocationContext().getSession();
Object user = session.get("userLogged");
if (user == null) {
return "login";
} else {
return ai.invoke();
}
}
}
my struts config
<?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>
<package name="default" namespace="/" extends="struts-default">
<action name="index" class="org.dejavu.software.view.HomeAction">
<result>home.jsp</result>
</action>
<action name="about" class="org.dejavu.software.view.AboutHomeAction">
<result>about.jsp</result>
</action>
</package>
<package name="admincp" namespace="/admincp" extends="struts-default">
<interceptors>
<interceptor name="login" class="org.dejavu.software.interceptor.LoginInterceptor" />
<interceptor-stack name="stack-with-login">
<interceptor-ref name="login"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="stack-with-login"/>
<global-results>
<result name="login">login.jsp</result>
</global-results>
<action name="logincp" class="org.dejavu.software.view.AdminLoginAction">
<result name="success">dashboard.jsp</result>
<result name="input">login.jsp</result>
<result name="error">login.jsp</result>
</action>
</package>
</struts>
When i enter correct username and password match to database it till redirect to login.jsp page
and i have no idea about that
please help me
Thank you very much
You must configure your login action to use default interceptor stack or it will NOT execute your method because your interceptor will return login result.
<action name="logincp" class="org.dejavu.software.view.AdminLoginAction">
<interceptor-ref name="defaultStack" />
<result name="success">dashboard.jsp</result>
<result name="input">login.jsp</result>
<result name="error">login.jsp</result>
</action>
you also have to check whether user is trying to log in for first time or not.
Because when user tries to log in first time, the session will always be null it will redirect to login page.
For this you can use one other parameter in your login form to check whether user is trying to log in for first time inside interceptor and if yes then invoke the action.
for example:
<form action='' method=''>
<input type='hidden' name='firstLogin' value='1'/>
<input type='text' name='username'/>
<input type='password' name='password'/>
</form>
I used plain html in this code may be you are using struts2-tags so you can implement in that way also.
And inside your Interceptor check.
request = ai.getInvocationContext().get(HTTP_REQUEST);
if(user == null)
{
if(!StringUtils.isEmpty(request.getParameter('firstLogin'))){
return ai.invoke();
}
return "login";
}
else{
return ai.invoke();
}

Uploading image in struts2

I have problem when upload image in Struts2.
I am trying to upload an image from jsp page to action class in struts2
My code is successfully run but executes up to System.out.println("2") and the image is not copied to the specified location.
Please help me to solve this problem
My Action class is below:
import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import com.opensymphony.xwork2.ActionSupport;
public class upload extends ActionSupport {
public String execute()throws Exception
{
try{
HttpServletRequest request = ServletActionContext.getRequest();
System.out.println("1");
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
System.out.println("2");
for (FileItem item : items)
{
System.out.println("3");
if (!item.isFormField()){
String fieldname = item.getFieldName();
System.out.println(fieldname);
System.out.println("4");
File file = new File("F:/www/test/Rohit/workspace_Rohit/uploadWithStruts2/WebContent/uploadimage","hi.jpg");
item.write(file);
}
}
}
catch (Exception e) {
System.out.println(e);
}
return SUCCESS;
}
}
My jsp page is:
<form action="test.action" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="upload"/>
</form>
// For upload Image in Struts2
// Jsp Page is:
<s:form method="post" action="test.action" enctype="multipart/form-data">
<s:file name="imageFile" label="User Image" />
<s:submit value="submit"></s:submit>
//Struts.xml
<struts>
<package name="default" extends="struts-default">
<action name="test" class="Test">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
//Test.java
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
public class test extends ActionSupport{
private static final long serialVersionUID = 1L;
private File imageFile;
public File getImageFile() {
return imageFile;
}
public void setImageFile(File imageFile) {
this.imageFile = imageFile;
}
public String execute()throws Exception
{
try{
//code for image random name
// start from here to
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String dt = format.format(date);
String name = "";
StringTokenizer str = new StringTokenizer(dt);
while (str.hasMoreElements())
{
String nm=(String) str.nextElement();
name+=nm;
}
String name1="";
StringTokenizer strg = new StringTokenizer(name,"/");
while (strg.hasMoreElements())
{
String nam=(String) strg.nextElement();
name1+=nam;
}
String imgname="";
StringTokenizer strge = new StringTokenizer(name1,":");
while (strge.hasMoreElements())
{
String na=(String) strge.nextElement();
imgname+=na;
}
//code for copy image to specific path
String sourceFilePath=imageFile.getAbsolutePath();
//System.out.println(sourceFilePath);
File sourceFile=new File(sourceFilePath);
File destnationFile=new File("E:/Jaydip_Baldha/workspace_new/Struts2Upload/WebContent/upload_image/"+imgname+".jpg");
FileUtils.copyFile(sourceFile, destnationFile);
}
catch(Exception e)
{
e.printStackTrace();
}
return SUCCESS;
}
}

Passing parameters to results in struts2 does not work

I have configured result as follows : Its my custom result type.
<result-types>
<result-type name="myBytesResult" class="blahblah.MyBytesResult" />
</result-types>
<action name="myAction" class="blahblah.MyAction">
<result name="success" type="myBytesResult">
<param name="pptId">${pptId}</param>
</result>
</action>
And my result has setter/getter for pptId and MyAction also has setter/getter for pptId. But when i check in my result, Its not setting pptId (I am getting ${pptId} as string in result). It seems its not getting getter from Action.
What could be reason for the same ?
The code MyAction
public String doDefault() {
System.out.println("Default Called");
setPptId("MyPpt");
return "success";
}
public byte[] getMyImageInBytes() throws Exception {
try {
//.....
} catch (Exception e) {
}
return null;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getPptId() {
return this.pptId;
}
public void setPptId(String pptId) {
this.pptId = pptId;
}
MyBytesResult
private String contentType;
private String pptId;
public void execute(ActionInvocation invocation) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
//...Some more code for settign response
System.out.println("pt Id[" + this.pptId + "]");
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getPptId() {
return pptId;
}
public void setPptId(String pptId) {
this.pptId = pptId;
}
Updated answer
So, after some digging, it appears that this is actually working properly. It is the responsibility of the Result to evaluate the incoming data as an OGNL expression if that is necessary. This is how the redirect and http header results work. You can parse the value against the stack in your custom result as follows:
String resolvedPptId = TextParseUtil.translateVariables(pptId, stack)
From the Javadoc for translateVariables:
Converts all instances of ${...}, and %{...} in expression to the value returned by a call to {#link ValueStack#findValue(java.lang.String)}. If an item cannot
be found on the stack (null is returned), then the entire variable ${...} is not
displayed, just as if the item was on the stack but returned an empty string.

Resources