I have a form for submitting credit card information data:
<g:FormPanel ui:field="creditCardForm" action="/app/create-credit-card" method="post">
<g:HTML>
<input data-braintree-name="number" value="4111111111111111"/>
<input data-braintree-name="cvv" value="100"/>
<input data-braintree-name="expiration_date" value="10/20"/>
<input data-braintree-name="postal_code" value="94107"/>
<input data-braintree-name="cardholder_name" value="John Smith"/>
</g:HTML>
</g:FormPanel>
But for some reason the SubmitCompleteHandler does not come into action when the POST is done:
this.creditCardForm.addSubmitHandler(new SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
LOGGER.fine("onSubmit()");
}
});
this.creditCardForm.addSubmitCompleteHandler(new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
LOGGER.fine("complete ..");
LOGGER.fine("Submit result: " + event.getResults());
}
});
The Servlet resturns just a String and writes some debug messages:
public class CreateCreditCardServlet extends HttpServlet implements Servlet {
private final static Logger LOGGER = Logger.getLogger(CreateCreditCardServlet.class.getName());
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { LOGGER.debug("#########################################################");
LOGGER.debug("doPost");
LOGGER.debug("#########################################################");
resp.getOutputStream().println("This is servlet response");
}
}
I see the response coming in the developer tool but why is the handler not getting called?
From the FormPanel documentation:
The back-end server is expected to respond with a content-type of
'text/html', meaning that the text returned will be treated as HTML.
If any other content-type is specified by the server, then the result
HTML sent in the onFormSubmit event will be unpredictable across
browsers, and the onSubmitComplete event may not fire at all.
So, in the servlet you need to do something like that:
resp.setContentType("text/html")
Related
i have servlet
#Component(service={Servlet.class},
property={"sling.servlet.methods=get",
"sling.servlet.resourceTypes=/content/wknd-events"})
public class MainServlet extends SlingAllMethodsServlet
{
#Reference
DemoInterfaceImpl demoInterface;
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
demoInterface.redirectUser(request,response);
}
}
demoInterface
#Component(
service= IDemoInterface.class,
immediate = true)
public class DemoInterfaceImpl implements IDemoInterface {
#Override
public void redirectUser(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws IOException {
resp.sendRedirect("/content/we-retail/us/en.html");
}
}
and i have my component
<a href="/content/wknd-events.html">
<button> go</button>
</a>
i want to redirect to /content/we-retail/us/en.html on button click but it doesn't work. I still go to /content/wknd-events.html. I don't understand where is my mistake
Your basic mistake is here "sling.servlet.resourceTypes=/content/wknd-events"})
The resourceType in Sling is the resourceType property set on the resources/nodes. So, if you register a servlet based on resourceType, it will get invoked only if you have the component or resource of that type. In your case , the servlet is registered with a content path as resourceType . Instead of sling.servlet.resourceTypes ; you can try sling.servlet.paths (e.g "sling.servlet.paths=/bin/test") and register your servlet to a path. Instead of giving a href attribute in the <a> tag, write an AJAX call on the click event of the button and give the servlet path as the URL.
$.ajax({
type: 'GET',
url:'/bin/test',
success: function(msg){
<!-- some code -->
}
});
I have problem with CRUD delete operation. When i click Delete which is written in this way in jsp file <form action="delete?Id=${medicines.id}" method="post">
<input type="submit" value="Delete">
</form>.
Here is my DeleteController(if I type something in doGet, then I get results from it, not blank page)
#WebServlet("/delete")
public class MedicinesDeleteController extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int id = Integer.parseInt(request.getParameter("Id"));
if(request.getUserPrincipal() != null) {
MedicinesService query = new MedicinesService();
query.delete(id);
response.sendRedirect(request.getContextPath() + "/");
} else {
response.sendError(403);
}
}
}
Delete function from MedicinesService(i think this is my problem)
public void delete(int id) {
DAOFactory factory = DAOFactory.getDAOFactory();
MedicinesDAO medicinesDao = factory.getMedicinesDAO();
Medicines medicines = new Medicines();
medicines.setId(id);
medicinesDao.delete(medicines);
}
And MedicinesDAOImpl
private final static String DELETE_MEDICINES =
"DELETE FROM medicines WHERE id_medicines=:id_medicines;";
#Override
public void delete(Medicines medicines) {
SqlParameterSource namedParameter = new MapSqlParameterSource("Id", medicines.getId());
template.update(DELETE_MEDICINES, namedParameter);
}
New errors
medicinesDao.delete(medicines); < MedicicinesService:41
template.update(DELETE_MEDICINES, namedParameter); < MedicinesDAOImpl:77
query.delete(id); <MedicinesDeleteController:31
Type Exception Report
Message No value supplied for the SQL parameter 'id_medicines': No value registered for key 'id_medicines'
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'id_medicines': No value registered for key 'id_medicines'
org.springframework.jdbc.core.namedparam.NamedParameterUtils.buildValueArray(NamedParameterUtils.java:355)
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.getPreparedStatementCreator(NamedParameterJdbcTemplate.java:398)
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.getPreparedStatementCreator(NamedParameterJdbcTemplate.java:370)
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:317)
pl.firstaidkit.dao.MedicinesDAOImpl.delete(MedicinesDAOImpl.java:77)
pl.firstaidkit.dao.MedicinesDAOImpl.delete(MedicinesDAOImpl.java:1)
pl.firstaidkit.service.MedicinesService.delete(MedicinesService.java:41)
pl.firstaidkit.controller.MedicinesDeleteController.doPost(MedicinesDeleteController.java:31)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
pl.firstaidkit.filter.LoginFilter.doFilter(LoginFilter.java:26)
Note The full stack trace of the root cause is available in the server logs.
Original issue was that , this would result in an http get method call and doGet() method had no code to handle the same
Delete
Second issue was with the mismatch in MapSqlParameterSource param name and place holder in query.
Since Servlet 3.0, HttpServletResponse#getHeaderNames() and HttpServletResponse#getHeaders() has been available. However, I'm using an older spec, specifically Servlet 2.4.
Having looked at the resource, How can I get the HTTP status code out of a ServletResponse in a ServletFilter?, I got an idea of how to write a wrapper. If I understand it right, I have to use setHeader() to facilitate the creation of getHeaderNames() and getHeaders(). I think I have a solid footing on how to store the headers to simulate the usage of these missing methods.
The problem is the filter which leverages this wrapper does not seem to be calling setHeader() automatically. I don't get it. I presume sincegetStatus() is working properly, I'm expecting setHeader() to behave in the same fashion. Specifically, I'm looking to print out all the response headers, after calling chain.doFilter(). I'm not sure what I'm doing wrong here. Maybe there is something wrong with how I'm storing header name-value pairs.
I would appreciate any help. Thank you.
public class ServletResponseWrapper extends HttpServletResponseWrapper {
private int httpStatus = SC_OK;
private HashMap<String, String> hashMapHeaders = new HashMap<String, String>();
public ServletResponseWrapper(HttpServletResponse response) {
super(response);
}
#Override
public void sendError(int sc) throws IOException {
httpStatus = sc;
super.sendError(sc);
}
#Override
public void sendError(int sc, String msg) throws IOException {
httpStatus = sc;
super.sendError(sc, msg);
}
#Override
public void setStatus(int sc) {
httpStatus = sc;
super.setStatus(sc);
}
public int getStatus() {
return httpStatus;
}
#Override
public void sendRedirect(String location) throws IOException {
httpStatus = SC_MOVED_TEMPORARILY;
super.sendRedirect(location);
}
#Override
public void setHeader(String name, String value) {
hashMapHeaders.put(name, value);
super.setHeader(name, value);
}
public String getHeader(String name) {
return hashMapHeaders.get(name);
}
public Enumeration<String> getHeaderNames() {
Enumeration<String> enumerationHeaderNames = Collections.enumeration(hashMapHeaders.keySet());
return enumerationHeaderNames;
}
}
public class ServletResponseWrapperFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletResponseWrapper servletResponseWrapper = new ServletResponseWrapper( (HttpServletResponse) response );
chain.doFilter( request, servletResponseWrapper );
// Process response
// This works, even though I never explicitly call the setStatus() method
int status = response.getStatus();
// This returns NULL because no header values get set; I presume setHeader() gets called implicitly
Enumeration<String> headerNames = servletResponseWrapper.getHeaderNames();
}
public void init(FilterConfig config) throws ServletException {
//empty
}
public void destroy() {
// empty
}
}
web.xml file
<display-name>Tomcat App</display-name>
<filter>
<filter-name>ResponseHeadersFilter</filter-name>
<filter-class>com.company.filters.ResponseHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ResponseHeadersFilter</filter-name>
<url-pattern>/testfilter.jsp</url-pattern>
</filter-mapping>
I took the vendor's servlet out of the equation. The filter now fires on an empty JSP file. Tomcat is also hooked to a front-end web server, IIS. I disabled IIS. Now, I'm accessing the website directly over Tomcat, via port 8080. Despite all this, I dot see any response headers.
Using Fiddler, the response headers I see are few but existing, namely:
(Cache) Date
(Entity) Content- Length, Content-Type
(Miscellaneous) Server
And status response, i.e. HTTP/1.1 200 OK
I can get by without getting response headers in the filter. But the big question I have is this is a bug with Servlet version 2.4 or is there some kind of OS Server and/or Tomcat configuration change I need to enable? Unless there's some Tomcat configuration, I'm led to believe this is likely a bug. Perhaps a clean install using the default configuration of the Tomcat version I'm using, 5.5.28, would resolve the problem, but I cannot attempt that at this time.
I am getting MalformedJSONException, unterminated object error. The content of the url passed is unquoted or relaxed json data. Parsing this content works fine when using just Gson alone but when using Retrofit, it throws the above exception after reading the contents of the URL. Is there a way to enable lenient parsing of the content?
Main Activity Class is given below
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.build();
Log.d("myinfo","endpoint built");
QuizAPI api = adapter.create(QuizAPI.class);
api.getFeed(new Callback<QuizObject>() {
#Override
public void success(QuizObject arg0, Response arg1) {
Log.d("myinfo", "success in callback");
Log.d("myinfo",arg0.getVersion());
}
#Override
public void failure(RetrofitError arg0) {
Log.d("myinfo", arg0.getLocalizedMessage());
}
});
}
protected void updateDisplay(){
output.append("updating..");
}
I can't understand the problem im having with PlayN.net. Maybe it's trivial, but since im new to web based stuff, I'm kinda stuck, so I hope someone here can enlighten me :)
My problem: I would like to acess a servlet from my game, it works, but only in java. Html gives me back an empty string.
Simple Servlet:
public class Servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter writer = response.getWriter();
writer.println("test");
writer.close();
}
}
and simple call:
PlayN.net().get("http://localhost:8080/Test", new Callback<String>() {
#Override
public void onSuccess(String result) {
System.out.println("YAY "+result);
}
#Override
public void onFailure(Throwable cause) {
System.out.println("BUH");
}
});
So like I said, java prints "YAY test", HTML prints "YAY" and I cannot figure out why.
I tried running the servlet on an other server (not localhost) but the same reaction.
Anyone an idea what I'm doing wrong?
In the browser (HTML) you have to work with the 'Same origin policy': See http://en.wikipedia.org/wiki/Same_origin_policy
Suggested solutions and work-arounds:
Collaboration from PlayN client with server
Why net().get on success return empty string