The requested resource is not available in struts2 File upload - java

I am new to Struts2 and am developing a web application with file upload option. Everything has been configured but when i run the module HTTP Status 404 error: The requested resource is not available. (Link: http://localhost:8080/File_Upload/index.jsp). please find below my config,
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=UTF-8">
<title>File Upload</title>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload()
{
$("#loading")
.ajaxStart(function(){
$(this).show();
})//
.ajaxComplete(function(){
$(this).hide();
});//
$.ajaxFileUpload
(
{
url:'fileUploadAction.action',//
secureuri:false,//false
fileElementId:'myFile',//id <input type="file" id="file" name="file" />
dataType: 'json',// json
success: function (data, status) //
{
//alert(data.message);//jsonmessage,messagestruts2
$("#file_name").attr("value",data.myFile);
$("#file_path").attr("value",data.myFileFileName);
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.myFile);
}
}
},
error: function (data, status, e)//
{
alert(e);
}
}
)
return false;
}
</script>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<label for="myFile">Upload your file</label>
<input type="file" name="myFile" id="myFile"/>
<input type="button" value="" onclick="return ajaxFileUpload();">
<input type="hidden" name="file_name[]" id="file_name[]" value=""/>
<input type="hidden" name="file_path[]" id="file_path[]" value=""/>
<input type="submit"/>
</form>
<div id="loading"><span style="position: fixed;left: 50%;top: 50%; transform: translate(-50%, -50%); color:#f3cbbb ">
<img src="<%=request.getContextPath()%>/images/ajax-loader.gif" alt="loading" width="200" height="200" style="padding-left:85px">
<br /><br />
<span style=" font-weight: 700; font-size: 18px">Please wait,File is being uploaded
</span></span>
</div>
</body>
</html>
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>
<package name="default" extends="struts-default">
<action name="fileUploadAction" class="com.tutorialspoint.struts2.MultipleFileUploadAction">
<result type="json" name="success">
<param name="contentType">text/html</param>
</result>
<result type="json" name="error">
<param name="contentType">text/html</param>
</result>
</action>
</package>
</struts>
Action.class:
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 MultipleFileUploadAction extends ActionSupport {
private File[] myFile;
private String[] myFileContentType;
private String[] myFileFileName;
private String destPath;
public String execute()
{
/* Copy file to a safe location */
destPath = "E:/kalidass/Upload/";
try{
for(int i=0;i<myFile.length;i++)
{
System.out.println("Src File name: " + myFile[i]);
System.out.println("Dst File name: " + myFileFileName[i]);
File destFile = new File(destPath, myFileFileName[i]);
FileUtils.copyFile(myFile[i], 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;
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<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>
jar files:
Jar files

You have to add in your struts.xml this action inside your default package
<action name="index">
<result>/index.jsp</result>
</action>
In this way when you'll try to open http://localhost/myapp/index it will return the index.jsp

Related

Etat HTTP 500 - javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection

I am new in Struts,I follow a tutorial on how to create a Struts web application. here are the files I created.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Mon application Struts de tests</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="HelloWorldForm" type="com.hello.HelloWorldFrom" />
<form-bean name="LoginForm" type="com.test.LoginForm.LoginForm"/>
</form-beans>
<action-mappings type="org.apache.struts.action.ActionMapping">
<action path="/helloWorld" type="com.hello" name="HelloWorldForm">
<forward name="success" path="/HelloWorld.jsp" />
</action>
<action path="login" parameter="" input="/index.jsp" scope="request"
name="loginForm" type="com.test.controller.LoginAction">
<forward name="succes" path="/accueil.jsp" redirect="false" />
<forward name="echec" path="/index.jsp" redirect="false" />
</action>
</action-mappings>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page language="java" %>
<%# taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%# taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%# taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html:html locale="true">
<head>
<title>authentication</title>
<html:base/>
</head>
<body bgcolor="white">
<html:form action="login" focus="nameUserr">
<table border="0" align="center">
<tr>
<td align="right">
User:
</td>
<td align="left">
<html:text property="nameUserr" size="20" maxlength="20"/>
</td>
</tr>
<tr>
<td align="right">
Password :
</td>
<td align="left">
<html:password property="psdUser" size="20" maxlength="20"
redisplay="false"/>
</td>
</tr>
<tr>
<td align="right">
<html:submit property="submit" value="Submit"/>
</td>
<td align="left">
<html:reset/>
</td>
</tr>
</table>
</html:form>
LoginAction.java
package com.test.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
import com.test.LoginForm.LoginForm;
public class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest req,
HttpServletResponse res) throws Exception {
String result = null;
String nomUtilisateur = ((LoginForm) form).getNameUser();
String mdpUtilisateur = ((LoginForm) form).getPsdUser();
if (nameUser.equals("xyz") && psdUser.equals("xyz")) {
result = "succes";
} else {
result = "failure";
}
return mapping.findForward(result);
}
}
LoginForm.java
package com.test.LoginForm;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public class LoginForm extends ActionForm{
String nameUser;
String psdUser;
public String getpsdUser() {
return psdUser;
}
public void setpsdUser(String psdUser) {
this.psdUser= psdUser;
}
public String getnameUser() {
return nameUser;
}
public void setnameUser(String nameUser) {
this.nameUser= nameUser;
}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
return errors;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.psdUser= null;
this.nameUser= null;
}
}
but when running, I got the following error
Etat HTTP 500 - javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
EDIT: the complete stack trace
Report type Exception
Message javax.servlet.ServletException: javax.servlet.jsp.JspException: Can not find ActionMappings gold ActionFormBeans collection
description The server encountered an internal error that prevented it from fulfilling the request.
exception
org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: Can not find ActionMappings gold ActionFormBeans collection
org.apache.jasper.servlet.JspServletWrapper.handleJspException (JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service (JspServletWrapper.java:455)
org.apache.jasper.servlet.JspServlet.serviceJspFile (JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service (JspServlet.java:339)
javax.servlet.http.HttpServlet.service (HttpServlet.java:727)
Parent cause
javax.servlet.ServletException: javax.servlet.jsp.JspException: Can not find ActionMappings gold ActionFormBeans collection
org.apache.jasper.runtime.PageContextImpl.doHandlePageException (PageContextImpl.java:916)
org.apache.jasper.runtime.PageContextImpl.handlePageException (PageContextImpl.java:845)
org.apache.jsp.index_jsp._jspService (index_jsp.java:112)
org.apache.jasper.runtime.HttpJspBase.service (HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service (HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service (JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile (JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service (JspServlet.java:339)
javax.servlet.http.HttpServlet.service (HttpServlet.java:727)
Parent cause
javax.servlet.jsp.JspException: Can not find ActionMappings gold ActionFormBeans collection
org.apache.struts.taglib.html.FormTag.lookup (FormTag.java:798)
org.apache.struts.taglib.html.FormTag.doStartTag (FormTag.java:506)
org.apache.jsp.index_jsp._jspx_meth_html_005fform_005f0 (index_jsp.java:189)
org.apache.jsp.index_jsp._jspx_meth_html_005fhtml_005f0 (index_jsp.java:143)
org.apache.jsp.index_jsp._jspService (index_jsp.java:99)
org.apache.jasper.runtime.HttpJspBase.service (HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service (HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service (JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile (JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service (JspServlet.java:339)
javax.servlet.http.HttpServlet.service (HttpServlet.java:727)
Note The complete trace of the mother cause of this error is available in the log files for Apache Tomcat / 7.0.59.
I googled and I tried all the solutions proposed but the error persists. Any idea Please.
P.S : I use Struts 1.1
The struts-config.xml in your file ends with </action-mappings> instead of <struts-config>
Also there are many errors in each and every file. So it seems you have not made any attempt to verify if your code is correct or not.
1) In web.xml file
There is issue with DTD declaration, it should be like :
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
2) In struts-config.xml file:
You have declared the form bean name as LoginForm where as in the action you are using it as loginForm
Also there is no forward declaration that shows what you want to do when your action class returns failure.
So the code should be like this:
<action path="/login" parameter="" input="/index.jsp" scope="request"
name="LoginForm" type="com.test.controller.LoginAction">
<forward name="succes" path="/accueil.jsp" redirect="false" />
<forward name="echec" path="/index.jsp" redirect="false" />
<forward name="failure" path="/loginFailed.jsp" redirect="false" />
</action>
3) In index.jsp you have multiple issues:
a) The taglib declaration should be like this (for Struts 1.3.10):
<%# taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="logic" %>
b) The struts html custom tag do not have any attribute called locale also the index.jsp shows that you are not closing the struts html tag.
Check this:
<html:html>
......
</html:html>
c) The property declaration:
<html:text property="nameUserr" size="20" maxlength="20"/>
says the form bean has a property called nameUserr but the LoginForm has the property declared as nameUser so change the code in the jsp file to
<html:text property="nameUser" size="20" maxlength="20"/>
4) The LoginForm bean has wrong getter and setter methods. They should be like:
public String getNameUser() {
return nameUser;
}
public void setNameUser(String nameUser) {
this.nameUser = nameUser;
}
public String getPsdUser() {
return psdUser;
}
public void setPsdUser(String psdUser) {
this.psdUser = psdUser;
}
5) Finally in LoginAction action class you the comparison is not correct, it should be:
String nomUtilisateur = ((LoginForm) form).getNameUser();
String mdpUtilisateur = ((LoginForm) form).getPsdUser();
if (nomUtilisateur.equals("xyz") && mdpUtilisateur.equals("xyz")) {
result = "succes";
} else {
result = "failure";
}

Struts 2 file upload : File object being null

I am trying to use Struts 2 file upload but it seems to me that its not working. Below is my code.
UploadAction.java:
public class UploadAction extends ActionSupport{
private File file;
private String orgFileName;
private String orgContentType;
public void setUpload(File file){
this.file=file;
}
public void setUploadContentType(String contentType){
this.orgContentType=contentType;
}
public void setUploadFileName(String fileName){
this.orgFileName=fileName;
}
#Override
public String execute(){
if(file==null)
{
System.out.println("No file....");
}
System.out.println(orgContentType);
System.out.println(orgFileName);
return SUCCESS;
}
}
struts.xml:
<constant name="struts.multipart.maxSize" value="20971520" />
<constant name="struts2.multipart.saveDir" value="C:/users/sabertooth/desktop/upload" />
<include file="example.xml"/>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="upload" class="UploadAction">
<result name="success">/example/HelloWorld.jsp</result>
</action>
</package>
I am also trying to set struts2.multipart.saveDir property as you can see above but when I read the server logs I see this line
unable to find `struts.multipart.saveDir` defaulting to `javax.servlet.dir`
Also the file object is null as no file... gets printed out on console.
I can't figure out what is wrong here.
EDIT:
fileupload.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>
<h1>upload file below</h1>
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
</body>
</html>
Apart from changing the saveDir (really not necessary, and dangerous), your are not following the conventions in the Action class: the name of an private variable must match the names of its Getters and Setters; and finally, in page you are mismatching the name by pointing to the private variable, not the setter. Change it to:
public class UploadAction extends ActionSupport{
private File upload;
private String uploadFileName;
private String uploadContentType;
public void setUpload(File upload){
this.upload=upload;
}
public void setUploadContentType(String uploadContentType){
this.uploadContentType=uploadContentType;
}
public void setUploadFileName(String uploadFileName){
this.uploadFileName=uploadFileName;
}
#Override
public String execute(){
if(upload==null)
{
System.out.println("No file....");
}
System.out.println(uploadContentType);
System.out.println(uploadFileName);
return SUCCESS;
}
}
JSP
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
Change this
<input type="file" name="file" id="uploadfile" />
to
<input type="file" name="upload" id="uploadfile" />
Your setter in your action class is setUpload so it is looking for a request parameter called upload, not file. For the sake of convention you should also change
private File file;
public void setUpload(File file){
this.file=file;
}
to
private File upload;
public void setUpload(File file){
this.upload=file;
}

404 error once I click on the submit button in this spring form project

Below are my pages, please do help.
home.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link type="text/css" rel="stylesheet" href="css/homepage.css">
<link type="text/css" rel="stylesheet" href="css/datepickerJqueryUI.css">
<script src="js/homepage.js"></script>
<script src="js/jquery.js"></script>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery.datepicker.min.js"></script>
<script>
$(function() {
$( "#datepickerDeparture" ).datepicker();
});
$(function() {
$( "#datepickerReturn" ).datepicker();
})
</script>
</head>
<body>
<div class="headerBackground">
<!-- Headers for Logo and menu items -->
<div class="header">
<div class="logo"></div>
<div class="menu">
Menu List Items
</div>
</div>
</div>
<!-- Division for items between the logo header and footer -->
<div class="body">
<!-- Division for search -->
<div class="searchBox" >
<form action="search" method="get" name="searchBus">
<div class="searchLeavingFrom">Leaving from : <input type="text" name="from" class="txtBox"><h6 id="leavingFrom" class="errorMsg"></h6></div>
<div class="searchGoingTo">Going To :<input type="text" name="destination" class="txtBox"><h6 id="destination" class="errorMsg"></h6></div>
<div class="searchDepartOn">Depart On:<input type = "text" name="departureDate" class="txtBox" id="datepickerDeparture"><h6 id="departure" class="errorMsg"></h6></div>
<div class="searchReturn">Return On:<input type = "text" name="returnDate" class="txtBox" id="datepickerReturn"></div>
<div><input type="button" name="search" value="Search Buses" class="searchBtn" onClick="validateForm()"></div>
</form>
</div>
</div>
<!-- Division for footer -->
<div>
</div>
</body>
</html>
web.xml
<web-app id="WebApp_ID" 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>TicketStore</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TicketStore</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/TicketStore-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--- my servlet mapping if we put as .jsp it doesnt run at all i mean homepage doesnt display at all-->
</servlet>
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
TicketStore-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean name="search" id="search" class="com.ticketgoose.controller.SearchDetails">
<property name="formView" value="home" />
<property name="successView" value="searchBuses" />
</bean>
<!-- Register the Customer.properties -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
SearchDetails.java
package com.ticketgoose.controller;
import com.ticketgoose.form.SearchForm;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class SearchDetails {
#RequestMapping (value = "/search", method = RequestMethod.GET)
public String addContact(#ModelAttribute("searchDetails")
SearchForm searchDetails, BindingResult result){
System.out.println("From:" + searchDetails.getFrom() +
" To:" + searchDetails.getDestination());
return "redirect:searchBus.html";
}
#RequestMapping("/searchBus")
public ModelAndView showContacts() {
return new ModelAndView("searchDetails", "command", new SearchForm());
}
}
searchBuses.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">
<html>
<head>
<title>Success Page</title>
</head>
<body>
User Details
<hr>
From : ${user.name}
To : ${user.gender}
Date of jourey: ${user.country}
Return journey: ${user.aboutYou}
</body>
</html>
This is my form:
SearchForm.java
package com.ticketgoose.form;
import java.sql.Date;
public class SearchForm {
String from;
String destination;
Date departureDate;
Date returnDate;
//getter setters
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getDestination() {
return destination;
}
public void getDestination(String Destination) {
this.destination = Destination;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}}
Please help me solve this, I couldn't figure out the problem at all.
Is you application running under an application context on the web server?
Try this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<form action="<c:url value="/search" />" method="get" name="searchBus">
The action of form say action="search" :
<form action="search" method="get" name="searchBus">
But, in your web.xml your mapping for spring is *.do :
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Change action="search" by action="search.do"
or change the mapping by ( not recommended )
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>

How to use servlets in struts2

i have a struts2 web app and I want to use a servlet in my project,but struts2's filter does not allow to call servlets
I have looked into this solution, but unfortunately it didn't work out and the problem still stands.
Any ideas?
servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.print("morteza");
OutputStream o = response.getOutputStream();
InputStream is = new FileInputStream(new File("d:/Desert.jpg"));
byte[] buf = new byte[32 * 1024];
int nRead = 0;
while( (nRead=is.read(buf)) != -1 ) {
o.write(buf, 0, nRead);
}
o.flush();
o.close();
return;
}
struts.xml:
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<constant name="struts.action.excludePattern" value="Ser"/>
</struts>
web.xml:
<servlet>
<description></description>
<display-name>Ser</display-name>
<servlet-name>Ser</servlet-name>
<servlet-class>Ser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ser</servlet-name>
<url-pattern>/Ser</url-pattern>
</servlet-mapping>
webpage:
<%# 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>
fap
<img src="Ser" height="200" width="400"/>
</body>
</html>
you can use struts2 Stream Result for display the image
public class ImageAction extends ActionSupport{
public InputStream getImage() throws FileNotFoundException{
return new FileInputStream("f://test.jpg");
}
}
<action name="getImage" class="com.project.ImageAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">Image</param>
<param name="contentDisposition">attachment;filename="image" </param>
<param name="bufferSize">1024</param>
</result>
</action>
if your project url like http://localhost:8080/project
<img src="http://localhost:8080/project/getImage" height="200" width="400"/>
or
<img src="getImage" height="200" width="400"/>

Ajax with struts

I have a problem using ajax with struts
I want to load dependent dropdown list using ajax. I am using struts2.
Below is the code for the 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>Enter Product</title>
<script type="text/javascript">
var request;
function findindex1()
{
var temp=document.getElementById("country").value;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",'temp.action?index='+temp,true);
request.send(null);
}
function showResult(){
if(request.readyState == 4){
alert(request.responseText+"1");
document.getElementById("text").innerHTML=request.responseText; //Just to test
var val=<%=request.getParameter("index") %> -
/* document.getElementById("city").flush(); */
}
alert(request.responseText+"1");
}
function change(){
var temp=document.getElementById("country").value;
location.href='loadProduct.action';
}
</script>
</head>
<body onload="fill()">
<s:form method="post" action="product.action" name="product" theme="simple">
<table id="table">
<tr><td>Country</td><td><s:select id="country" name="country.countryId" list="countryList" listKey="countryId"
listValue="name" onchange="findindex1()" ></s:select></td></tr>
<tr>
<td>City</td>
<td><s:select id="city" name="city.id" list="cities" listKey="id"
listValue="name" headerKey="city.id" ></s:select></td>
</tr>
<tr>
<td>Product Desc</td>
<td><s:textfield name="product.description"></s:textfield></td>
</tr>
<tr>
<td>Product Name</td>
<td><s:textfield name="product.name"></s:textfield></td>
</tr>
<tr>
<td><s:submit id="search" name="submit" value="Search"></s:submit></td>
<td><s:submit name="submit" value="Create"></s:submit>
</td>
</tr>
<tr>
<td></td>
<td><s:label id="text" name="text">Text to change</s:label>
</td>
</tr>
</table>
</s:form>
</body>
</html>
I have checked the code and it sets the value of the List cities in the action class on changing the value of the country dropdown in the jsp. But i am unable to reflect the changes in the jsp .
The action class function is :
public String temp()
{
String[] id=(String[])getParameters().get("index");
index=Integer.parseInt(id[0]);
cities=(ArrayList<City>)productCreateService.selectCities(Integer.parseInt(id[0]));
for(Iterator<Country> i=countryList.iterator();i.hasNext();)
{
Country c = i.next();
if(c.getCountryId()==Integer.parseInt(id[0]))
{
Country c1= countryList.get(0);
country=c;
break;
}
}
String out="";
for(Iterator<City> i=cities.iterator();i.hasNext();)
{
}
inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
return SUCCESS;
}
All the varibles have getter setters . I know the code is messed up . Initially i testes it for cities tag. When that didnt work i tried testing on a simple tag (here id="text") . But even that didnt work .
The model, Services and DAO(though not here) are all correct.
The struts.xml file is as follows .
<!-- Some or all of these can be flipped to true for debugging -->
<constant name="struts.i18n.reload" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.configuration.xml.reload" value="false" />
<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.action.extension" value="action" />
<constant name="struts.serve.static" value="true" />
<constant name="struts.serve.static.browserCache" value="false" />
<constant name="actionPackages" value="com.oxxo.pilot.web.action" />
<package name="default" extends="struts-default" namespace = "/">
<global-results>
<result name="custom_error">/jsp/exception.jsp</result>
<result name="input">/jsp/fail.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception"
result="custom_error" />
<action name="temp" class="ProductAction" method="temp">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
Could somebody please tell me what am i doing wrong. If you need any part of the code please let me know . Thanks .

Categories