Swing+servlet connection
Добрый день! Делаю swing - servlet connection. То есть через обычное десктопное приложение в сервлет передаются какие-то данные и эти же данные получает назад.
public class Demo
{
public static void main(String arg[])
{
try
{
Test frame=new Test();
frame.setSize(300,100);
frame.setVisible(true);
}
catch(Exception e)
{JOptionPane.showMessageDialog(null, e.getMessage());}
}
}
Класс Test
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
class Test extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JButton SUBMIT;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
URL u;
URLConnection uc;
DataOutputStream printout;
Test()
{
label1 = new JLabel();
label1.setText("Input:");
text1 = new JTextField(15);
text2 = new JTextField(50);
label2 = new JLabel();
label2.setText("Output:");
SUBMIT=new JButton("SUBMIT");
panel=new JPanel(new GridLayout(3,1));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(SUBMIT);
add(panel,BorderLayout.CENTER);
SUBMIT.addActionListener(this);
setTitle("I/O");
}
public void actionPerformed(ActionEvent ae)
{
onSendData();
}
private URLConnection getServletConnection()
throws MalformedURLException, IOException {
String input = text1.getText();
// Connection zum Servlet
URL urlServlet = new URL("http://localhost:8080/SwingChat/MyServlet?");
URLConnection con = urlServlet.openConnection();
// konfigurieren
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty(
"Content-Type",
"text/html;charset=UTF-8");
//
return con;
}
private void onSendData() {
try {
// get input data for sending
String input = text1.getText();
// send data to the servlet
URLConnection con = getServletConnection();
OutputStream outstream = con.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstream);
oos.writeObject(input);
oos.flush();
oos.close();
// receive result from servlet
InputStream instr = con.getInputStream();
ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
String result = (String) inputFromServlet.readObject();
inputFromServlet.close();
instr.close();
// show result
text2.setText(result);
} catch (Exception ex) {
ex.printStackTrace();
text2.setText(ex.toString());
}
}
}
И сервлет
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
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;
@WebServlet(urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
//response.setContentType("application/x-java-serialized-object");
// read a String-object from applet
// instead of a String-object, you can transmit any object, which
// is known to the servlet and to the applet
InputStream in = request.getInputStream();
ObjectInputStream inputFromSwing = new ObjectInputStream(in);
String echo = (String) inputFromSwing.readObject();
// echo it to the applet
OutputStream outstr = response.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstr);
oos.writeObject(echo);
oos.flush();
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Когда запускаю, выходит
java.net.SocketException: Network is unreachable: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
Когда в браузере набираю "http://localhost:8080/SwingChat/MyServlet" ошибка ERROR The requested URL could not be retrieved
Вот мой web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web- app_2_4.xsd"
version="2.4">
<display-name>SwingChat</display-name>
<description>
This is a simple web application with a source code organization
based on the recommendations of the Application Developer's Guide.
</description>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
Что я делаю не так? Помогите. :(
Источник: Stack Overflow на русском