Where to put Java Simple Captcha Builder? - java

I am a newbie at java/java servlet. I need the simpleCaptcha for a form, using html and javaservlet for the code. With reference to http://simplecaptcha.sourceforge.net/extending.html.
Captcha captcha = new Captcha.Builder(200, 50)
.addText()
.addBackground()
.addNoise()
.gimp()
.addBorder()
.build(); // Required.
Where (java servlet) should I put this piece of code in order to create the captcha on html?
Thank you very much.

To extend SimpleCaptcha and customize your CAPTCHA, my understanding is that you'll have to create your own HttpServlet (maybe extends SimpleCaptchaServlet). To do so, I suggest to download the source code and to look at SimpleCaptchaServlet or StickyCaptchaServlet. This is what the doGet() method of SimpleCaptchaServlet looks like:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Captcha captcha = new Captcha.Builder(_width, _height)
.addText()
.addBackground(new GradiatedBackgroundProducer())
.gimp()
.addNoise()
.addBorder()
.build();
CaptchaServletUtil.writeImage(resp, captcha.getImage());
req.getSession().setAttribute(NAME, captcha);
}
This should be self-explaining: create your own servlet and put your custom Captcha Builder code in the doGet() method. Then, follow the instructions of the Installing section but, instead of using one of their servlet, declare yours in the web.xml. Finally, package/deploy your application. An example is bundled in the source distribution under examples. Check it out if you need more guidance about the structure, the dependencies and the packaging of your web application.

hey have you had a look at this page yet?
http://simplecaptcha.sourceforge.net/installing.html
this is about as straight forward as it gets I think. This project gives you a few Capcha servlets out of the box. You just have to map them in your web.xml file. You can follow along and create the jsp that will call them.

Related

Redirect correctly to a JSP inside WEB-INF

I am a but stuck and confused over this. I have all my .JSP files inside WEB-INF/pages/ and want to access them.
I have done a requestDispatcher on /forward/* like this
#WebServlet("/forward/*")
public class ForwardController extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/WEB-INF" + req.getPathInfo()).forward(req, resp);
}
}
This works great and I can access my JSP files using /forward/pages/index.jsp, though, what I have read so should this not be accessable for the user, but now it clearly is. Is this done in the right way?
Also, now that we've redirect to that link, http://localhost/forward/pages/index.jsp
and want to logout, i use a button to /logout, but now the link before follows along like this, http://localhost/forward/pages/logout
How can I overcome these 2 things?
Best regards
As said the jsp pages inside WEB-INF can only be accessible through controller so whenever you need to access any jsp from another jsp then you need to route through controller. If you want to access jsp to jsp then those should be outside WEB-INF

Using session to send params to a Liferay Portlet

I need to make a Servlet which will manage some information and, after that, will go to a Liferay 6.2 Portlet. Both in the same server.
I need the Servlet to send a parameter, but I don't want to send it GET, but POST method. So, I try to put it in the session to retrieve it from the Portlet.
At the Servlet, I have:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
request.getSession().setAttribute("param1", "TEST 1");
url = "http://myServer/";
response.sendRedirect(response.encodeRedirectURL(url));
} catch (Exception e) {
e.printStackTrace();
}
}
And at the Portlet I manage the information at render method, as I want to get param1 before I render the page:
public void render (RenderRequest renderRequest, RenderResponse renderResponse)
throws PortletException, IOException {
super.render(renderRequest, renderResponse);
//Try to retrieve from getOriginalServletRequest
HttpServletRequest servletReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest));
String param1 = servletReq.getSession().getAttribute("param1").toString();
//Try to retrieve from getHttpServletRequest
HttpServletRequest servletReq_ = PortalUtil.getHttpServletRequest(renderRequest);
String param1_ = servletReq_.getSession().getAttribute("param1").toString();
}
As you can see, I tried to retrieve from getHttpServletRequest and from getOriginalServletRequest, but I always get the param1 null.
Any suggestion?
Thank you in advance!
Update question:
I'm being called from a third part, and I'm receiving a GET parameter I want to evaluate.
After that, and not rendering a page in the middle, I want to redirect to one or another Portlet, depending of that evaluation.
I need to send some personal information to those Portlets, so I want to send some parameters in POST method.
A Servlet doesn't fit as doesn't share session with Portlets.
I've tried to implement a landing Portlet, but the redirect can only be done in action phase, so I'd need to render a (empty) page before the redirect, don't like that part. Render phase doesn't allow redirect (even getting PortalUtil.getHttpServletResponse(), doesn't work)
Any suggestion? Thanks!
A servlet and a portlet will not share the same session. The portlet is living within the portal server, e.g. Liferay. The servlet is typically in its own web application, thus completely separated by design.
If you need to communicate between the two, here are two possible solutions/workarounds:
reimplement your servlet as a portlet, potentially utilizing the resource-phase of a portlet
use a request parameter instead of a session attribute
Edit after all of the comments:
It seems best to take a step back and look at the underlying problem - what is the problem that you're actually trying to solve? The content of your question is how you're trying to solve it, and obviously there are challenges. It looks like the problem needs a different solution in the first place.
My answer describes why your solution can't work, but that obviously doesn't help solving the underlying problem.

Disable servlet at build/package/deploy, enable at run-time?

Lets say I have a simple "Hello world" type servlet, configured with the annotation #WebServlet("/hello").
I want to disable it for build/deployment, so it will not be possible to "call" the servlet. How would I do that?
Then, through a configuration file, I want to be able to enable the servlet at run-time, so it can be used by a client. How would I do that?
Is either of these possible?
You can't enable servlets during runtime via standard API. It can at most only be enabled during build time in web.xml or during deploy time by ServletContext#addServlet(). Your best bet is to always enable it and control it on a per-request basis. You can use a servlet filter for this.
First give the servlet a name.
#WebServlet(urlPatterns="/hello", name="yourServlet")
public class YourServlet extends HttpServlet {
// ...
}
So that you can easily map a filter directly to it without worrying about servlet's URL patterns.
#WebFilter(servletNames="yourServlet")
public class YourFilter implements Filter {
// ...
}
In your filter, just decide whether to continue the chain, or to return a 404 based on your configuration file setting.
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (isYourConfigurationFileSettingSet()) {
chain.doFilter(request, response);
} else {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
The isYourConfigurationFileSettingSet() part can't be answered in detail based on the information provided so far. In case you actually also couldn't figure out that, then head to Where to place and how to read configuration resource files in servlet based application?
Instead of defining the servlet through an annotation, do it in the web.xml file. Different versions of this file may allow you to have the servlets enabled or not.
The version of web.xml to use should be selected at build and deployment time. Maybe by a Maven profile or similar. Take a look at the following link for some ideas on that: https://maven.apache.org/guides/mini/guide-building-for-different-environments.html
If you want truly run-time control, then you may have to do a little custom coding. A filter (or, I suppose, the servlet itself) could check the value of a property and return a response with an HTTP error code (I suppose 403 would be vaguely appropriate; 404 less so, but if you want it to appear as though the servlet didn't exist in that configuration, it would work...)

Spring MVC webapp link to excel document and rename it

I have a question about whether or not something is possible. I have a spring mvc webapp that will have a button that links to an external website which returns an Excel document. The name of the excel document returned is rubbish and I would like to rename the document as it comes in before the user is prompted to save.
Is this possible using spring mvc. I'm on a really old version. The version compatible with Java 1.4.2.
So far I'm thinking that I'll extend org.springframework.web.servlet.mvc.AbstractController, override handleRequestInternal and then do something like this....
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
urlBuilder.setServerName(batchServerName);
urlBuilder.setPort(Integer.parseInt(batchServerPort));
urlBuilder.setContextPath(batchReportRoot);
urlBuilder.setServletPath(reportNameServletPath);
urlBuilder.setPathInfo(reportNamePathInfo);
urlBuilder.setScheme(HTTP);
String transitionUrl = urlBuilder.getUrl();
ModelAndView modelAndView = new ModelAndView(new RedirectView(transitionUrl));
return modelAndView;
But how do i take it further to rename the document as it comes in etc...
thanks
Perhaps another approach you might consider is that you have a Controller implementation that proxies the request onto the external website. Rather than interacting with the external website directly, your users interact with your Controller. This will give you the opportunity to re-name the file before it is served to your users. It also means that should things change in the future, you only need to change the implementation of your Controller.
So a proposed work flow could be:
User clicks link to your controller /downloadExcelReport
The request is handled by ExcelReportController
ExcelReportController makes an HTTP request to the external website and fetches the Excel document
Before returning the Excel report to your user, ExcelReportController sets the correct HTTP headers to ensure that the file is named according to what you need.
This way you're only providing a normal Controller implementation rather than having to override the internals of Spring.

I can't get google cloud endpoints to work correctly, am I calling the correct public link?

The api is tagged:
#Api(version = "v1",
description = "API for interfacing with accounts",
defaultVersion = AnnotationBoolean.TRUE)
and one of the methods I want to call is:
#ApiMethod(name = "account.register",
path = "account",
httpMethod = HttpMethod.POST)
public void register(HttpServletRequest request, HttpServletResponse response)
{ ...
but I can't seem to figure out the url to access it :(
I tried POST-ing to myapp.appspot.com/_ah/api/myapi/v1/account but it 404's
A few things...
I think one doesn't usually use Endpoints this way: by posting manually to a URL. Instead, you are expected to generate a client library (which encapsulates the URL) and then use the client library.
If you just want to check out your endpoints, I've heard that the API explorer is very useful. For your specific application you'd use:
https://myapp.appspot.com/_ah/api/explorer
and be redirected to a version of the APIs Explorer for your application.
The actual calls to your App Engine backend are to paths such as this: /_ah/spi/MyEndpoint.myMethod. (Note: the spi versus api in the path.) The actual path you tried to construct is Google's API serving infrastructure acting as a frontend to your application.
You do not have any (HttpServletRequest request, HttpServletResponse response) in an endpoint.
The easiest thing to do is to make your java class (which you want to persist) and then in eclipse point at the java class and right click and select "google -> generate google cloud endpoint class" Then you get a good idea how it looks in different scenarios.
If you want to send parameters you have to add for instance myMethod( #Named( "myName" ) String name ).
But check out the endpoint genration first, it makes it all much simpler
And look here for more info: https://developers.google.com/appengine/docs/java/endpoints/annotations

Categories