martin5211 37

Have you tried [ICODE]if(saw == "")[/ICODE]?

martin5211 37

Create a JAR file, it is executable in almost all brand new computers with Java Runtime Environment installed.

martin5211 37

I found some errors in your code:

[CODE]
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/*
The Main class creates the GUI for the Dorm and
Meal charges.
/
public class Main extends JFrame
{
private JPanel dormPanel;
private JComboBox dormBox;
private JPanel mealPanel;
private JComboBox mealBox;
private JPanel totalChargesPanel;
private JPanel selectedMealPanel;
private JPanel buttonPanel;
private JButton calcButton;
private JLabel label1;
private JTextField totalCharges;

private String[] dorm = { "Allen Hall: $1,500 per semester", 
        "Pike Hall: $1,600 per semester", 
        "Farthing Hall: $1,200 per semester", 
"University Suites: $1,800 per semester"};

private String[] meal = { "7 meals per week: $650 per semester", 
        "14 meals per week: $1,095 per semester", 
"Unlimited meals: $1,500 per semester"};

/**
    Constructor
 */
public Main()
{
    super("Dormitory and Meal Plan");

    // Specify an action for the close button.
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create a BorderLayout manager.
    setLayout(new BorderLayout());

    // Create the dorm and meal panel.      
    buildDormPanel();
    buildMealPanel();
    buildSelectedTotalChargesPanel();
    buildButtonPanel();

    // Add the components to the content pane.   
    add(dormPanel, BorderLayout.WEST);
    add(mealPanel, BorderLayout.EAST);
    add(totalChargesPanel, BorderLayout.SOUTH);
    add(buttonPanel, BorderLayout.NORTH);

    // Pack the contents of the window and display it.    
    pack();
    setVisible(true);
}

// The buildDormPanel method builds the dorm panel. 
private void buildDormPanel()
{
    // Create the dorm panel.      
    dormPanel = new JPanel();
    dormBox = new JComboBox(dorm);

    // Register the action listener.      
    dormBox.addActionListener(new ComboBoxListener());

    // Add the dorm panel to the panel.
    dormPanel.add(dormBox);
}

// The buildMealPanel method builds the meal panel. 
private void buildMealPanel()
{
    // Create the meal panel. ...

martin5211 37

Post the issue in a separate thread. Post the code and we'll try to fix it.

martin5211 37

This can be solved using a trim function from client-side, Javascript.

martin5211 37

Maybe, I'm using different application server and browser. Use trim() to remove leading/trailing spaces in ContactServlet:

[CODE]request.setAttribute("emailState", email.trim());[/CODE]

martin5211 37

I can't reproduce the error. Any other hint you could give me?

martin5211 37

Do you have insert privileges into that database?

martin5211 37

An extremely complex filter maybe could perform a domain check and a smtp validation but that can be slow... and that could take time to develop.

martin5211 37

That happens because before [ICODE]<% if (s != null && s.equals("Songs")) out.println("selected=\"selected\""); %>[/ICODE] there is an extra > symbol, needs to be removed on each case.

martin5211 37

Remove [ICODE]Selected="True"[/ICODE] and add > after the value on line 4

martin5211 37

[QUOTE][CODE]<% if s != null && (s.equals("Songs"))[/CODE][/QUOTE]

There's a missing parenthesis, should be:

[CODE]<% if [COLOR="Red"]([/COLOR]s != null && s.equals("Songs"))[/CODE]

Do the same in the other cases.

martin5211 37

Add [ICODE]s != null &&[/ICODE] before [ICODE]s.equals("Option3")[/ICODE] on each condition

martin5211 37

It's easy, use a condition on each option.

[CODE]
<% String s = (String) request.getAttribute("subState"); %>

<option value="Help" <% if (s.equals("Help")) out.println("selected=\"selected\""); %>><fmt:message key="help.text.help"/></option>
<option value="Other" <% if (s.equals("Other")) out.println("selected=\"selected\""); %>><fmt:message key="help.text.other"/></option>

[/CODE]

Instead of using RequestDispatcher object in ContactServlet for the success page, redirect to the same contact form, send an attribute with [ICODE]request.setAttribute()[/ICODE], then finally in the contact form is practical to use a condition (check the attribute isn't null), to display the message.

martin5211 37

I'm sorry, I forgot to add [icode]test(email)[/icode] in the condition that send the email.

[CODE]
package net.sourceforge.subsonic.controller;

import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.;
import javax.servlet.http.
;
import javax.mail.;
import javax.mail.internet.
;

public class ContactServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{

String email = request.getParameter("email");
String subject = request.getParameter("subject");
String message = request.getParameter("message");

request.setAttribute("emailState", email);
request.setAttribute("subState", subject);
request.setAttribute("msgState", message);

if (email.isEmpty()){
    request.setAttribute("err_email", "Please proivde a email");
}
if (!test(email)){
    request.setAttribute("err_email", "Provided incorrect email");
}
if (message.isEmpty()){
    request.setAttribute("err_msg", "Please provide a message");
}
if (subject.isEmpty()){
    request.setAttribute("err_sub", "Please provide a subject");
}

    if(!email.isEmpty() && !message.isEmpty() && !subject.isEmpty() && test(email)){
        Properties props = new Properties();
        props.put("mail.smtp.host", "mysmptserver.com");
        props.put("mail.smtp.port", "587");

            Session session = Session.getDefaultInstance(props, null);

    try {
                Message m = new MimeMessage(session);
                m.setFrom(new InternetAddress(email, ""));
                m.addRecipient(Message.RecipientType.TO, new InternetAddress("myadress@mydomain.com", ""));
                m.setSubject(subject);
                m.setText(message);
                Transport.send(m);

        } catch (AddressException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
    }

    RequestDispatcher view = request.getRequestDispatcher("success.jsp");

    view.forward(request, response);

        }else{
    RequestDispatcher view = request.getRequestDispatcher("contact.jsp");

    view.forward(request, response);

    }
}
public static boolean test(String str){
    String reg = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
    Pattern p = Pattern.compile(reg);
    Matcher m = p.matcher(str);
    while(m.find())
    {
        String s1 = m.group(0);
        if (str == s1) return true;
    }

    return false;
}

}
[/CODE]

Contact form:

[code]

Your email address:

Mail subject:

Mail message:

martin5211 37

To save the information of each field use [icode]request.setAttribute("emailState", email)[/icode] and then [icode]out.println(request.getAttribute("emailState"))[/icode] on the input value (contact form), very similar to the procedure to pass errors.

martin5211 37

There is missing two imports. Place the methods aside, not inside.

[CODE]
package net.sourceforge.subsonic.controller;

import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.;
import javax.servlet.http.
;
import javax.mail.;
import javax.mail.internet.
;

public class ContactServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{

String email = request.getParameter("email");
String subject = request.getParameter("subject");
String message = request.getParameter("message");

if (email.isEmpty()){
    request.setAttribute("err_email", "Please proivde a email");
}
if (!test(email)){
    request.setAttribute("err_email", "Provided incorrect email");
}
if (message.isEmpty()){
    request.setAttribute("err_msg", "Please provide a message");
}
if (subject.isEmpty()){
    request.setAttribute("err_sub", "Please provide a subject");
}

    if(!email.isEmpty() && !message.isEmpty() && !subject.isEmpty()){
        Properties props = new Properties();
        props.put("mail.smtp.host", "mysmptserver.com");
        props.put("mail.smtp.port", "587");

            Session session = Session.getDefaultInstance(props, null);

    try {
                Message m = new MimeMessage(session);
                m.setFrom(new InternetAddress(email, ""));
                m.addRecipient(Message.RecipientType.TO, new InternetAddress("myadress@mydomain.com", ""));
                m.setSubject(subject);
                m.setText(message);
                Transport.send(m);

        } catch (AddressException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
    }

    RequestDispatcher view = request.getRequestDispatcher("donate.view");

    view.forward(request, response);

        }else{
    RequestDispatcher view = request.getRequestDispatcher("help.view");

    view.forward(request, response);

    }
}
public static boolean test(String str){
    String reg = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
    Pattern p = Pattern.compile(reg);
    Matcher m = p.matcher(str);
    while(m.find())
    {
        String s1 = m.group(0);
        if (str == s1) return true;
    }

    return false;
}

}
[/CODE]

martin5211 37

I forgot the i letter on line 8. Place that method after doGet. Use the following conditional after email.isEmpty() condition.

[CODE]
if (!test(email)){
request.setAttribute("err_email", "Provided incorrect email");
}
[/CODE]

martin5211 37

Here is the example, use it into a conditional. I extracted the pattern from [URL="http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/"]http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/[/URL]

[CODE]
public static boolean test(String str){
String reg = "[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)@[A-Za-z0-9]+(\.[A-Za-z0-9]+)(\.[A-Za-z]{2,})";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
while(m.find())
{
String s1 = m.group(0);
if (str == s1) return true;
}

    return false;
}

[/CODE]

martin5211 37

That's more difficult, you need a static method that does an email extraction using regular expressions (Regex) and return a boolean.

Just another suggestion, you can also store the values of each field on request parameters and pass it to each input field to remember the content.

martin5211 37

There is an extra parenthesis on message.isEmpty() call.

[CODE]if(!email.isEmpty() && !message.isEmpty()[COLOR="Red"])[/COLOR] && !subject.isEmpty()){[/CODE]

martin5211 37

Could you be more specific? Are you using out.println(request.getAttribute("err_msg")) on the contact form?

martin5211 37

Both are almost the same code...

[code]
String email = request.getParameter("email");
String subject = request.getParameter("subject");
String message = request.getParameter("message");

if (email.isEmpty()){
    request.setAttribute("err_email", "Email is empty");
}
if (message.isEmpty()){
    request.setAttribute("err_msg", "Message is empty");
}

if(!email.isEmpty() && !message.isEmpty()){
...
}else{
    RequestDispatcher view = request.getRequestDispatcher("contact.jsp");

    view.forward(request, response);

}

[/code]

martin5211 37

Well, we're validating if the message is null. It's possible to add more fields on that condition and an else clause to redirect to the form again. Also, would be nice to pass a request parameter to the jsp.

[CODE]
import java.io.IOException;
import java.util.Properties;
import javax.servlet.;
import javax.servlet.http.
;
import javax.mail.;
import javax.mail.internet.
;

public class ContactServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{

    String email = request.getParameter("email");
    String subject = request.getParameter("subject");
    String message = request.getParameter("message");

    if(!message.isEmpty()){
        String host = "smtp.gmail.com";
            int port = 587;
            String username = "*** your Gmail username ***";
            String password = "*** your Gmail password ***";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            Session session = Session.getDefaultInstance(props, null);

            String body = message;

        try {
                Message m = new MimeMessage(session);
                m.setFrom(new InternetAddress(email, null));
                m.addRecipient(Message.RecipientType.TO, new InternetAddress("destination@example.com", "me"));
                m.setSubject(subject);
                m.setText(body);

                Transport transport = session.getTransport("smtp");
                transport.connect(host, port, username, password);

                Transport.send(m);

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }

        RequestDispatcher view = request.getRequestDispatcher("success.jsp");
        view.forward(request, response);

    }else{
        request.setAttribute("error", "Message is empty");

        RequestDispatcher view = request.getRequestDispatcher("contact.jsp");  // return to contact form
        view.forward(request, response);

    }
}

}
[/CODE]

Use [ICODE]out.println(request.getAttribute("error"))[/ICODE] on the contact form to show the error. A better alternative would be:

[code]

Mail message:

[/code]

martin5211 37

Another alternative, is to use Gmail as mail transport agent, with some modifications of the code:

[CODE]
import java.io.IOException;
import java.util.Properties;
import javax.servlet.;
import javax.servlet.http.
;
import javax.mail.;
import javax.mail.internet.
;

public class ContactServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{

    String email = request.getParameter("email");
    String subject = request.getParameter("subject");
    String message = request.getParameter("message");

    if(!message.equals(null)){
        String host = "smtp.gmail.com";
        int port = 587;
        String username = "*** your Gmail username ***";
        String password = "*** your Gmail password ***";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getDefaultInstance(props, null);

        String body = message;

    try {
            Message m = new MimeMessage(session);
            m.setFrom(new InternetAddress(email, null));
            m.addRecipient(Message.RecipientType.TO, new InternetAddress("destination@example.com", "me"));
            m.setSubject(subject);
            m.setText(body);

            Transport transport = session.getTransport("smtp");
            transport.connect(host, port, username, password);

            Transport.send(m);

        } catch (AddressException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }

        RequestDispatcher view = request.getRequestDispatcher("success.jsp");

        view.forward(request, response);

    }
}

}
[/CODE]

martin5211 37

Yes, a SMTP server is missing according to the first line.

martin5211 37

Can you give the complete stack trace of the error?

martin5211 37

That's weird, works flawlessly in my computer. In most cases, you need to configure Postfix or Sendmail to accept incoming email through port 25.

martin5211 37

Use [ICODE]String message = request.getParameter("message");[/ICODE] on the servlet to extract each input field value, the following snippet will do the rest:

[CODE]
import java.io.IOException;
import java.util.Properties;
import javax.servlet.;
import javax.servlet.http.
;
import javax.mail.;
import javax.mail.internet.
;

public class ContactServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{

    String email = request.getParameter("email");
    String subject = request.getParameter("subject");
    String message = request.getParameter("message");

    if(!message.equals(null)){
        Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

    try {
                Message m = new MimeMessage(session);
                m.setFrom(new InternetAddress(email, "user"));
                m.addRecipient(Message.RecipientType.TO, new InternetAddress("dest@example.com", "me"));
                m.setSubject(subject);
                m.setText(message);
                Transport.send(m);

        } catch (AddressException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
    }

    RequestDispatcher view = request.getRequestDispatcher("success.jsp");

    view.forward(request, response);

    }
}

}
[/CODE]

martin5211 37

It's a common mistake that everyone makes. Other issue that could happen are related with thread safety when using attributes, could get the exact same symptoms.