I've tried this question before with little success but that's probably my fault so I'll be as specific as possible!
Part A)
I have a compiled java class which returns a hello world string. The source code for this file is below. After configuring the web.xml setting I am able to get good results from a browser pointing at localhost. This is working exactly as planned.
Part B)
I have an HTML landing page with a single link in it which, when pressed will read a local text file and replace content within it. This is also working exactly as planned.
Part A means I am able to have a client call a server-side java class file and get outputs. Part B means I am able to replace one part of a webpage after a button has been pressed.
My question, from this point is quite straight forward. I would like to merge the two concepts so that when the link from part B is pressed the text updated will reflect the 'hello world' result set from Part A.
Thanks in advance.
Part A Code:
package mypkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
Part B Code
<p id="mySentence">
Click here to update the page.
When you click the link, this content will be replaced.</p>
<script type="text/javascript">
var http = createRequestObject();
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
objAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}
function getNewContent(){
http.open('get','newcontent.txt');
http.onreadystatechange = updateNewContent;
http.send(null);
return false;
}
function updateNewContent(){
if(http.readyState == 4){
document.getElementById('mySentence').innerHTML = http.responseText;
}
}
</script>
Related
I'm trying to learn how to write simple servlets to use with a Raspberry Pi.
I want to control the board I/O via web.I'm using the Pi4J library which is a wrapper for the WiringPi C library.It works when I use it to blink a led locally so I assume that I'm doing something wrong coding my servlet.
This is the code I wrote:
package com.luca.servlet;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.PinState;
public class MyServlet extends javax.servlet.http.HttpServlet {
private GpioController gpio=GpioFactory.getInstance();
private GpioPinDigitalOutput redLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_23,PinState.LOW);
private GpioPinDigitalOutput greenLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_22,PinState.LOW);
private GpioPinDigitalOutput blueLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_21,PinState.LOW);
private GpioPinDigitalOutput[] pins=new GpioPinDigitalOutput[]{redLed,greenLed,blueLed};
#Override
public void doGet(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response) throws java.io.IOException {
java.io.PrintWriter print=response.getWriter();
print.write("<body>"+
"<p> Choose a color! </p>"+
"<form action=\"first\" method=\"POST\">"+
"<input type=\"submit\" name=\"button\" value=\"red\"/>"+
"</form>"+
"<form action=\"first\" method=\"POST\">"+
"<input type=\"submit\" name=\"button\" value=\"green\"/>"+
"</form>"+
"<form action=\"first\" method=\"POST\">"+
"<input type=\"submit\" name=\"button\" value=\"blue\"/>"+
"</form>"+
"</body>");
}
public void doPost(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response) throws java.io.IOException {
java.io.PrintWriter pw=response.getWriter();
String act=request.getParameter("button");
switch(act) {
case "red":
togglePin();
redLed.high();
pw.write("<p>the led is red!</p>");
break;
case "green":
togglePin();
greenLed.high();
pw.write("<p>the led is green</p>");
break;
case "blue":
togglePin();
blueLed.high();
pw.write("<p>the led is blue!</p>");
break;
}
}
private void togglePin() {
for (GpioPinDigitalOutput pin : pins)
if (pin.isHigh()) pin.toggle();
}
it compiles fine and I manually deploy it inside tomcat,with the deployment descriptor and all.
But when I connect it says to me that the resource is unavailable.
If I remove the GPIO related code it works fine.
Can someone please help me out? Google searching doesn't seem to help
You need to set an Url Pattern in order to access to your servlet methods like POST and GET.
For example use:
#WebServlet("/raspberryServelt")
public class MyServlet extends javax.servlet.http.HttpServlet {
...
And then access to the servlet methods doing a POST or GET request...
For example doing a get to:
localhost:8080/yourWebAppName/raspberryServelt
Will work...
You must put in your project the pi4j libraries in path WEB-INF/lib
I am a complete new t servlet can someone plz tell me what is wrong with my code;i am trying to name input from user in a textbox and then display welcome :"text entered by user in textbox"
here is my code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class myprogramme extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException {
res.setContentType("text/html");
PrintWritter out=res.getWritter();
String name=req.getParameter("txtname");
out.println("<b>< font size=8 color="red">" +"welcome:"+ </font> "</b>"+name);
}
}
name of the textbox is txtname which i am storing in name variable
To answer your specific question, you need to escape your String literal (the double quotes surrounding red) and you didn't quote the font close tag (but you could collapse it to a single HTML String) like -
out.println("<b><font size=8 color=\"red\">Welcome:</font></b>" + name);
That being said, this is not a good way to write Java Servlet today. Because it uses presentation in the Servlet.
Edit It's getWriter(), change this
PrintWritter out=res.getWritter();
to
PrintWriter out=res.getWriter();
True, it is not the best way to do it, but I would suggest you to do like below for you to learn it easily:
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("txtname");
StringBuilder sb = null;
try {
sb = new StringBuilder();
sb.append("<b>< font size='8' color='red'>");
sb.append(" Welcome : " + name + " </font></b>");
out.println(sb.toString())
} catch (Exception e) {
e.printStackTrace();
}
}
I haven't test it, hope you can get an idea..
I was doing a simple web project (you can see the code below). As far as I know, session attributes are related to one session. When I opened two tabs of the same browser and run type the URL, only one session ID is created, but two different objects of the same session attribute are running (i.e I don't want to run two quizzes at the same time. But, when I changed the question in one of the tab, it doesn't affect the session attributes of the other tab). Can you explain me why it happened like that? How can I change my code to make the session variables shared so that when I changed one of the session attributes in one of the tabs, I wanted the other tab's session variables to be affected to?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.quizServlet;
import QuizApp.Quiz;
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;
import javax.servlet.http.HttpSession;
/**
*
* #author Mati
*/
#WebServlet(name = "QuizServlet", urlPatterns = {"/Quiz"})
public class QuizServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
} catch (Exception ex) {
out.write("<font style='color:red'><b>" + ex.getMessage() + "</b></font>");
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
if (request.getSession().getAttribute("QuizzObject") == null) {
Quiz quiz = new Quiz();
quiz.addQuestion(new int[]{1, 2, 3, 4});
quiz.addQuestion(new int[]{1, 1, 2, 3, 5, 8});
quiz.addQuestion(new int[]{0, 5, 10, 15, 20, 25});
request.getSession().setAttribute("QuizzObject", quiz);
}
if (request.getSession().getAttribute("questionsLeft") == null) {
request.getSession().setAttribute("questionsLeft", true);
}
Quiz qq = (Quiz) request.getSession().getAttribute("QuizzObject");
qq.reset();
StringBuilder SB = new StringBuilder();
SB.append("<form name='myform' method='post'>");
SB.append("<h3>Have fun with NumberQuiz!</h3>");
SB.append("<p><input type='submit' name='btnNext' value='Start quiz' /></p>");
SB.append("</form>");
out.print(SB.toString());
} catch (Exception ex) {
out.write("<font style='color:red'><b>" + ex.getMessage() + "</b></font>");
} finally {
out.close();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
StringBuilder SB = new StringBuilder();
String msg="";
SB.append("<html><head></head><body>");
Quiz qq = (Quiz) request.getSession().getAttribute("QuizzObject");
SB.append(request.getSession().getId());
boolean questionsLeft = (Boolean) request.getSession().getAttribute("questionsLeft");
if (questionsLeft) {
qq.addAttempts();
if (request.getParameter("txtAnswer") != null) {
if (qq.isCorrect(Integer.parseInt(request.getParameter("txtAnswer")))) {
qq.scoreAnswer();
} else {
msg="<p><font style='color:red'>Wrong Answer .. Try Again</font></p>";
}
}
if (qq.getCurrentQuestion() == null) {
request.getSession().setAttribute("questionsLeft", false);
SB.append("Congratulations, you have completed the quiz!");
SB.append("<br>Your final score is:" + qq.getScore());
SB.append("<br>Total attempts:" + qq.getAttempt());
qq.reset();
request.getSession().setAttribute("questionsLeft",null);
} else {
SB.append("<form name='myform' method='post'>");
//SB.append("<h3>Have fun with NumberQuiz!</h3>");
SB.append("<p>Your current score is " + qq.getScore() + ".</p>");
SB.append("<p>Guess the next number in the sequence!</p>");
SB.append("<p>" + qq.getCurrentQuestion().toString().replaceAll("\\?", "<font style='color:red'><b>?</b></font>") + "</p>");
SB.append("<p>Your answer:<input type='text' id='txtAnswer' name='txtAnswer' value='' /></p>");
SB.append("<p><input type='submit' name='btnNext' value='Next' onclick='return validate()' />");
SB.append("<input type='Reset' name='btnStart' value='Restart!' onclick=\"document.location.href='/QuizzWeb/Quiz';return false;\" /></p>");
SB.append(msg);
SB.append("</form>");
SB.append("<script type='text/javascript'>function validate(){if(document.getElementById('txtAnswer').value==''){alert('You should write an answer');return false;}return true;}</script>");
}
SB.append("</body></html>");
out.print(SB.toString());
}
} catch (Exception ex) {
out.print("<font style='color:red'><b>" + ex.getMessage() + "</b></font>");
} finally {
out.close();
}
}
#Override
public String getServletInfo() {
return "Short description";
}
}
I think you may have a few concepts muddled a bit, hopefully this explanation will make sense and help you sort things out.
A session lives on your application server. When created, it is communicated to your browser through use of a cookie (often named JSESSIONID). When your browser supplies that cookie to the webserver as part of a request, the server can retrieve the session and associated objects (should be serializable, see other SO questions) that had already been attached to that session (provided that this session has not expired).
As these session variables live only on the server, they are used by the server to build the response given to the client. But in order to have a response, your client needs to make a request. You made a request and changed the state of the first tab, but because the second tab didn't make a request of its own, it's state hasn't updated. (Because these tabs are in the same browser, they share a session cookie, and retrieve the same session to fufill their requests). With some more building out, you could make use of some client side technologies such as AJAX to perodically make small requests about the session state and refresh the display of your browser windows. (You could distinguish such requests by having them call a different resource, or different accept types on the request).
Now with the design of your code... I didn't look at it in too much depth, but you may want to work through your flow a bit more. It seems a GET will always reset your quiz and a post continues it? (This feels somewhat odd to me, but I can't put my finger on why... I'd recommend reading up on REST and designs driven from such. JAX-RS & Jersey is pretty sweet :) ).
Edit: Here's a much simpler servlet that you could use to play with. Plop it into a war, and open 2 tabs, one just to the servlet itself, and another appending the query string ?checkOnly=true. Play with refreshing each tab independently and see what happens to the count.
package test.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Counting servlet counts the number of requests to it.
* #author Charlie Huggard-Lee
*/
#SuppressWarnings("nls")
public class CountingServlet extends HttpServlet {
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 4279853716717632192L;
/**
* {#inheritDoc}
*/
#Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
final HttpSession session = req.getSession();
AtomicInteger counter = (AtomicInteger) session.getAttribute("Count");
if (counter == null) {
counter = new AtomicInteger();
session.setAttribute("Count", counter);
}
final boolean checkOnly = Boolean.parseBoolean(req.getParameter("checkOnly"));
final int thisCount;
if (checkOnly) {
thisCount = counter.get();
} else {
thisCount = counter.getAndIncrement() + 1;
}
resp.setStatus(200);
resp.setHeader("Content-Type", "text/plain"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setCharacterEncoding("UTF-8"); //$NON-NLS-1$
final PrintWriter writer = resp.getWriter();
if (session.isNew()) {
writer.append("Hey new user!\n");
} else {
writer.append("Welcome Back!\n");
}
writer.append("Session ID: ");
writer.append(session.getId());
writer.append("\n");
if (checkOnly) {
writer.append("(checking) ");
}
writer.append("Count: ");
writer.append(Integer.toString(thisCount));
}
}
When session is established server sends cookie to your browser. The same cookie is sent back everytime an URL matches cookie scope, which (most of the time) is defined by domain & path attributes of a cookie. So it doesn't matter if you have 2, 10 or 50 open tabs in your browser. As long as there's a match between URL you're accessing and your session cookie scope, you will get the same session. As far as browser is concerned, there is no such thing as session, so don't assume that your browser is aware of it. It just simply sends cookies. That's all.
And there are no "two different objects of the same session atribute". Session guarantees that there is only one entry for a given name. You just overwrite it everytime you do a request from other tab.
I'm trying to figure out how to upload one file using GWTs FileUpload widget. I'm using GWT and Google AppEngine with Java but I would like to upload file to my own Linux server.
I have the following code already but now I can't figure out how to submit my file to the Google AppServer server and save it to another server:
public class FileUploader{
private ControlPanel cp;
private FormPanel form = new FormPanel();
private FileUpload fu = new FileUpload();
public FileUploader(ControlPanel cp) {
this.cp = cp;
this.cp.setPrimaryArea(getFileUploaderWidget());
}
#SuppressWarnings("deprecation")
public Widget getFileUploaderWidget() {
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// form.setAction(/* WHAT SHOULD I PUT HERE */);
VerticalPanel holder = new VerticalPanel();
fu.setName("upload");
holder.add(fu);
holder.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("You selected: " + fu.getFilename(), null);
form.submit();
}
}));
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
if (!"".equalsIgnoreCase(fu.getFilename())) {
GWT.log("UPLOADING FILE????", null);
// NOW WHAT????
}
else{
event.cancel(); // cancel the event
}
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
form.add(holder);
return form;
}
}
Now, what do I need to do next? What do i need to put in web.xml and how do I write my servlet so i can store file and return url of that object (if possible)
Here's the code from my app:
1) I created a class to accept http request:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10*(1024*1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
2) Then in my web.xml I've added these lines:
<servlet>
<servlet-name>fileUploaderServlet</servlet-name>
<servlet-class>com.testapp.server.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUploaderServlet</servlet-name>
<url-pattern>/testapp/fileupload</url-pattern>
</servlet-mapping>
3) And for form.action did this:
form.setAction(GWT.getModuleBaseURL()+"fileupload");
I would suggest using GWTUpload because it's dead simple to use and extend. You can add it to your project in less than 10 minutes and it supports GAE right out of the box (using GWTUpload-GAE). See the examples for some common usage scenarios.
In GWT, you can post the file to the server using http form methods, and you must use the supplied HttpServlet to accept and save the data as binary blogs in the Appengine BigTable.
Then, you need a second HttpServlet to read the file from bigtable, SET THE MIME TYPE IN THE HTTP HEADER {and caching options}, and then stream the file to the user.
Although RPC isn't NECESSARILY needed, you must let the client know what the generated fileId is so they can access it {unless you want to let user's supply the id and force them to worry about name overrides... ...ick}. Either you can use rpc to ask for a list of / single id {like "newest file id by user"}, or you can return that id in the body of the UploadServlet's response... but then you must make sure your post target is an in-page iframe, poll to make sure the iframe has a body between the submit event and the actual server response, and then parse and use that id in gwt to create an img or object tag that uses the file.
The key part is having one servlet for upload, and another to download. Remember, BigTable just stores binary blobs, so you also need your data entity to have a mime/content Type that can be read from the input file {never rely on file extensions!}. Also, there's a 1MB per entity in the BigTable, and a 10MB request limit for free accounts. You may wish to have your data entity contain a list of 1-10 blobs, each of which are a max 1024bytes.
Basically, your best bet is to find a working, free copy, like Google File Service, and extend it to learn how the system works.
If you wish, I will be posting my own open-source version of file handling, once I finish the gwt control widgets and can consider it all stable enough to be useful to anyone. Email x AT aiyx DOT info if you want me to send you a jar of betalicious code.
Here you go with a complete GWT fileupload with Progress bar
Here you can DOWNLOAD the source
Hello everyone and thanks in advance.
This is a last ditch effort to figure out what the problem is or find a better solution.
I am using JSP filter to filter web access to a tomcat web server.
I have a client, a server and the filter.
The client and the filter open up sockets the the server receives them.
I heard that opening up a server socket in a JSP files is a no-no but I cannot think of a better way to make it send a string to the server software, if you know any please do tell
But the problem on hand is that when the page is filtered it only send the string initially and not anytime after that
I have the socket opened in the filter and the receiver in the server program is in a thread so it should be taking and printing the string when it is received.
All of my code is zipped in here, you will need tomcat to run.
http://www.easy-share.com/1904209945/JNetProtect.zip
I'm really sorry for the length and complexity of this question, please if there is any better way to do this do speak up,
From your explanation it looks to me, that you are lacking some significant concepts. Please excuse me if it sounds offensive to you.
JSP page is processed on the server, which means if you are opening up a socket in your JSP it doesn't mean client is opening the socket.
However, can't you use command pattern, probably using Servlet Filter, to direct your request to a particular Command object and then do your socket stuff there.
Well I didn't get any exceptions,
But what would you suggest I do with this filter so I can do an outSide.println() in the DoFilter()?
import java.net.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public final class IEFilter implements Filter
{
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
ServerSocket fs;
String browser = "";
String blockInfo;
String address = request.getRemoteAddr();
if(((HttpServletRequest)request).getHeader ("User-Agent").indexOf("MSIE") >= 0)
{
browser = "Internet Explorer";
}
if(browser.equals("Internet Explorer"))
{
BufferedWriter fW = new BufferedWriter(new FileWriter("C://logs//IElog.rtf"));
blockInfo = "Blocked IE user from:" + address;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>");
out.println("This page is not available - JNetProtect");
out.println("</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<center><H1>Error 403</H1>");
out.println("<br>");
out.println("<br>");
out.println("<H1>Access Denied</H1>");
out.println("<br>");
out.println("Sorry, that resource may not be accessed now.");
out.println("<br>");
out.println("<br>");
out.println("<hr />");
out.println("<i>Page Filtered By JNetProtect</i>");
out.println("</BODY>");
out.println("</HTML>");
// outSide.println("Blocked and Internet Explorer user");
fW.write(blockInfo);
fW.newLine();
fW.close();
} else {
chain.doFilter(request, response);
}
}
public void destroy()
{
outsocket.close();
outSide.close();
}
public void init(FilterConfig filterConfig)
{
try
{
Socket outsocket;
PrintWriter outSide ;
outsocket = new Socket("Localhost", 1337);
outSide = new PrintWriter(outsocket.getOutputStream(), true);
}catch (Exception e){
System.out.println("error with this connection");
e.printStackTrace();
}
}
}