ExecAndWaitInterceptor doesn't work with Jquery ajax call - struts2

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

Related

Could not find 'ShowToastr' ('ShowToastr' was undefined). Blazor

I get this error: Could not find 'ShowToastr' ('ShowToastr' was undefined).
I am creating a Blazor app with .NET6.
This is the page:
#page "/hotel/rooms"
#inject ILocalStorageService localStorage
#inject IJSRuntime jsRuntime
#inject IHotelRoomService hotelRoomService
<h3>HotelRooms</h3>
#code {
private HomeViewModel HomeModel { get; set; } = new HomeViewModel();
public IEnumerable<HotelRoomDto> Rooms { get; set; } = new List<HotelRoomDto>();
protected override async Task OnInitializedAsync()
{
try
{
if (await localStorage.GetItemAsync<HomeViewModel>(SD.Local_InitialBooking) != null)
{
HomeModel = await localStorage.GetItemAsync<HomeViewModel>(SD.Local_InitialBooking);
}
else
{
HomeModel.NumberOfNights = 1;
}
await LoadRooms();
}
catch (Exception ex)
{
await jsRuntime.ToastrError(ex.Message);
}
}
common.js :
window.ShowToastr = (type, message) => {
if (type === "success") {
toastr.success(message, "Operation Successful")
}
if (type === "error") {
toastr.error(message, "Operation Failed")
}
}
I have two references on ToastrError :
public static class IJSRuntimeExtension
{
public static async ValueTask ToastrSuccess(this IJSRuntime JSRuntime, string message)
{
await JSRuntime.InvokeVoidAsync("ShowToastr", "success", message);
}
public static async ValueTask ToastrError(this IJSRuntime JSRuntime, string message)
{
await JSRuntime.InvokeVoidAsync("ShowToastr", "error", message);
}
}
While debugging HotelRooms.razor the whole try block passes, the LoadRooms(the method is entered) and after that the debugger enters the catch block where I get this error.
This is the index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>HiddenVilla_Client</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="HiddenVilla_Client.styles.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet" />
</head>
<body>
<div id="app">
<div style="position:fixed;top:50%;left:50%;margin-top:-50px;margin-left:-100px;">
<img src="images/ajax-loader.gif" />
</div>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" integrity="sha512-VEd+nq25CkR676O+pLBnDW09R7VQX9Mdiij052gVCp5yVH3jGtH70Ho/UUv4mJDsEdTvqRCFZg0NKGiojGnUCw==" crossorigin="anonymous"></script>
<script src="https://js.stripe.com/v3/" defer></script>
<script src="js/common.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
Please move ShowToastr to OnAfterRender event, this is the event when UI is fully ready and accessible.
In index.html "you already have it"
link the toastr cdns
In your common.js
function toastrSuccess(message){
toastr.success(message);
}
function toastrError(message){
toastr.error(message);
}
your component
#page "/hotel/rooms"
#inject ILocalStorageService localStorage
#inject IJSRuntime jsRuntime
#inject IHotelRoomService hotelRoomService
<h3>HotelRooms</h3>
#code {
private HomeViewModel HomeModel { get; set; } = new HomeViewModel();
public IEnumerable<HotelRoomDto> Rooms { get; set; } = new List<HotelRoomDto>();
protected override async Task OnInitializedAsync()
{
try
{
if (await localStorage.GetItemAsync<HomeViewModel>(SD.Local_InitialBooking) != null)
{
HomeModel = await localStorage.GetItemAsync<HomeViewModel>(SD.Local_InitialBooking);
}
else
{
HomeModel.NumberOfNights = 1;
}
await LoadRooms();
//example of using toastr success
await jsRuntime.InvokeVoidAsync("toastrSuccess","what ever you want in success toastr");
}
catch (Exception ex)
{
await jsRuntime.InvokeVoidAsync("toastrError",ex.Message);
}
}
References

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 :)

Adding dynamic WebComponent divs

I'm trying to dynamically add a number of divs using Dart. The divs contain a custom web component, and I'm trying to pass in a variable. I want to be able to specify n number of variables, pass them to n number of components, and insert those into an HTML document. What's happening, however, is I'm getting the inserted divs without the variables. I wonder if this is a case of Dart trying to pass something into a an already loaded DOM and therefore doing nothing...? Here's some code:
product_elem.dart:
import 'package:web_ui/web_ui.dart';
import 'dart:html';
class ProductComponent extends WebComponent {
var productId;
}
product_elem.html:
<!DOCTYPE html>
<html>
<body>
<element name="product-elem" constructor="ProductComponent" extends="div">
<template>
<div style="width:335px;margin:10px;">
<h3>
{{productId}}
</h3>
</div>
</template>
<script type="application/dart" src="product_elem.dart"></script>
</element>
</body>
</html>
testcase_component.dart:
import 'dart:html';
import 'package:web_ui/web_ui.dart';
var productId;
void main() {
List myList = new List();
myList.addAll(["Foo", "Bar", "Baz"]);
for (var i = 0; i < myList.length; i++) {
productId = myList[i];
query('#products').innerHtml +=
"<div is='product-elem' id='product_elem' product-id='{{productId}}'></div>";
}
}
testcase_component.html:
<!DOCTYPE html>
<html>
<head>
<link rel="import" href="product_elem.html">
</head>
<body>
<div id="products">
<!-- Insert dynamic divs here -->
</div>
<script type="application/dart" src="testcase_component.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
You can't just add WebComponents like that. WebUI doesn't know that anything was added, so you just end up with a normal div.
Here is the current (slightly messy) way to dynamically add WebComponents:
void main() {
List myList = new List();
myList.addAll(["Foo", "Bar", "Baz"]);
for (var i = 0; i < myList.length; i++) {
productId = myList[i];
var product = new ProductComponent(productId);
product.host = new DivElement();
var lifecycleCaller = new ComponentItem(product)..create();
query('#products').append(product.host);
lifecycleCaller.insert();
}
}
This way the proper WebUI lifecycles are called.
Also make sure to add a constructor for ProductElem so that productId can be externally set:
class ProductComponent extends WebComponent {
var productId;
ProductComponent(this.productId);
}

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.

How To Upload Image

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
}
}

Resources