How To Upload Image - asp.net-mvc

I am getting the following error whilst uploading a file.
The parameters dictionary contains a
null entry for parameter 'category_id'
of non-nullable type 'System.Int32'
for method
'System.Web.Mvc.ActionResult
AddProduct(Int32, System.String,
Single, System.String, System.String,
System.String, System.String,
System.String, System.String)' in
'Ecommerce.Controllers.AdminController'.
To make a parameter optional its type
should be either a reference type or a
Nullable type. Parameter name:
parameters
I am using a dialog box.
The View
<script type="text/javascript">
$(function() {
$("#dialog").dialog({
bgiframe: true,
height: 140,
modal: true,
autoOpen: false,
resizable: false
})
});
</script>
<div id="dialog" title="Upload files">
<% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<p><input type="file" id="fileUpload" name="fileUpload" size="23"/> </p>
<p><input type="submit" value="Upload file" /></p>
<% } %>
</div>
<p>
<label for="image_name">image_name:</label>
Upload File
<%= Html.ValidationMessage("image_name", "*") %>
</p>
The Controller Action
public ActionResult AddProduct(int category_id, string product_name, float product_price, string product_desc, string weight, string image_name, string img_content, string available_qty, string isFeature)
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.FileName));
string filecontent = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.ContentType));
image_name = Path.GetFileName(file.FileName);
img_content = Path.GetFileName(file.ContentType);
file.SaveAs(filePath);
}
}
AdminImplementation _adminImplementation = new AdminImplementation();
Boolean isfeature = Convert .ToBoolean(isFeature);
if (isfeature)
{
isFeature = "Featured";
}
else
{
isFeature = "NotFeatured";
}
int i = _adminImplementation.addproduct(category_id, product_name, product_price, product_desc, weight,image_name ,img_content ,available_qty ,isFeature );
ViewData["succm"] = "Product added successfully";
return View();
}
Please suggest some useful answers.
Thanks
Ritz

Looks to me like you're not providing all the parameters required for a specific ActionResult. category_id isn't being provided to AddProduct. You'd need to show us your code for us to be able to find out what's really going wrong.
How are you calling that ActionResult?

**UPLOADING IMAGE AND SAVING PATH IN THE DATABASE
________________________________________________________________________________________
<%# 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>
<div>
<h3> Choose File to Upload in Server </h3>
<form action="Recent" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</div>
</body>
</html>
____________________________________________________________________________________________
import java.sql.*;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import java.util.Hashtable;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ParameterParser;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class Recent
*/
#WebServlet("/Recent")
#MultipartConfig
public class Recent extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Recent() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Sample s1=new Sample();
final String UPLOAD_DIRECTORY = "/home/pradeep/Documents/pradeep/WebContent/Images";
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new
ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField())
{
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
String Path= "/home/pradeep/Documents/pradeep/WebContent/Images/" +name;
s1.connecting(Path);
}
}
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/Result.jsp").forward(request, response);
}
}
__________________________________________________________________________________________
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import dbconnections.Connections;
public class Sample {
Connections con=new Connections();
public void connecting(String Path)
{
Connection conn=con.Connect();
PreparedStatement pst;
String query="INSERT INTO Student1 (Path) values (?)";
try {
pst=conn.prepareStatement(query);
pst.setString(1,Path);
pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
}

Related

Set method is not called in struts2 for file input but called for other perameters

I am new to struts2. What I am trying is to get data from the client and insert into the db.But while doing this setImageFile(File fie) isnt called and thus imageFile object is null. While other set methods are called and is thus respective members contains values.
action.class
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.Map;
import javax.servlet.http.Part;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.dispatcher.SessionMap;
public class register extends ActionSupport implements SessionAware{
SessionMap<String, String> sessionMap;
private String name;
private String email;
private String dob;
private String address;
private File imageFile;
private String imageFileFileName;
private String imageFileContentType;
#Override
public void setSession(Map map)
{
sessionMap = (SessionMap)map;
sessionMap.put("", name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public File getImageFile() {
return imageFile;
}
public void setFile(File imageFile) {
this.imageFile = imageFile;
}
public void setSessionMap(SessionMap<String, String> sessionMap) {
this.sessionMap = sessionMap;
}
public String execute()
{
try
{
Class.forName("org.postgresql.Driver");
Connection conn=DriverManager.getConnection("jdbc:postgresql://localhost:5432/DemoDB", "postgres", "postgres");
InputStream imageInputStream = new FileInputStream(imageFile);
String query = "insert into userProfile('Name','Address','email','dob','img') values(?,?,?,?,?)";
Date date = Date.valueOf(dob);
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(0, name);
preparedStatement.setString(1, address);
preparedStatement.setString(2, email);
preparedStatement.setDate(3, date);
preparedStatement.setBinaryStream(4, imageInputStream, imageFile.length());
preparedStatement.execute();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return "success";
}
}
In the above code imageFile is null. And othe members contains value
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="register" namespace="/" extends="tiles-default">
<action name="register" class="com.passportseva.register">
<result name="success" type="tiles">login</result>
<result name="input" type="tiles">register</result>
<result name="error">layoutmanager.jsp</result>
</action>
</package>
</struts>
This is jsp where the action is called
registration.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="register" method="POST">
<div>
<div><h1>Name</h1></div>
<input type="text" name="name" hint="name"/>
</div>
<div>
<div><h1>Email</h1>></div>
<input type="text" name="email" hint="email"/>
</div>
<div>
<div><h1>DOB</h1></div>
<input type="date" name="dob"/>
</div>
<div>
<div><h1>Address</h1></div>
<input type="area" name="address" hint="address"/>
</div>
<div>
<s:file name="imageFile" label="image"/>
</div>
<input type="submit" value="register"/>
</form>
</body>
</html>
I used tiles here
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="login" template="/layoutmanager.jsp">
<put-attribute name="title" value="Login Page"/>
<put-attribute name="body" value="/login.jsp"/>
</definition>
<definition name="register" template="/layoutmanager.jsp">
<put-attribute name="title" value="Passport seva registration"/>
<put-attribute name="body" value="/registration.jsp"/>
</definition>
</tiles-definitions>
The output says that invalid field value for imageFile.
Use Struts Form tag with enctype attribute.
<s:form action="register" method="POST" enctype="multipart/form-data">
</s:form>

ExecAndWaitInterceptor doesn't work with Jquery ajax call

I have a working action which is using the ExecAndWait Interceptor. My wait page is
<%# page language="java" pageEncoding="UTF-8" session="false"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="2"/>"/>
</head>
<body>
<h3>Waiting</h3>
<div id="wait-result">
</div>
</body>
</html>
this is working correctly and adding a breakpoint to my action I can see that the action only gets invoked once regardless of the number of refreshes. As it should.
Now, if I remove the meta-refresh tag and replace it with a JQuery script to
reload the page, what I see is my action gets invoked for each request and the final result page never arrives.
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<script>
var repeat = false;
function executeQuery() {
$.ajax({
type: 'GET',
url: 'search',
async: false,
success: function(data) {
if ($(data).find('#wait-result')) {
repeat = true;
} else {
repeat = false;
$('#wait-result').html(data);
}
}
});
if (repeat) {
setTimeout(executeQuery, 1000);
}
}
$(document).ready(function() {
setTimeout(executeQuery, 1000);
});
</script>
</head>
<body>
<h3>Waiting</h3>
<div id="wait-result">
</div>
</body>
</html>
Is it possible to use the ExecAndWait Interceptor with a JQuery Ajax call? If so, what am I doing wrong?
Regards
EDIT
As requested here is the action
package com.harkonnen.actions.search;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.harkonnen.services.filter.ZeroResFilter;
import com.harkonnen.services.search.SearchService;
import com.harkonnen.services.search.Town;
#Component
#Scope("protototype")
#Namespace("/search")
#ParentPackage("search")
#InterceptorRefs({
#InterceptorRef(value="secureStack"),
#InterceptorRef(value="execAndWait", params={"delay", "500", "delaySleepInterval","500"}
)
})
#Results({
#Result(name="input", location="start.jsp"),
#Result(name="success", type="redirectAction", location="start" ),
#Result(name="wait", location="wait.jsp")
})
public class Search extends BaseAction {
private int x;
private int y;
private int radius;
private List<Town> towns;
#Autowired
SearchService service;
private static final Logger logger = Logger
.getLogger(Search.class.getName());
public String execute() {
try {
towns = new ZeroResFilter(service.search(x,y,radius)).filter();
System.out.println("Search Complete");
} catch (SQLException e) {
logger.error(e);
addActionError("Sorry, there was an unexpected error with your query.");
return INPUT;
}
if (towns.size() == 0) {
addActionError("There were no results found for the specified search.");
return INPUT;
}
context.setSearchX(x);
context.setSearchY(y);
context.setRadius(radius);
context.setResults(new ArrayList<Town>(towns));
context.setTowns(towns);
return SUCCESS;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
}
The base action
package com.harkonnen.actions.search;
import java.util.Map;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.harkonnen.services.SearchContext;
import com.opensymphony.xwork2.ActionSupport;
#Component
#Scope("protototype")
#Namespace("/search")
public class BaseAction extends ActionSupport implements SessionAware {
protected SearchContext context;
protected boolean isLoggedIn() {
return true;
}
#Override
public void setSession(Map<String, Object> session) {
this.context = (SearchContext) session.get("context");
}
public SearchContext getContext() {
return context;
}
}
The success jsp
<%# page language="java" pageEncoding="UTF-8" session="false"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">#import "<%=request.getContextPath()%>/resources/css/global.css";</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>HoTH Search</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
</head>
<body id="body">
<div id="container">
<div id="login">
<s:action var="login" name="login" executeResult="true"/>
</div>
<div id="perform">
<s:action var="search" name="action-prompt" executeResult="true"/>
<s:actionerror/>
</div>
<div id="results">
<s:action var="results" name="display-search-results" executeResult="true"/>
</div>
<div id="footer-wrapper">
<p>Copyright ©2015 Harkonnen Solutions.</p>
</div>
</div>
</body>
</html>
Ok, found it.
The problem was trying to parse the response to the GET request into an HTML object and then trying to run a selector.
Changing the line
if ($(data).find('#wait-result')) {
to
if (data.indexOf('#wait-result') >=0) {
fixes the problem and now everything runs as expected

How can I retrieve value from my component

I have created a form component. In that form component I also have a range component.
I was wondering how can I retrieve my value from my range component and more generally how can I interact with a component from outside it. (even if the goal is to encapsulate things)
I don't know if there are components like that somewhere but for now I just want to learn how it works. thanks !
Here is my code
index.html
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>data_generator_front</title>
</head>
<body>
<my-form></my-form>
<div class="results"></div>
<script type="application/dart" src="index.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
index.dart
import "package:angular/angular.dart";
import "package:angular/application_factory.dart";
import "package:data_generator_front/component/my_form.dart";
import "package:data_generator_front/component/range.dart";
#Injectable()
class RootContext {
String myProperty = "jeahhhhhhhh";
void method1() {
print("method1");
}
}
main() {
applicationFactory()
.rootContextType(RootContext)
.addModule(new DateFormModule())
.addModule(new RangeComponentModule())
.run();
}
my_form.html
<form>
<range name="years" value="myProp"></range>
<div>
<label>Random:</label>
<input type="checkbox" ng-model="random">
</div>
<div>
<input type="submit" value="Go !">
</div>
</form>
my_form.dart
library my_form;
import "package:angular/angular.dart";
#Component(selector: "my-form", templateUrl: "my_form.html", exportExpressions: const ["submit"])
class DateFormComponent {
#NgOneWay("random")
bool random;
submit() {
print("hello");
}
}
class DateFormModule extends Module {
DateFormModule() {
bind(DateFormComponent);
}
}
range.dart
import "package:angular/angular.dart";
#Component(selector: "range", templateUrl: "range.html")
class RangeComponent {
#NgAttr("name")
String name;
#NgOneWay("range_begin")
String range_begin;
#NgOneWay("range_end")
String range_end;
List<String> ranges = [];
addRange() {
ranges.add("$range_begin-$range_end");
range_begin = "";
range_end = "";
}
info(){
print(range_begin);
print(range_end);
print(ranges);
print(ranges.reduce((begin, item){
return begin += ",$item";
}));
}
}
class RangeComponentModule extends Module {
RangeComponentModule() {
bind(RangeComponent);
}
}
range.html
<div>
<label>{{name}}:</label>
<input type="text" placeholder="begin" size="8" ng-model="range_begin">
<input type="text" placeholder="end" size="8" ng-model="range_end">
<input type="submit" value="add" ng-click="addRange()" >
<input type="submit" value="info" ng-click="info()" >
<input type="submit" value="value" ng-click="range()" >
</div>
I guess changing NgOneWay to NgTwoWay should do the trick so the value gets updated inside the component. To get the value outside of the component bind
<range name="years" value="{{myProp}}"></range>
and create a field in your my-form component.
#NgTwoWay('myProp')
var myProp;
Alternatively you can implement ScopeAware to get the scope and then use scope.emit, scope.broadcast, scope.on... to send the data as event on submit to send it across the DOM not just to the immediate parent/child
almost :) but it's only works one way
I initialize the property in my_form.dart then the my_form.html has the value binded and finally the range component can use the value at init time.
but when I change the code inside the component the value is not binded anymore with the my_form.dart
here is the code
range.html didn't change
my_form.dart
library my_form;
import "package:angular/angular.dart";
#Component(selector: "my-form", templateUrl: "my_form.html", exportExpressions: const ["submit"])
class DateFormComponent {
#NgOneWay("random")
bool random;
#NgTwoWay("v1")
String v1 = "eee";
submit() {
print(random);
print(v1);
}
}
class DateFormModule extends Module {
DateFormModule() {
bind(DateFormComponent);
}
}
my_form.html
<form>
<range name="years" value="{{v1}}"></range>
<div>
<label>Random:</label>
<input type="checkbox" ng-model="random">
</div>
<div>
<input type="submit" value="Go !" ng-click="submit()">
</div>
</form>
range.dart
import "package:angular/angular.dart";
#Component(selector: "range", templateUrl: "range.html")
class RangeComponent {
#NgAttr("name")
String name;
#NgAttr("value")
String value;
#NgOneWay("range_begin")
String range_begin;
#NgOneWay("range_end")
String range_end;
List<String> ranges = [];
addRange() {
ranges.add("$range_begin-$range_end");
range_begin = "";
range_end = "";
value = ranges.reduce((begin, item){
return begin += ",$item";
});
}
info(){
print(range_begin);
print(range_end);
print(ranges);
print(value);
}
}
class RangeComponentModule extends Module {
RangeComponentModule() {
bind(RangeComponent);
}
}
thanks for helping anyway :)

enable disable button in jsf 2.2

I am trying simple example to enable and disable button based upon submit of form. If some one can also point me to concept of jsf:id as I am mixing plain html5 with jsf.
Below are relevant code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://java.sun.com/jsf"
xmlns:f="http://java.sun.com/jsf/core">
<head jsf:id="head">
<title>Putting it all together </title>
<!-- script jsf:target="body" jsf:name="js.js"/>
<link jsf:name="css.css" rel="stylesheet" type="text/css" /-->
</head>
<body jsf:id="body">
<form jsf:id="form" jsf:prependId="false">
<label jsf:for="name">Name </label>
<input jsf:id="name" type="text" jsf:value="#{complex.name}">
<f:ajax execute="#this" render="progress"/>
</input>
<label jsf:for="tel">Tel </label>
<input jsf:id="tel" type="tel" jsf:value="#{complex.tel}">
<f:ajax execute="#this" render="progress"/>
</input>
<label jsf:for="email">Email </label>
<input jsf:id="email" type="email" jsf:value="#{complex.email}">
<f:ajax execute="#this" render="progress"/>
</input>
<label for="progress">Progress </label>
<progress jsf:id="progress" max="3">#{complex.progress} of 3 </progress>
<input jsf:id="submit" type="submit" value="submit">
<f:ajax execute="#this" render="login" event="click" listener="#{complex.process}" />
</input>
<!-- label jsf:id="status"></label-->
<button jsf:id="login" disabled="#{complex.status}">Login</button>
</form>
</body>
</html>
The managed bean is:
package mypackage.bean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;
#ManagedBean
#SessionScoped
public class Complex implements Serializable {
public Complex() {}
private String name;
private String tel;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private boolean status;
public void process(AjaxBehaviorEvent event) {
status = !status;
}
public boolean isStatus() {
return status;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getProgress() {
int progress = 0;
if(name != null) {
progress++;
}
if(tel != null) {
progress++;
}
if(email != null) {
progress++;
}
return progress + "";
}
}
Here is error printed to web page:
HTTP Status 500 - java.lang.Boolean cannot be cast to java.lang.String
type Exception report
message java.lang.Boolean cannot be cast to java.lang.String
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.Boolean cannot be cast to java.lang.String
javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
root cause
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
com.sun.faces.renderkit.html_basic.HtmlResponseWriter.getAttributeValue(HtmlResponseWriter.java:1210)
com.sun.faces.renderkit.html_basic.HtmlResponseWriter.flushAttributes(HtmlResponseWriter.java:1170)
com.sun.faces.renderkit.html_basic.HtmlResponseWriter.closeStartIfNecessary(HtmlResponseWriter.java:1112)
com.sun.faces.renderkit.html_basic.HtmlResponseWriter.writeText(HtmlResponseWriter.java:935)
com.sun.faces.facelets.compiler.LiteralTextInstruction.write(LiteralTextInstruction.java:76)
com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:183)
javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:900)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1847)
javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:900)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1847)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1850)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1850)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:202)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.35 logs.
Apache Tomcat/7.0.35
The critical part of your code is
<button jsf:id="login" disabled="#{complex.status}">Login</button>
and then this exception
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
Now It mean for <button> tag, the value of disabled attribute is not boolean but a String.So the value of this attribute is disabled="disabled".Please see this question as well for handling the disabled attribute for HTML5
You need to set the String value from your managed bean and declare status property as a String rather than boolean.

file upload in strurts 2

i need file upload in strurts 2 and store it to server location,i used by googles no use, can anybody give better idea. advance thanks
To google, it might help to check what you type: it's "struts2", no "strurts"
Anyway, you dont need to google, the official docs are enough
http://struts.apache.org/2.2.1/docs/file-upload-interceptor.html
http://struts.apache.org/2.2.1/docs/handling-file-uploads.html
http://cwiki.apache.org/WW/file-upload.html
Here is whole code of struts2 file upload.
Action file (fileupload.java)
package com.tutorialspoint.struts2;
import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import com.opensymphony.xwork2.ActionSupport;
public class uploadFile extends ActionSupport{
private File myFile;
private String myFileContentType;
private String myFileFileName;
private String destPath;
public String execute()
{
/* Copy file to a safe location */
destPath = "C:/apache-tomcat-6.0.33/work/";
try{
System.out.println("Src File name: " + myFile);
System.out.println("Dst File name: " + myFileFileName);
File destFile = new File(destPath, myFileFileName);
FileUtils.copyFile(myFile, destFile);
}catch(IOException e){
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}
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>
<title>File Upload</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<label for="myFile">Upload your file</label>
<input type="file" name="myFile" />
<input type="submit" value="Upload"/>
</form>
</body>
</html>
success.jsp
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
You have successfully uploaded <s:property value="myFileFileName"/>
</body>
</html>
Cheers.

Resources