Error of Null Pointer Exception in java using struts [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to retrieve data from database but i am getting Null Pointer Exception in struts.I am using ecllipse mars.
Thanks in advance
My files are:-
web.xml
enter code here
<?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" version="3.0">
<display-name>Report2</display-name>
<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>
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>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="myapp" />
<package name="default" extends="struts-default" namespace="/">
<action name="database" class="genius.database.ReportAction"
method="execute">
<result name="Success">/ReportView.jsp</result>
</action>
</package>
</struts>
ReportAction.java
package genius.database;
import java.sql.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import genius.database.Student;
public class ReportAction{
HttpServletRequest request=null;
public String execute() throws SQLException,ClassNotFoundException {
Connection con;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/registertable?
zeroDateTimeBehavior=convertToNull","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
List<Student> li=null;
li=new ArrayList<Student>();
while(rs.next()){
Student st=new Student();
st.setRno(rs.getInt(1));
st.setName(rs.getString(2));
st.setEng(rs.getInt(3));
st.setMaths(rs.getInt(4));
li.add(st);
}
request.setAttribute("disp", li);
return "Success";
}
}
Student.java
package genius.database;
public class Student {
private int rno;
private String name;
private int eng;
private int mat;
public int getRno() {
return rno;
}
public void setRno(int rno) {
this.rno = rno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public int getMaths() {
return mat;
}
public void setMaths(int mat) {
this.mat = mat;
}
}
ReportView.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<%#page language="java" import="java.util.*" %>
<%#page language="java" import="genius.database.Student" %>
<%#page language="java" import="genius.database.ReportAction" %>
<!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>
<h2>Report</h2>
<s:actionerror key="error.Insert"/>
<s:form name="form" method="post">
<table border="1">
<thead>
<tr>
<td>Roll No</td>
<td>Name</td>
<td>Eng</td>
<td>Maths</td>
</tr>
</thead>
<tbody>
<tr>
<%
List<Student> li=(List<Student>)request.getAttribute("disp");
out.println(li);
if(li==null){
Iterator<Student> it=li.iterator();
while(it.hasNext()){
Student st=(Student)it.next();
int rno=st.getRno();
String name=st.getName();
int eng=st.getEng();
int mat=st.getMaths();
%>
<td><%out.println(rno);%></td>
<td><%out.println(name);%></td>
<td><%out.println(eng);%></td>
<td><%out.println(mat);%></td>
<% }
}
%>
</tr>
</tbody>
</table>
</s:form>
</body>
</html>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<!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>Report</title>
</head>
<body>
<s:form action="database.action">
<s:submit value="Submit"></s:submit>
</s:form>
</body>
</html>

You probably mean:
if (li!=null)
From
if(li==null){
Iterator<Student> it=li.iterator();
while(it.hasNext()){
Student st=(Student)it.next();
int rno=st.getRno();
String name=st.getName();
int eng=st.getEng();
int mat=st.getMaths();
Not sure if that's it, but that will definitely cause a NullPointerException.

Better to use JSTL rather than scriplets in you JSP
e.g.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
....
<c:forEach items="${disp}" var="student" >
${student.rno}
${student.name}
</c:forEach>
see https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm

Related

Jsp include another jsp with Struts2, but no result

I used a jsp include another jsp, but I don't get any result, only html tag content.
HelloEmp.jsp: it had iterator value with stuts2 tag.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix = "s" uri = "/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Example of List</h2>
<s:iterator value="helloList">
<s:property /><br/>
</s:iterator>
</body>
</html>
HelloAction.java: it had a string array
import java.util.ArrayList;
import java.util.List;
public class HelloAction {
private List<String> helloList = new ArrayList<String>();
public String execute() throws Exception {
helloList.add("Jacky");
helloList.add("Natali");
return "success";
}
public List<String> getHelloList() {
return helloList;
}
public void setHelloList(List<String> helloList) {
this.helloList = helloList;
}
}
employees.jsp: it included HelloEmp.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<title>Employees</title>
</head>
<body>
<p>An example of the include tag: </p>
<s:include value = "example/HelloEmp.jsp"/>
</body>
</html>
struts.xml:
<package name = "helloworld" extends = "struts-default">
<action name = "hello" class = "example.HelloAction" method = "execute">
<result name = "success">HelloEmp.jsp</result>
</action>
</package>
When I opened employees.jsp, only can see tag content in HelloEmp.jsp, I can't see the iterator value:
But if I directly open HelloEmp.jsp, I got the result:
Please help me how to fix it? thank you!
Instead of using value use page
<jsp:include page="Demo.jsp" /> might work.
Finally I use action tag instead,
<s:action name="action_name" executeResult="true"/>
that works for me!
Thank you for you guys.

Springboot. ModelAndView addObject is not replace a tag

My controller does not replace tags.
My controller has two endpoints URLs "/" and "/login"
#Controller
#RequestMapping(value={"/"})
public class Index {
#GetMapping("/")
public ModelAndView getLoginPageId() {
return new ModelAndView("login");
}
#GetMapping("/index")
public ModelAndView getLoginPageId(
#RequestParam("login") String login,
#RequestParam("password") String password
) {
ModelAndView modelAndView = new ModelAndView("index");
modelAndView.addObject("message", "123");
return modelAndView;
}
}
login.jsp
<html>
<head>
<title>login</title>
</head>
<body>
<form name="newUser" action="/index" method="get">
Login:<br>
<input type="text" name="login"><br>
Password:<br>
<input type="text" name="password"><br>
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
index.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
</head>
<body>
<h1>My message ${message}</h1>
</body>
</html>
The Chrome browser gives response
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>My Message ${message}</title>
</head>
<body>
<h1>HOA v ${message}</h1>
</body>
</html>
The ${message} is not replaced. I'm expecting ${message} should be replaced to 123.
What do I need to change?
Try to add <%# page isELIgnored="false" %> it will enable EL:
Have a look at:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<%# page isELIgnored="false" %>
<meta charset="UTF-8"/>
<title>My Message ${message}</title>
</head>
<body>
<h1>HOA v ${message}</h1>
</body>
</html>
Alternatively you could add <el-ignored>false</el-ignored> to 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_2_5.xsd" version="2.5">
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-property-group>
</web-app>

Struts2 : Action's property setter is not invoked

I try to post a simple form :
<s:form action="register">
<s:textfield name="lastname"></s:textfield>
<s:submit></s:submit>
</s:form>
The action :
public class RegisterAction extends ActionSupport {
private String lastname;
public String execute() {
System.out.println("register");
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
The action outputs the register string but the setter is never called.
Why the setter is never called ?
Even when I type directly the action in the browser http://localhost:8686/register.action?lastname=sdjh the setter is not invoked but the execute method outputs "register".
I don't see any missing parts in your code. I tried to replicate the same and I found it's working perfectly. Following is my code.
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_3_1.xsd" version="3.1">
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="register" class="com.tmp.RegisterAction">
<result>one.jsp</result>
</action>
</package>
</struts>
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!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">
</head>
<body>
<s:form action="register">
<s:textfield name="lastname"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
RegisterAction
package com.tmp;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport {
private static final long serialVersionUID = 1L;
String lastname;
public String getLastname() {
return lastname;
}
public void setLastname( String lastname ) {
this.lastname = lastname;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return Action.SUCCESS;
}
}
one.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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">
</head>
<body>
<s:property value="lastname"/>
</body>
</html>

Content-Type not allowed: fileUpload in Struts 2

I am new to Struts 2 and trying to do use fileUpload interceptor. I am attaching all my code layers
Action Class (FileUploadAction):
package com.caveofprogramming.actions;
import java.io.File;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
public String getFileUploadContentType() {
return fileUploadContentType;
}
public void setFileUploadContentType(String fileUploadContentType) {
this.fileUploadContentType = fileUploadContentType;
}
public String getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
#Action( value = "/fileUpload",
results={#Result(name="success",location="/success.jsp"),
#Result(name="error",location="/error.jsp"),
#Result(name="input",location="/error.jsp")
},
interceptorRefs={
#InterceptorRef(
params={"allowedTypes","image/jpeg,image/jpg,application/zip",
"maximumSize","1024000"},
value="fileUpload"
),
#InterceptorRef("defaultStack"),
#InterceptorRef("validation")
}
)
public String execute(){
try{
return SUCCESS;
} catch(Exception e){
return ERROR;
}
}
public String display() {
return NONE;
}
}
error.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<s:fielderror/>
</body>
</html>
Success.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Success
</body>
</html>
fileUpload.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
<body>
<h1>Struts 2 <s:file> file upload example</h1>
<s:form method="post" enctype="multipart/form-data" action="fileUpload">
<s:file label="File One" name="fileUpload" />
<s:submit />
</s:form>
</body>
</html>
I am not understanding why I am getting this error
"Content-Type not allowed: fileUpload "photography-104a.jpg" "upload_37fbf440_169b_4687_af65_93c8c967256c_00000000.tmp" image/pjpeg"
Although my uploading file format is .jpg.
You are getting this error probably because you don't allow files with content type image/pjpeg. Use parameter of fileUpload interceptor to define allowed MIME types
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/pjpeg</param>
</interceptor-ref>

Struts2 - getting 404 Resource Unavailable error from request page

I'm trying to write a login example that takes the user to a success.jsp if username equals password and an error message if it doesn't. The error message works but success (username=password) results in a 404 (HTTP Status 404 - /Struts2Ch4/success.jsp)
I experienced a similar problem in a previous post. I had not declared the RESULT parameter in the class. I was advised to use annotations in the class file and this solved the problem. In this case both the success and result parameters seem to be declared by the class so I'm not sure why I'm getting 404.
alias.jsp
<%# page language="java" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title><s:text name="app.title"/></title>
<link rel="stylesheet" href="mystyle.css" type="text/css" />
</head>
<body>
<table align="center" width="300">
<tr>
<td colspan="2"><s:actionerror/></td>
</tr>
<tr><td align="center" colspan="2">Enter Login ID and Password</td></tr>
<tr><td align="center">
<s:form action="aliasing" method="post">
<s:textfield name="uname" key="app.loginid"/>
<s:password name="pwd" key="app.password"/>
<s:submit value="Enter"/>
</s:form>
</td>
</tr>
<tr><td align="center" colspan="2">
B a c k</td>
</tr>
</table>
</body>
</html>
struts.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">
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="exception"/>
</global-exception-mappings>
<action name="aliasing" class="com.manaar.action.AliasAction">
<param name="aliases">#{ 'uname' : 'loginid','pwd' : 'password' }</param>
<interceptor-ref name="alias"/>
<interceptor-ref name="basicStack"/>
<result name="success">/success.jsp</result>
<result name="error">/alias.jsp</result>
<result name="input">/alias.jsp</result>
</action>
</package>
</struts>
AliasAction.java
package com.manaar.action;
import com.opensymphony.xwork2.ActionSupport;
public class AliasAction extends ActionSupport {
private String loginid;
private String password;
public String getLoginid() {
return loginid;
}
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute() throws Exception {
System.out.println("Login Id: "+getLoginid());
System.out.println("Password: "+getPassword());
if(loginid.equals(password))
return SUCCESS;
else{
this.addActionError(getText("app.invalid"));
return ERROR;
}
}
}
success.jsp
<%# page language="java" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title><s:text name="app.title"/></title>
<link rel="stylesheet" href="mystyle.css" type="text/css" />
</head>
<body>
<div align="center">
<h1><s:text name="app.success"/></h1>
The action has returned SUCCESS as result code.<br><br>
Back to Index</div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp
<%# page language="java" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"/>
<html>
<head><title><s:text name="app.title"/></title>
<link rel="stylesheet" href="mystyle.css" type="text/css" />
</head>
<body>
<table align="center" width=400>
<tr><td><h2>Sruts 2 Interceptors</h2></td></tr>
<tr><td><s:a href="alias.jsp">Interceptor Example 1</s:a></td></tr>
<tr><td>alias, basicStack </td></tr>
<tr><td> </td></tr>
<tr><td><s:a href="model.jsp">Interceptor Example 2</s:a></td></tr>
<tr><td>
exception, prepare, debugging, model-driven, params, conversionError, workflow
</td></tr>
<tr><td> </td></tr>
<tr><td>
<s:a href="servletAction.action">Interceptor Example 3</s:a>
</td></tr>
<tr><td>servlet-config, scoped-model-driven </td></tr>
<tr><td> </td></tr>
<tr><td><s:a href="longAction.action">Interceptor Example 4</s:a></td></tr>
<tr><td>completeStack, execAndWait</td></tr>
<tr><td> </td></tr>
<tr><td><s:a href="login.jsp">Interceptor Example 5</s:a> </td></tr>
<tr><td>basicStack, validation, workflow, scope </td></tr>
</table>
</body>
</html>

Categories

Resources