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

Have you tried OpenCMS at [URL="http://www.opencms.org/"]http://www.opencms.org/[/URL]? It's truly open source.

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

[QUOTE]java.lang.Exception: Port 8083 already in use.[/QUOTE]

Seems to be that maybe there is another instance running on the server.

martin5211 37

Add a hidden field and modify the value from Javascript. Then you can extract the values using request.getParameter()

martin5211 37

Your external IP is not accessible from intranet, it is a common issue. If you did the right steps, try to access to your wan address from an outside location.

martin5211 37

Thank you. It's ok now using the dot notation.

martin5211 37 Posting Whiz in Training

Hello everybody,

I worked long hours this evening trying to unthread the whole thing and still not working... I don't know why. The page display the results using normal code in JSP (no jstl tags). When using jstl tags the page results in blank screen, no posts. Here is the code:

index.jsp (jstl not working)

[CODE]
<%@ page import="bean.PostBean"%>
<%@ page import="model.Posts" %>
<%@ page import="java.util.*" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

Report Results (NIOSH)
${post.title}

${post.text}

[/CODE]

index.jsp (works)

[CODE]
<%@ page import="bean.PostBean"%>
<%@ page import="model.Posts" %>
<%@ page import="java.util.*" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

Report Results (NIOSH)

[/CODE]

Posts.java

[CODE]
import java.sql.Statement;
import java.util.ArrayList;

import bean.PostBean;

public class Posts {

public ArrayList<PostBean> getPosts() throws Exception{
    ArrayList<PostBean> list = new ArrayList<PostBean>();

    String driver = "com.mysql.jdbc.Driver";
    String user = "root";
    String password = "xx";

    Class.forName(driver);
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dcaminoa", user, password);

    Statement select = (Statement) conn.createStatement();

    ResultSet result = select.executeQuery("select * from posts");

    while(result.next())
    {
        PostBean post = new PostBean();
        post.setId(result.getInt("id"));
        post.setTitle(result.getString("title"));
        post.setText(result.getString("text"));
        list.add(post);
    }
    result.close(); ...

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.

martin5211 37

This is an simple approach to dispatch a value to index.jsp

index.html:
[CODE]

Select Person
Fred

[/CODE]

result.jsp:

[CODE]

[/CODE]

Person.java:

[CODE]
package com.example;

import javax.servlet.;
import javax.servlet.http.
;
import java.io.;
import java.util.
;

public class Person extends HttpServlet
{
public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
String p = request.getParameter("person");

    // display email stored in web.xml
    PrintWriter out = response.getWriter();
    request.setAttribute("email", p);

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

}
[/CODE]

web.xml (stored inside WEB-INF):
[CODE]
<?xml version="1.0" encoding="UTF-8"?>

Person Servlet Example Person com.example.Person Person /Person.do

[/CODE]

martin5211 37

Code for JavaBean:

[CODE]
package com.example;

public class Person {
public String name;

public void setName(String name){
    this.name = name;
}

public String getName(){
    return this.name;
}

}
[/CODE]

result.jsp

[CODE]

Person: [/CODE] result2.jsp [CODE] Person: [/CODE] Don't forget to use session scope for your javabeans.

martin5211 37

You could use a non-enterprise JavaBean, then use and