Spring Security block js post query for file upload - javascript

I create application similar to https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/
But I use Spring Security and this is the reason of error (if I remove Spring Security all work correctly):
{"timestamp":"2018-08-20T09:26:44.223+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/uploadFile"}
What I have to change for avoid this problem?
FileController:
#RestController
public class FileController {
private final FileStorageService fileStorageService;
#Autowired
public FileController(FileStorageService fileStorageService) {
this.fileStorageService = fileStorageService;
}
#PostMapping("/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
String filename = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(filename)
.toUriString();
return new UploadFileResponse(
filename,
fileDownloadUri,
file.getContentType(),
file.getSize()
);
}
//...
}
upload-files.html with vanila js script that send post query:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>Spring Boot File Upload / Download Rest API Example</title>
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<div class="upload-container">
<div class="upload-header">
<h2>File Upload</h2>
</div>
<div class="upload-content">
<div class="single-upload">
<h3>Upload Single File</h3>
<form id="singleUploadForm" name="singleUploadForm">
<input id="singleFileUploadInput" type="file" name="file" class="file-input" required />
<button type="submit" class="primary submit-btn">Submit</button>
</form>
<div class="upload-response">
<div id="singleFileUploadError"></div>
<div id="singleFileUploadSuccess"></div>
</div>
</div>
</div>
</div>
</body>
<script>
'use strict';
var singleUploadForm = document.querySelector('#singleUploadForm');
var singleFileUploadInput = document.querySelector('#singleFileUploadInput');
var singleFileUploadError = document.querySelector('#singleFileUploadError');
var singleFileUploadSuccess = document.querySelector('#singleFileUploadSuccess');
function uploadSingleFile(file) {
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/uploadFile");
xhr.onload = function() {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
singleFileUploadError.style.display = "none";
singleFileUploadSuccess.innerHTML = "<p>File Uploaded Successfully.</p><p>DownloadUrl : <a href='" + response.fileDownloadUri + "' target='_blank'>" + response.fileDownloadUri + "</a></p>";
singleFileUploadSuccess.style.display = "block";
} else {
singleFileUploadSuccess.style.display = "none";
singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
xhr.send(formData);
}
singleUploadForm.addEventListener('submit', function(event){
var files = singleFileUploadInput.files;
if(files.length === 0) {
singleFileUploadError.innerHTML = "Please select a file";
singleFileUploadError.style.display = "block";
}
uploadSingleFile(files[0]);
event.preventDefault();
}, true);
</script>
</html>
UPDATE
WebSecurityConfig:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
private final CustomUserDetailsService userDetailsService;
#Autowired
public WebSecurityConfig(CustomUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(getPasswordEncoder());
}
private PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
#Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
#Override
public boolean matches(CharSequence charSequence, String encoded) {
return !encoded.equals(USER_NOT_FOUND_PASSWORD)
&& BCrypt.checkpw(charSequence.toString(), encoded);
}
};
}
}

#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
// Spring Security should completely ignore URLs starting with /resources/
.antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest()
.hasRole("USER").and()
// Possibly more configuration ...
.formLogin() // enable form based log in
// set permitAll for all URLs associated with Form Login
.permitAll();
}
You should add access persmission to url's otherwise spring security won't allow to access.

Related

Spring #RequestBody working with Postman, but a 415 with javascript from browser [duplicate]

This question already has an answer here:
Make XmlHttpRequest POST using JSON [duplicate]
(1 answer)
Closed 1 year ago.
I'm a starting web-developer and mostly done stuff with java on Spring boot. Just beginning to get familiar with javascript and right now having a problem that seems similar to many others here on stackoverflow, but the difference seems to be, that everything is working when POSTing with Postman, but when trying with browser via javascript, Il get a 415.
The
alert(JSON.stringify(task)) gives (when "taskName"="walk"): {"name":"walk"}
When the same body is POSTed with Postman, the response is:
{
"id": 65,
"name": "walk",
"new": false
}
Dependencies for jackson-databind, -core and -annotations version 2.10.1 are in use.
The javacode:
var url = contextRoot + "tasks"
var http = new XMLHttpRequest()
http.onreadystatechange = function() {
alert("readystatechange")
//if (this.readyState != 4) {
// return
//}
document.getElementById("received").innerHTML = this.responseText
}
function addTask() {
var task = {
name: document.getElementById("taskName").value
}
alert(JSON.stringify(task))
http.open("POST", url)
http.send(JSON.stringify(task))
}
My #RestController
#RestController
public class TaskController {
#Autowired
private TaskRepository taskRepository;
#GetMapping("/tasks")
public List<Task> list() {
return taskRepository.findAll();
}
#PostMapping(path = "/tasks", consumes = "application/json", produces = "application/json")
public Task create(#RequestBody Task task) {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println(task);
return taskRepository.save(task);
}
/*#PostMapping("/tasks")
public String create(#RequestBody String task) {
System.out.println("!!!!!!!!!!!!!!!!!!!!");
System.out.println(task);
return "hilipataheijjaa";
}*/
}
HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8" />
<title>Tasks</title>
</head>
<body>
<h2>Tasks</h2>
<input type="text" id="taskName"/>
<button onclick="addTask()">Add Task</button>
<p id="received">
</p>
<script th:inline="javascript"> var contextRoot = /*[[#{/}]]*/ '';</script>
<script th:src="#{/javascript/tasks.js}" defer></script>
</body>
</html>
Task.java
import javax.persistence.Entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.AbstractPersistable;
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
public class Task extends AbstractPersistable<Long> {
private String name;
}
The XMLHttpRequest.responseText:
{"timestamp":"2021-06-21T08:27:33.989+00:00","status":415,"error":"Unsupported
Media
Type","trace":"org.springframework.web.HttpMediaTypeNotSupportedException:
Content type 'text/plain;charset=UTF-8' not supported\r\n\tat
org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:227)\r\n\tat
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:422)\r\n\tat
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:367)\r\n\tat
org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.getHandlerInternal(RequestMappingInfoHandlerMapping.java:110)\r\n\tat
org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.getHandlerInternal(RequestMappingInfoHandlerMapping.java:59)\r\n\tat
org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:395)\r\n\tat
org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1234)\r\n\tat
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1016)\r\n\tat
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n\tat
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat
javax.servlet.http.HttpServlet.service(HttpServlet.java:652)\r\n\tat
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat
javax.servlet.http.HttpServlet.service(HttpServlet.java:733)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat
org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)\r\n\tat
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)\r\n\tat
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)\r\n\tat
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\r\n\tat
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\r\n\tat
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat
java.base/java.lang.Thread.run(Thread.java:834)\r\n","message":"Content
type 'text/plain;charset=UTF-8' not supported","path":"/tasks"}
Spring console:
2021-06-21 11:27:02.189 WARN 5152 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.web.HttpMediaTypeNotSupportedException: Content
type 'text/plain;charset=UTF-8' not supported] 2021-06-21 11:27:33.988
WARN 5152 --- [nio-8080-exec-5]
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.web.HttpMediaTypeNotSupportedException: Content
type 'text/plain;charset=UTF-8' not supported]
Thank You in advance!
The error is obvious. => HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/json');
You can add this and try.
Spring boot Application will return JSON format.
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
}
};

How to send an image using websockets in java?

I am trying to send an image by drag and drop in send message area but its failing to do so. I dont know how to send an image in this code. Can someone please help me out?
ChatEndpoint.java
This is serverendpoint of websocket.I have four methods.onOpen,onClose,onMessage and onError.I am not doing anything in onOpen method.This method gets called when websocket establishes the connection.When the websocket tries to send message to the client,onMessage method gets called.Here the message sent from the jsp page(client) sends it in json string format to the server.The object mapper converts it to java object.I have also made an enum for MessageType having two options LOGIN and MESSAGE.I am checking inf the java object matches with the login message type then it stores the name of chat user from properties of user obtained from session object.It also then sends the session object to join method where the session is added to the list of session object.It also send the message the user has joined the chat room.If messagetype is a message then it sends it to send message method of room class where the message is sent back to the client using sendText.
#ServerEndpoint(value = "/chat")
public class ChatEndpoint {
private Logger log = Logger.getLogger(ChatEndpoint.class.getSimpleName());
private Room room = Room.getRoom();
#OnOpen
public void onOpen(final Session session, EndpointConfig config) {}
#OnMessage
public void onMessage(final Session session, final String messageJson) {
ObjectMapper mapper = new ObjectMapper();
ChatMessage chatMessage = null;
try {
chatMessage = mapper.readValue(messageJson, ChatMessage.class);
} catch (IOException e) {
String message = "Badly formatted message";
try {
session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, message));
} catch (IOException ex) { log.severe(ex.getMessage()); }
} ;
Map<String, Object> properties = session.getUserProperties();
if (chatMessage.getMessageType() == MessageType.LOGIN) {
String name = chatMessage.getMessage();
properties.put("name", name);
room.join(session);
room.sendMessage(name + " - Joined the chat room");
}
else {
String name = (String)properties.get("name");
room.sendMessage(name + " - " + chatMessage.getMessage());
}
}
#OnClose
public void OnClose(Session session, CloseReason reason) {
room.leave(session);
room.sendMessage((String)session.getUserProperties().get("name") + " - Left the room");
}
#OnError
public void onError(Session session, Throwable ex) { log.info("Error: " + ex.getMessage()); }
}
Room.java
public class Room {
private static Room instance = null;
private List<Session> sessions = new ArrayList<Session>();
public synchronized void join(Session session) { sessions.add(session); }
public synchronized void leave(Session session) { sessions.remove(session); }
public synchronized void sendMessage(String message) {
for (Session session: sessions) {
if (session.isOpen()) {
try { session.getBasicRemote().sendText(message); }
catch (IOException e) { e.printStackTrace(); }
}
}
}
public synchronized static Room getRoom() {
if (instance == null) { instance = new Room(); }
return instance;
}
}
index.jsp
Here i am sending the wsUri which is stored in context param as ws://localhost:8080/single-room-chat/chat
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<% String WsUrl = getServletContext().getInitParameter("WsUrl"); %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name='viewport' content='minimum-scale=1.0, initial-scale=1.0,
width=device-width, maximum-scale=1.0, user-scalable=no'/>
<title>single-room-chat</title>
<link rel="stylesheet" type="text/css" href="content/styles/site.css">
<script type="text/javascript" src="scripts/chatroom.js"></script>
<script type="text/javascript">
var wsUri = '<%=WsUrl%>';
var proxy = CreateProxy(wsUri);
document.addEventListener("DOMContentLoaded", function(event) {
console.log(document.getElementById('loginPanel'));
proxy.initiate({
loginPanel: document.getElementById('loginPanel'),
msgPanel: document.getElementById('msgPanel'),
txtMsg: document.getElementById('txtMsg'),
txtLogin: document.getElementById('txtLogin'),
msgContainer: document.getElementById('msgContainer')
});
});
</script>
</head>
<body>
<div id="container">
<div id="loginPanel">
<div id="infoLabel">Type a name to join the room</div>
<div style="padding: 10px;">
<input id="txtLogin" type="text" class="loginInput"
onkeyup="proxy.login_keyup(event)" />
<button type="button" class="loginInput" onclick="proxy.login()">Login</button>
</div>
</div>
<div id="msgPanel" style="display: none">
<div id="msgContainer" style="overflow: auto;"></div>
<div id="msgController">
<textarea id="txtMsg"
title="Enter to send message"
onkeyup="proxy.sendMessage_keyup(event)"
style="height: 20px; width: 100%"></textarea>
<button style="height: 30px; width: 100px" type="button"
onclick="proxy.logout()">Logout</button>
</div>
</div>
</div>
</body>
</html>
chatroom.js
var CreateProxy = function(wsUri) {
var websocket = null;
var audio = null;
var elements = null;
var playSound = function() {
if (audio == null) {
audio = new Audio('content/sounds/beep.wav');
}
audio.play();
};
var showMsgPanel = function() {
elements.loginPanel.style.display = "none";
elements.msgPanel.style.display = "block";
elements.txtMsg.focus();
};
var hideMsgPanel = function() {
elements.loginPanel.style.display = "block";
elements.msgPanel.style.display = "none";
elements.txtLogin.focus();
};
var displayMessage = function(msg) {
if (elements.msgContainer.childNodes.length == 100) {
elements.msgContainer.removeChild(elements.msgContainer.childNodes[0]);
}
var div = document.createElement('div');
div.className = 'msgrow';
var textnode = document.createTextNode(msg);
div.appendChild(textnode);
elements.msgContainer.appendChild(div);
elements.msgContainer.scrollTop = elements.msgContainer.scrollHeight;
};
var clearMessage = function() {
elements.msgContainer.innerHTML = '';
};
return {
login: function() {
elements.txtLogin.focus();
var name = elements.txtLogin.value.trim();
if (name == '') { return; }
elements.txtLogin.value = '';
// Initiate the socket and set up the events
if (websocket == null) {
websocket = new WebSocket(wsUri);
websocket.onopen = function() {
var message = { messageType: 'LOGIN', message: name };
websocket.send(JSON.stringify(message));
};
websocket.onmessage = function(e) {
displayMessage(e.data);
showMsgPanel();
playSound();
};
websocket.onerror = function(e) {};
websocket.onclose = function(e) {
websocket = null;
clearMessage();
hideMsgPanel();
};
}
},
sendMessage: function() {
elements.txtMsg.focus();
if (websocket != null && websocket.readyState == 1) {
var input = elements.txtMsg.value.trim();
if (input == '') { return; }
elements.txtMsg.value = '';
var message = { messageType: 'MESSAGE', message: input };
// Send a message through the web-socket
websocket.send(JSON.stringify(message));
}
},
login_keyup: function(e) { if (e.keyCode == 13) { this.login(); } },
sendMessage_keyup: function(e) { if (e.keyCode == 13) { this.sendMessage(); } },
logout: function() {
if (websocket != null && websocket.readyState == 1) { websocket.close();}
},
initiate: function(e) {
elements = e;
elements.txtLogin.focus();
}
}
};

How do i read an incoming JSON from JavaScript inside a servlet in doPost()?

I'm trying to send some JSON information from a JavaScript client through XMLHttpRequest (Ajax) to a servlet in java, but i do not know the proper way of getting and decoding the data. I've seen many examples on the net, but no one seems to work. I just want to know wich method should i use like request.getParameter() and what kind of objects like JSONParser do i need. Every code or example i tried to use doesn't work, returns null in the parameters, or throws java.lang.NullPointerExceltion. The Post request arrives to the servlet because i monitorize the response, but i can't manage to acces the data. I'll post my codes. Many thanks to whoever can help me.
HTML (index.html):
<%# 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>AJAX JSON Example</title>
<script type="text/javascript" src="ajaxjsonfunctions.js"></script>
</head>
<body>
<input type="text" id="name" name="name" value="PuMa" placeholder="Name..."/>
<input type="text" id="age" name="age" value="28" placeholder="Age..."/>
<input type="text" id="country" name="country" value="Colombia" placeholder="Country..."/>
<input type="button" id="sendjsonpost" name="sendjsonpost" value="Send JSON POST" />
<hr/>
</body>
</html>
JavaScript, Ajax (ajaxjsonfunctions.js):
window.onload = function()
{
var sendjsonpost = document.getElementById("sendjsonpost");
xhr = new XMLHttpRequest();
sendjsonpost.onclick = function()
{
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var country = document.getElementById("country").value;
if (name == "" || age == "" || country == "")
alert("Debe ingresar todos los datos.");
else
enviarDatosPost(name, age, country);
}
function enviarDatosPost(name, age, country)
{
xhr.onreadystatechange = prepararRespuestaPost;
xhr.open("POST", "MessagesJSON", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var datosJSON = crearDatosJSON(name, age, country);
alert(JSON.stringify(datosJSON));
xhr.send(JSON.stringify(datosJSON));
}
function crearDatosJSON(name, age, country)
{
var datosJSON = {name : name, age : age, country : country};
return datosJSON;
}
function prepararRespuestaPost()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
alert(xhr.responseText +" --- " + xhr.statusText);
}
}
}
}
Servlet (MessagesJSON.java):
package com.puma.servlets;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.*;
import org.json.JSONObject;
import org.json.simple.*;
#WebServlet(asyncSupported = true, urlPatterns = { "/MessagesJSON" })
public class MessagesJSON extends HttpServlet
{
private static final long serialVersionUID = 1L;
public MessagesJSON()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
JSONObject jObj = new JSONObject(request.getParameter("name"));
Iterator iterKey = jObj.keys(); //gets all the keys
while(iterKey.hasNext())
{
String jsonKey = iterKey.next().toString();
String jsonValue = jObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
In order to retrieve the body of the request in the servlet, you need to call ServletRequest#getReader. In your case this would look like this:
BufferedReader reader = request.getReader();
You can then pass this Reader into the constructor of JSONTokener:
JSONTokener tokener = new JSONTokener(reader);
And finally you can parse this into a JSONObject:
JSONObject jObj = new JSONObject(tokener);

h:commandLink in jsf2 not invoking bean method and not even through javascript call

This is happenin after migrating my project to jsf2 on tomcat7. Earlier on tomcat5.5 for jsf 1 its was working fine. I have a .xhtml file from where I am trying to call a managed bean method through h:commandLink but its not being invoked. I have tried adding the EL 2.2 jars as suggetsed in other stackoverflow forums relating the same topic and also added the entries in web.xml :
<context-param>
<param-name>org.apache.myfaces.EXPRESSION_FACTORY</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
but issue is not resolved. Please help.
.xhtml file :
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:t="http://myfaces.apache.org/tomahawk">
<f:view>
<f:loadBundle var="text" basename="#{basePage.bundleName}"/>
<title>#{text['user.passwordHint']}</title>
<p>Looking up password hint for ${param.username}...</p>
<h:form id="passwordForm">
<h:inputHidden id="username" value="#{passwordHint.username}"/>
<h:commandLink action="#{passworHint.execute}" id="execute">
<f:param name="username" value="${param.username}"></f:param>
</h:commandLink>
</h:form>
<script type="text/javascript">
var f = document.forms['passwordForm'];
f.elements['passwordForm:_link_hidden_'].value='passwordForm:execute';
f.elements['username'].value='${param.username}';
f.submit();
</script>
</f:view>
</html>
Managed bean:
public class PasswordHint extends BasePage {
#ManagedProperty(value="#{param.username}")
private String username;
/* private String execute;
public String getExecute() {
return execute;
}
public void setExecute(String execute) {
this.execute = execute;
}*/
public String getUsername() {
System.out.println("get username of passwordhint-------"+username);
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String execute() {
/* FacesContext context = FacesContext.getCurrentInstance();
Map<String,String> params = context.getExternalContext().getRequestParameterMap();
System.out.println(params.get("username"));
System.out.println("Inside password hint execute-------------");
*/
// ensure that the username has been sent
if (username == null || "".equals(username)) {
log.warn("Username not specified, notifying user that it's a required field.");
addError("errors.required", getText("user.username"));
return null;
}
if (log.isDebugEnabled()) {
log.debug("Processing Password Hint...");
}
// look up the user's information
try {
User user = userManager.getUserByUsername(username);
System.out.println("username retrieved---------"+username);
StringBuffer msg = new StringBuffer();
msg.append("Your password hint is: " + user.getPasswordHint());
msg.append("\n\nLogin at: " + RequestUtil.getAppURL(getRequest()));
message.setTo(user.getEmail());
String subject = '[' + getText("webapp.name") + "] " + getText("user.passwordHint");
message.setSubject(subject);
message.setText(msg.toString());
mailEngine.send(message);
addMessage("login.passwordHint.sent",
new Object[] { username, user.getEmail() });
} catch (Exception e) {
e.printStackTrace();
System.out.println("In exception----------------");
// If exception is expected do not rethrow
//addError("login.passwordHint.error", username);
addMessage("login.passwordHint.sent", username);
}
return "success";
}
faces-config.xml:
<navigation-rule>
<from-view-id>/passwordHint.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/login.jsp</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>passwordHint</managed-bean-name>
<managed-bean-class>com.webapp.action.PasswordHint</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>username</property-name>
<value>#{param.username}</value>
</managed-property>
<managed-property>
<property-name>userManager</property-name>
<value>#{userManager}</value>
</managed-property>
<managed-property>
<property-name>mailEngine</property-name>
<value>#{mailEngine}</value>
</managed-property>
<managed-property>
<property-name>message</property-name>
<value>#{mailMessage}</value>
</managed-property>
<managed-property>
<property-name>templateName</property-name>
<value>accountCreated.vm</value>
</managed-property>
</managed-bean>
yes that's the actual code I am trying and that was a typo while copy pasting my actual code. Also the javascript error says : f.elements['passwordForm:_link_hidden_'] is null or not an object.

Unable to run show image preview on android webview?

Firstly this may sound like a duplicate question but i was unable to get any solutions via previous posted questions.I have a jsp page through which i am selecting images from PC and showing preview of that image which is working fine on chrome browser of my android phone also.But when i run it on WEBVIEW document.getElementById.click() function not working so i am unable to get image preview.
This is my JSP page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
function img_prvw(id1,id2)/*******************show preview of image*******************/
{
var oFiles = document.getElementById(id1).files;
var valid_extensions = /(.jpg|.jpeg|.png)$/i;
if(!(valid_extensions.test(document.getElementById(id1).files[0].name)))
{
document.getElementById('er').innerHTML="Select jpg or png image";
}
else
{
var reader = new FileReader();
reader.readAsDataURL(oFiles[0]);
reader.onload=
function (e) {
document.getElementById(id2).src=e.target.result;
};
}
}
</script>
</head>
<body>
<input type="file" style="display: none;" id="advrts_img" name="advrts_img" onchange="img_prvw('advrts_img','advrts_img_prvw')">
<img src="images/img_place.png" id="advrts_img_prvw" alt="" class="cursor margin_top10" style="width:100px;height:100px" onClick="document.getElementById('advrts_img').click()">
</body>
</html>
This is my android WebView code:
package com.example.sample_webview;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = (WebView) findViewById(R.id.wView);
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://minkme.org/minkmeuser/image_preview1.jsp");
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient() {
// The undocumented magic method override
// Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Chooser"),
FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg,
String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
// For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Chooser"),
MainActivity.FILECHOOSER_RESULTCODE);
}
});
setContentView(web);
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
// flipscreen not loading again
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
// To handle "Back" key press event for WebView to go back to previous
// screen.
/*
* #Override public boolean onKeyDown(int keyCode, KeyEvent event) { if
* ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) { web.goBack();
* return true; } return super.onKeyDown(keyCode, event); }
*/
}
I just want to browse images from android phone using input type="file".
in short : look over here to your input file Input file in a webview
After some time and some test, i have found that document.getElementById.click work perfectly well. i have test with the following change
test.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="jquery-1.11.1.min.js"> </script>
<script>
function img_prvw(id1,id2)/*******************show preview of image*******************/
{
console.log("Call of img_prvw");
var oFiles = document.getElementById(id1).files;
var valid_extensions = /(.jpg|.jpeg|.png)$/i;
if(!(valid_extensions.test(document.getElementById(id1).files[0].name)))
{
document.getElementById('er').innerHTML="Select jpg or png image";
}
else
{
var reader = new FileReader();
reader.readAsDataURL(oFiles[0]);
reader.onload=
function (e) {
document.getElementById(id2).src=e.target.result;
};
}
}
function onAdvrtsImgPrvwClick() {
console.log('Clickevent');
document.getElementById('advrts_img').click();
}
</script>
</head>
<body>
<input type="file" style="display: none;" id="advrts_img" name="advrts_img" onclick="console.log('click on input');" onchange="img_prvw('advrts_img','advrts_img_prvw')">
<img src="images/img_place.png" id="advrts_img_prvw" alt="" class="cursor margin_top10" style="width:100px;height:100px" onClick="onAdvrtsImgPrvwClick()">
</body>
</html>
MainActivity.java
public class MainActivity extends Activity {
private WebView mWebview;
static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebview = (WebView) findViewById(R.id.webView1);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT)
.show();
}
});
mWebview.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onConsoleMessage(ConsoleMessage cm)
{
String msg = cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId();
switch (cm.messageLevel()) {
case ERROR:
Log.e(TAG, msg);
break;
case LOG:
case TIP:
Log.i(TAG, msg);
break;
case WARNING:
Log.w(TAG, msg);
break;
case DEBUG:
default:
Log.d(TAG, msg);
break;
}
return true;
}
});
mWebview.loadUrl("file:///android_asset/test.html");
//setContentView(mWebview);
}
}
And it's appear that the console show the message 'click on input', so it have been correctly call, but it's the on change that is not called properly.

Categories