Send form data from jsp to servlet using ajax - ajax

I spent 10 years writing ASP/Ajax and MUST switch to JAVA.
I am starting very simple script so as to understand the concepts clearly before diving into more complex stuff. I am using Tomcat 7, Servlet 3
The problem is. The servlet is called successfully but the form data is not transferred
This is the edited servlet (Main.java)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Main
*/
#WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Main() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//int ids;
//String ids;
//response.setContentType("text/html;charset=UTF-8");
//PrintWriter out = response.getWriter();
String val = request.getParameter("id");
String name = request.getParameter("name");
//response.getWriter().write(val);
//response.getWriter().write("::");
//response.getWriter().write(name);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(val +" "+ name);
//System.out.print(val);
//if(val != null){
// //ids = Integer.parseInt(val);
// //out.print(ids);
// out.print(val);
//}
}
}
This is the edited JSP (Main.jsp):
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajaxSetup({ cache: false });
$(document).ready(function() {
$('#submit').click(function(event) {
var form = (event.target.form),
url = "/Main"
+ "?lName=" + escape(form.elements.lName.text)
+ "&fName=" + escape(form.elements.fName.text);
$.get(url, function(getData) {
$('#somediv').text(getData);
});
});
});
</script>
</head>
<body>
<form id="Main" action="Main" method="post">
<h4>AJAX Demo using Jquery in JSP and Servlet</h4>
Enter your Name:
<br/><input type="text" id="fName" name="fName"/>
<br/><input type="text" id="lName" name="lName"/>
<br/><input type="submit" id="submit" value="Ajax Submit"/>
<br/>
</form>
<div id="somediv">....</div>
</body>
</html>

Edit: If the form data is not transferred, that's because you are not sending it to the server. A GET request means you need lName=abc&fName=def appended to the URL:
<script>
$.ajaxSetup({ cache: false });
$(document).ready(function() {
$('#submit').click(function(event) {
var form = (event.target.form),
url = "/SomeServlet"
+ "?lName=" + escape(form.elements.lName.text)
+ "&fName=" + escape(form.elements.fName.text);
$.get(url, function(getData) {
$('#somediv').text(getData);
});
});
});
</script>

Related

Ajax radio buttons in Wicket 7

I created a Panel in which Im trying to get live Ajax behaviour to some radio options.
The problem is that I can not set the current active option, in the setter "setSelectedLang", the parameter there is always null, even when I click on different radio options. How can that be fixed?
I am running Wicket version 7.5.0.
package xx.yy.admin
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RadioChoice;
import org.apache.wicket.markup.html.panel.GenericPanel;
import org.apache.wicket.model.PropertyModel;
import xx.yy.admin.Survey;
import xx.yy.admin.AjaxListener;
import java.util.Arrays;
import java.util.List;
public class LanguageSelectionPanel extends GenericPanel<Void> {
private static final String SVENSKA = "Sve";
private static final String ENGELSKA = "Eng";
private AjaxListener listener;
private Form<Void> form;
private List<String> languages = Arrays.asList(SVENSKA, ENGELSKA);
private Survey surveyModel;
private String selectedLang = "Sve";
private RadioChoice languageRadioChoice;
public SurveyLanguageSelectionPanel(String id, Survey survey, AjaxListener listener) {
super(id);
this.surveyModel = survey;
this.listener = listener;
initialize();
}
protected void initialize() {
super.onInitialize();
form = new Form<Void>("langform") {
#Override
protected void onSubmit() {
info("Init : ");
}
};
add(form);
languageRadioChoice = getLanguageSelection();
form.add(languageRadioChoice);
}
private RadioChoice getLanguageSelection() {
RadioChoice<String> langRadioChoice = new RadioChoice<>("languages",
new PropertyModel<>(this, "selectedLang"), languages);
// Add Ajax Behaviour...
langRadioChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
listener.onUpdate(target);
}
});
return langRadioChoice;
}
public void setSelectedLang(String selectedLang) {
this.selectedLang = selectedLang;
}
public String getSelectedLang() {
return selectedLang;
}
}
The html code:
<body>
<wicket:panel>
<form style="" class="" wicket:id="langform">
<wicket:enclosure child="languages">
<span wicket:id="languages"></span>
</wicket:enclosure>
<br/>
<hr/>
</form>
</wicket:panel>
</body>
</html>
You have to use "AjaxFormChoiceComponentUpdatingBehavior" as described here:
onchange get current value with radioChoice
i.e.
langRadioChoice.add(new AjaxFormChoiceComponentUpdatingBehavior() {
protected void onUpdate(AjaxRequestTarget target) {
listener.onUpdate(target);
}
});

Spring boot websockets listener add parameter

I am implementing a chat room with webscoket by Spring boot
This is the code
ChatMessage.Class
public class ChatMessage {
private MessageType type;
private String content;
private String sender;
public enum MessageType {
CHAT,
JOIN,
LEAVE
}
public MessageType getType() {
return type;
}
public void setType(MessageType type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
}
My WebSocketConfig.Class
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/topic");
}
}
WebSocketListener.Class
#Component
public class WebSocketEventListener {
#Autowired
private SimpMessageSendingOperations messagingTemplate;
#EventListener
public void handleWebSocketConnectListener(SessionConnectedEvent event) {
System.out.println("Received a new web socket connection");
}
#EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
String username = (String) headerAccessor.getSessionAttributes().get("username");
if (username != null) {
ChatMessage chatMessage = new ChatMessage();
chatMessage.setType(ChatMessage.MessageType.LEAVE);
chatMessage.setSender(username);
messagingTemplate.convertAndSend("/topic/public", chatMessage);
}
}
}
ChatController:
#Controller
public class ChatController {
#Autowired
private SimpMessagingTemplate simpMessagingTemplate;
#MessageMapping("/chat.sendMessage/{room}")
public void sendMessage(#Payload ChatMessage chatMessage, #DestinationVariable String room) {
simpMessagingTemplate.convertAndSend("/topic/public/"+room, chatMessage);
}
#MessageMapping("/chat.addUser/{room}")
public void addUser(#Payload ChatMessage chatMessage,
SimpMessageHeaderAccessor headerAccessor, #DestinationVariable String room) {
// Add username in web socket session
headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
simpMessagingTemplate.convertAndSend("/topic/public/"+room, chatMessage);
}
}
My Index.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>Spring Boot WebSocket Chat Application</title>
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<noscript>
<h2>Sorry! Your browser doesn't support Javascript</h2>
</noscript>
<div id="username-page">
<div class="username-page-container">
<h1 class="title">Type your username</h1>
<form id="usernameForm" name="usernameForm">
<div class="form-group">
<input type="text" id="name" placeholder="Username" autocomplete="off" class="form-control" />
</div>
<div class="form-group">
<input type="text" id="room_num" placeholder="RoomNum" autocomplete="off" class="form-control"/>
</div>
<div class="form-group">
<button type="submit" class="accent username-submit">Start Chatting</button>
</div>
</form>
</div>
</div>
<div id="chat-page" class="hidden">
<div class="chat-container">
<div class="chat-header">
<h2>Spring WebSocket Chat Demo</h2>
</div>
<div class="connecting">
Connecting...
</div>
<ul id="messageArea">
</ul>
<form id="messageForm" name="messageForm">
<div class="form-group">
<div class="input-group clearfix">
<input type="text" id="message" placeholder="Type a message..." autocomplete="off" class="form-control"/>
<button type="submit" class="primary">Send</button>
</div>
</div>
</form>
</div>
</div>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="/js/main.js"></script>
</body>
</html>
main.js:
'use strict';
var usernamePage = document.querySelector('#username-page');
var chatPage = document.querySelector('#chat-page');
var usernameForm = document.querySelector('#usernameForm');
var messageForm = document.querySelector('#messageForm');
var messageInput = document.querySelector('#message');
var messageArea = document.querySelector('#messageArea');
var connectingElement = document.querySelector('.connecting');
var stompClient = null;
var username = null;
var room_num = null;
var colors = [
'#2196F3', '#32c787', '#00BCD4', '#ff5652',
'#ffc107', '#ff85af', '#FF9800', '#39bbb0'
];
function connect(event) {
username = document.querySelector('#name').value.trim();
room_num = document.querySelector('#room_num').value.trim();
if(username) {
usernamePage.classList.add('hidden');
chatPage.classList.remove('hidden');
var socket = new SockJS('/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, onConnected, onError);
}
event.preventDefault();
}
function onConnected() {
// Subscribe to the Public Topic
stompClient.subscribe('/topic/public/'+room_num, onMessageReceived);
// Tell your username to the server
stompClient.send("/app/chat.addUser/"+room_num,
{},
JSON.stringify({sender: username, type: 'JOIN'})
);
connectingElement.classList.add('hidden');
}
function onError(error) {
connectingElement.textContent = 'Could not connect to WebSocket server. Please refresh this page to try again!';
connectingElement.style.color = 'red';
}
function sendMessage(event) {
var messageContent = messageInput.value.trim();
if(messageContent && stompClient) {
var chatMessage = {
sender: username,
content: messageInput.value,
type: 'CHAT'
};
stompClient.send("/app/chat.sendMessage/"+room_num, {}, JSON.stringify(chatMessage));
messageInput.value = '';
}
event.preventDefault();
}
function onMessageReceived(payload) {
var message = JSON.parse(payload.body);
var messageElement = document.createElement('li');
if(message.type === 'JOIN') {
messageElement.classList.add('event-message');
message.content = message.sender + ' joined!';
} else if (message.type === 'LEAVE') {
messageElement.classList.add('event-message');
message.content = message.sender + ' left!';
} else {
messageElement.classList.add('chat-message');
var avatarElement = document.createElement('i');
var avatarText = document.createTextNode(message.sender[0]);
avatarElement.appendChild(avatarText);
avatarElement.style['background-color'] = getAvatarColor(message.sender);
messageElement.appendChild(avatarElement);
var usernameElement = document.createElement('span');
var usernameText = document.createTextNode(message.sender);
usernameElement.appendChild(usernameText);
messageElement.appendChild(usernameElement);
}
var textElement = document.createElement('p');
var messageText = document.createTextNode(message.content);
textElement.appendChild(messageText);
messageElement.appendChild(textElement);
messageArea.appendChild(messageElement);
messageArea.scrollTop = messageArea.scrollHeight;
}
function getAvatarColor(messageSender) {
var hash = 0;
for (var i = 0; i < messageSender.length; i++) {
hash = 31 * hash + messageSender.charCodeAt(i);
}
var index = Math.abs(hash % colors.length);
return colors[index];
}
usernameForm.addEventListener('submit', connect, true)
messageForm.addEventListener('submit', sendMessage, true)
I want to realize that multiple chat rooms exist at the same time, So i do not use the #Sendto
I define a input room_num to indicate the number of the chat room
In js file, use stompClient.send("/app/chat.sendMessage/"+room_num, {}, JSON.stringify(chatMessage)); to send message.
In Controller, use simpMessagingTemplate.convertAndSend("/topic/public/"+room, chatMessage); receive message from different chatroom
But this way of stitching url will produce a lot hard code
Is there any good alternative?
When the user leaves the chat room, handleWebSocketDisconnectListener use messagingTemplate.convertAndSend("/topic/public", chatMessage); to notify users in a same chatroom, someone leave this room,
but the url should be /topic/public/room_num.
However, this is a DisconnectListener, It will listen for all closed connections,
I want to realize that when the user leaves a chat room, only notify the users in the same chat room that the user has left

PrimeFaces invalidated component is not rerendered

PrimeFaces 6.1.
I have a SelectOneListBox with letters. Upon change, ajax event is triggered and fills PickList with words starting with selected letter. The PickList is valid if it contains the word XX, where X is the selected letter.
If the PickList is valid, everything works fine. If it gets invalidated, everything works fine (ajax is fired, messages are rerendered, etc.), only the PickList is not refreshed upon letters change, unless it is valid again.
Is there a way how to rerender the PickList, even if it not valid?
The code: Web.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head />
<h:body>
<f:view>
<h:form>
<p:selectOneListbox value="#{Web.letter}" required="true">
<f:selectItems value="#{Web.letters}" var="letter"
itemValue="#{letter}" />
<p:ajax event="change" update="words"
listener="#{Web.letterChanged}" />
</p:selectOneListbox>
<h:panelGrid columns="2" id="words">
<p:pickList id="pickList" value="#{Web.words}" var="word"
itemLabel="#{word}" itemValue="#{word}"
validator="#{Web.validateWords}" showSourceFilter="true"
filterMatchMode="startsWith" showTargetControls="true">
<p:ajax event="reorder" update="pickListMessages" />
<p:ajax event="transfer" update="pickListMessages" />
</p:pickList>
<p:message id="pickListMessages" for="pickList" />
</h:panelGrid>
</h:form>
</f:view>
</h:body>
</html>
Web.java:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.validator.ValidatorException;
import org.primefaces.model.DualListModel;
#ManagedBean (name = "Web")
#ViewScoped
#SuppressWarnings (
{ "javadoc", "nls", "unused" })
public class WebBean implements Serializable
{
private static final long serialVersionUID = 4067529596686991391L;
private Set<String> letters = new TreeSet<> (Arrays.asList ("A", "B", "C"));
private String letter = "A";
private DualListModel<String> words = new DualListModel<> (new ArrayList<> (),
new ArrayList<> ());
public Set<String> getLetters ()
{
return letters;
}
public String getLetter ()
{
return letter;
}
public void setLetter (String letter)
{
this.letter = letter;
}
public DualListModel<String> getWords ()
{
return words;
}
public void setWords (DualListModel<String> words)
{
this.words = words;
}
private void refreshWordsList ()
{
List<String> source = words.getSource ();
source.clear ();
source.addAll (Arrays.asList (letter + 'A', letter + 'B', letter + 'C'));
words.getTarget ().clear ();
}
public void letterChanged (AjaxBehaviorEvent ajaxEvent)
{
refreshWordsList ();
}
public void validateWords (FacesContext ctx, UIComponent component,
Object value) throws ValidatorException
{
#SuppressWarnings ("unchecked")
DualListModel<String> dualListModel = (DualListModel<String>) value;
List<String> validatedWords = dualListModel.getTarget ();
for (String word : validatedWords)
{
// OK?
if (word.charAt (0) == word.charAt (1))
{
return;
}
}
throw new ValidatorException (
new FacesMessage (FacesMessage.SEVERITY_ERROR, "No double", null));
}
}

How to programmatically add an AjaxBehavior to a UIComponent with primefaces

Since i've asked my last question (which still unanswered) i continued searching for a solution and lastly i found this topic which i think can help achieve what i want.
So , i tried that solution (which itself is a workaround) but it still didn't work for me.
Here is the code, it s all just a test for this issue :
the index.xhtml :
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>dyn add comps test </title>
</h:head>
<body>
<h:form id="form1">
<!-- once this first commandLink is clisked it will generate another commandlink below it -->
<h:commandLink value="cliick me">
<f:ajax event="click" listener="#{myBean.firstcmdLinkListenerHandler}"/>
</h:commandLink>
</h:form>
</body>
</html>
The managed Bean : MyBean.java
package mybeans;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlCommandLink;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.BehaviorEvent;
import org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl;
import org.primefaces.context.RequestContext;
#ManagedBean
#SessionScoped
public class MyBean {
public void handleClose(AjaxBehaviorEvent abe){
System.out.println("!!!-->>>>> the Ajax Behaviour Works !!!!! ");
}
public void reLoadCityList( BehaviorEvent event ){
System.out.println("!!!-->>>>> the reLoadCityList method Works !!!!! ");
}
public void firstcmdLinkListenerHandler(AjaxBehaviorEvent abe){
System.out.println("firstcmdLinkListenerHandleris running ! ");
FacesContext fc = FacesContext.getCurrentInstance();
Application application = fc.getApplication();
ExpressionFactory ef = fc.getApplication().getExpressionFactory();
UIComponent form1 = fc.getViewRoot().findComponent("form1");
if(form1!=null){
//Creating the commandLink
HtmlCommandLink mynewcmdlink = (HtmlCommandLink)application.createComponent(HtmlCommandLink.COMPONENT_TYPE);
mynewcmdlink.setId("mynewcmdlink");
mynewcmdlink.setValue("clickme2!!");
MyAjaxBehavior pajax = new MyAjaxBehavior();
Class[] par = new Class[1];
par[0] = BehaviorEvent.class;
//par[0] = AjaxBehaviorEvent.class; (*)
//pajax.setListener( myCreateMetExpression( "reLoadCityList", true, //void.class, par ) );
//i tried with both AjaxBehaviorEvent and BehaviorEvent as in (*)
//MethodExpression me = ef.createMethodExpression( //fc.getELContext(), "#{myBean.handleClose}", void.class, par);
MethodExpression me = ef.createMethodExpression( fc.getELContext(), "#{myBean.reLoadCityList}", void.class, par);
//pajax.setListener(me); //i've tried with this too but it wasn't sucesseful
pajax.addAjaxBehaviorListener( new AjaxBehaviorListenerImpl( me ) );
pajax.setProcess( "#this" );
mynewcmdlink.addClientBehavior( "change", pajax );
//adding thecommanLink to the form
form1.getChildren().add(mynewcmdlink);
//Refreshing the form to see the added commandLink :
RequestContext context = RequestContext.getCurrentInstance();
context.update("form1");
context.update("form1:foo");
}else
System.out.println("form1 is null!!");
}
and the MyAjaxBehavior.java used as the workaround in the primefaces forum article:
package mybeans;
import java.util.HashMap;
import javax.el.ELContext;
import javax.el.MethodExpression;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.BehaviorEvent;
import org.primefaces.component.behavior.ajax.AjaxBehavior;
public class MyAjaxBehavior extends AjaxBehavior {
#Override
public Object saveState(FacesContext context) {
HashMap<String, Object> map;
map = new HashMap<String, Object>();
map.put("update", getUpdate());
map.put("process", getProcess());
map.put("oncomplete", getOncomplete());
map.put("onerror", getOnerror());
map.put("onsuccess", getOnsuccess());
map.put("onstart", getOnstart());
map.put("listener", getListener());
if (initialStateMarked())
return null;
return UIComponentBase.saveAttachedState(context, map);
}
#SuppressWarnings("unchecked")
#Override
public void restoreState(FacesContext context, Object state) {
if (state != null) {
HashMap<String, Object> map;
map = (HashMap<String, Object>) UIComponentBase
.restoreAttachedState(context, state);
setUpdate((String) map.get("update"));
setProcess((String) map.get("process"));
setOncomplete((String) map.get("oncomplete"));
setOnerror((String) map.get("onerror"));
setOnsuccess((String) map.get("onsuccess"));
setOnstart((String) map.get("onstart"));
setListener((MethodExpression) map.get("listener"));
}
}
#Override
public void broadcast(BehaviorEvent event) throws AbortProcessingException {
ELContext eLContext = FacesContext.getCurrentInstance().getELContext();
// Backward compatible implementation of listener invocation
if (getListener() != null) {
try {
getListener().invoke(eLContext, new Object[] { event });
} catch (IllegalArgumentException exception) {
getListener().invoke(eLContext, new Object[0]);
}
}
}
}
Do something like this
Panel tp = new Panel();
FacesContext fc = FacesContext.getCurrentInstance();
ExpressionFactory ef = fc.getApplication().getExpressionFactory();
MethodExpression me = ef.createMethodExpression(fc.getELContext(), "#{myView.closeIt}", null, new Class<?>[]{BehaviorEvent.class});
AjaxBehavior ajaxBehavior = (AjaxBehavior) fc.getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
ajaxBehavior.setProcess("#this");
ajaxBehavior.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(me, me));
tp.addClientBehavior("close", ajaxBehavior);
component.getChildren().add(tp);
myView.closeIt()
public void closeIt(CloseEvent ce){
Panel p = (Panel) ce.getComponent();
System.out.println("Do what ever you want");
}

upload images in the database

I have been trying to upload an image into the table but no joy at all.
I have used a store procedure and encrypted my connection strings in the appsettings and use data layer to access the objects.
string FilePath = FileUpload1.PostedFile.FileName;
string FileName = Path.GetFileName(FilePath);
string ext = Path.GetExtension(FileName);
string ContentType = string.Empty;
switch (ext)
{
case ".jpg":
ContentType = "Image/jpg";
break;
case ".png":
ContentType = "Image/png";
break;
case ".gif":
ContentType = "Image/gif";
break;
}
if (ContentType != string.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
SqlCommand _SqlCom = new SqlCommand("sp_InsFoto");
_SqlCom.Parameters.Add("#imgName", SqlDbType.VarChar).Value = FileName;
_SqlCom.Parameters.Add("#Imgdata", SqlDbType.Binary).Value =bytes;
_SqlCom.Parameters.Add("#imgContentType", SqlDbType.VarChar).Value =ContentType;
obj.ExecuteNonQuery(ref _SqlCom);
And I have the store procedure as stated below
CREATE PROCEDURE [dbo].[sp_InsFoto]
(
#ImgName varchar(50)
,#ImgData varbinary(MAX)
,#ImgContentType varchar(50)
)
AS INSERT INTO tbl_Fotos
(
ImgName
,ImgData
,ImgContentType
)
VALUES
(
#ImgName
,#ImgData
,#ImgContentType
)
**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
}
}
Name of parameters in your code should exactly match names defined in stored procedure, so in the code below change #imgName to #ImgName and #imgContentType to #ImgContentType:
SqlCommand _SqlCom = new SqlCommand("sp_InsFoto");
_SqlCom.Parameters.Add("#imgName", SqlDbType.VarChar).Value = FileName;
_SqlCom.Parameters.Add("#Imgdata", SqlDbType.Binary).Value =bytes;
_SqlCom.Parameters.Add("#imgContentType", SqlDbType.VarChar).Value =ContentType;
obj.ExecuteNonQuery(ref _SqlCom);

Resources