create contact form in jsp? - java

I'm able to send email by using the following code and by using Javamail API, through which I can send to any email-id using "FROM"as my "yahoo email id". The code:
mailFORM.html
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Mail form in html</title>
</head>
<body>
<table border="1" width="50%" cellpadding="0" cellspacing="0">
<tr>
<td width="100%">
<form method="POST" action="mail.jsp">
<table border="1" width="100%" cellpadding="0" cellspacing="0">
<h1>Mail API</h1>
<tr>
<td width="50%"><b>To:</b></td>
<td width="50%"><input type="text" name="to" size="30"></td>
</tr>
<tr>
<td width="50%"><b>From:</b></td>
<td width="50%"><input type="text" name="from" size="30"></td>
</tr>
<tr>
<td width="50%"><b>Subject:</b></td>
<td width="50%"><input type="text" name="subject" size="30"></td>
</tr>
<tr>
<td width="50%"><b>Description:</b></td>
<td width="50%"><textarea name="description" type="text"
cols="40" rows="15" size=100>
</textarea>
</td>
</tr>
<tr>
<td><p><input type="submit" value="Send Mail" name="sendMail"></td>
</tr>
</table>
</p>
</form>
</td>
</tr>
</table>
</body>
</html>
mail.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%# page language="java" import="javax.naming.*,java.io.*,javax.mail.*,
javax.mail.internet.*,com.sun.mail.smtp.*"%>
<html>
<head>
<title>sending mail using contactus form</title>
</head>
<body>
<%
try{
Session mailSession = Session.getInstance(System.getProperties());
Transport transport = new SMTPTransport(mailSession,new URLName("smtp.mail.yahoo.com"));
transport = mailSession.getTransport("smtps");
transport.connect("smtp.mail.yahoo.com",465,"myyahooid#yahoo.com","myyahoopassword");
MimeMessage m = new MimeMessage(mailSession);
m.setFrom(new InternetAddress(%><%request.getParameter("from")%><%));
Address[] toAddr = new InternetAddress[] {
new InternetAddress(%><%request.getParameter("to")%><%)
};
m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr );
m.setSubject(%><%request.getParameter("subject")%><%);
m.setSentDate(new java.util.Date());
m.setContent(%><%request.getParameter("description")%><%, "text/plain");
transport.sendMessage(m,m.getAllRecipients());
transport.close();
out.println("Thanks for sending mail!");
}
catch(Exception e){
out.println(e.getMessage());
e.printStackTrace();
}
%>
</body>
Now, I want to create a simple CONTACTUS form in which I'll eliminate the "TO" field from "mailFORM.html" file for obvious reasons. As I only want any visitor to visit my website and send email to "mycompanyid#domain.com" by entering FROM, NAME, SUBJECT and description.
So how can I eliminate this problem of entering username and passwod. As I can't create a code in which I 've entred passord here. I can't create separate codes for different smtp's...as VISITIR visting my website contactus page can fill the form by entering his/her email from any domain i'e gmail, yahoo etc.
To conclude I just want to create form like this(taking any anonymous website) which sends the details to company's specific email-ids like "mycompanyid#domain.com"
http://www.tutorialspoint.com/about/contact_us.htm

Hard code your To email id in your JSP file, but its a good practice avoid writing your java code in JSP, should write only method call.
private final String TO_EMAIL = "something#domain.com";
see my code it works for all SMTPS.
package com.naveed.workingfiles;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
public class Mail {
String senderID;
String senderPassword;
String hostName;
int portNumber;
String attachmentPath;
String subject;
String body;
String cc;
String bcc;
// #=============================================================================================#
public String getBcc() {
return bcc;
}
// #=============================================================================================#
public void setBcc(String bcc) {
this.bcc = bcc;
}
// #=============================================================================================#
public String getCc() {
return cc;
}
// #=============================================================================================#
public void setCc(String cc) {
this.cc = cc;
}
// #=============================================================================================#
public String getBody() {
return body;
}
// #=============================================================================================#
public void setBody(String body) {
this.body = body;
}
// #=============================================================================================#
public String getSubject() {
return subject;
}
// #=============================================================================================#
public void setSubject(String subject) {
this.subject = subject;
}
// #=============================================================================================#
public String getSenderID() {
return senderID;
}
// #=============================================================================================#
public void setSenderID(String senderID) {
this.senderID = senderID;
}
public String getSenderPassword() {
return senderPassword;
}
// #=============================================================================================#
public void setSenderPassword(String senderPassword) {
this.senderPassword = senderPassword;
}
// #=============================================================================================#
public String getHostName() {
return hostName;
}
// #=============================================================================================#
public void setHostName(String hostName) {
this.hostName = hostName;
}
// #=============================================================================================#
public int getPortNumber() {
return portNumber;
}
// #=============================================================================================#
public void setPortNumber(int portNumber) {
this.portNumber = portNumber;
}
// #=============================================================================================#
public String getAttachmentPath() {
return attachmentPath;
}
// #=============================================================================================#
public void setAttachmentPath(String attachmentPath) {
this.attachmentPath = attachmentPath;
}
// #=============================================================================================#
public void sendMail(String receiverId) {
try {
// this below commented line for the HTML body text
// MultiPartEmail htmlEmail = new HtmlEmail();
// OR
// HtmlEmail email = new HtmlEmail();
MultiPartEmail email = new MultiPartEmail();
// setting the port number
email.setSmtpPort(getPortNumber());
// authenticating the user
email.setAuthenticator(new DefaultAuthenticator(getSenderID(),
getSenderPassword()));
// email.setDebug(true);
email.setSSL(true);
// setting the host name
email.setHostName(getHostName());
// setting the rciever id
email.addTo(receiverId);
// check for user enterd cc or not
if (getCc() != null) {
// add the cc
email.addCc(getCc());
}
// check for user enterd bcc or not
if (getBcc() != null) {
// add the bcc
email.addBcc(getBcc());
}
// setting the sender id
email.setFrom(getSenderID());
// setting the subject of mail
email.setSubject(getSubject());
// setting message body
email.setMsg(getBody());
// email.setHtmlMsg("<h1>"+getBody()+"</h1>");
// checking for attachment attachment
if (getAttachmentPath() != null) {
// add the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(getAttachmentPath());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
}
// send the email
email.send();
// System.out.println("Mail sent!");
} catch (Exception e) {
// System.out.println("Exception :: " + e);
e.printStackTrace();
}
}// sendmail()
}// mail
only you need to save all respective domain details (hostname,port), based on user email set all setters.
down load all required libraries.

You can just hardcore the Message.RecipientType.TO variable.
Somewhere you can define a static variable MY_MAIL and use MY_MAIL instead of request.getParameter("to")
Make sure to include the senders e-mail somewhere in the code though, such that you can contact them whenever neccessary.
Also a few other considerations:
Please read about seperating the actual Java code from a JSP page, you can find enough links for that on google.
You are importing classes, but then are never using the imports anymore.
There are useless %><% in the code, I don't even know where they are for.

Related

Problems Creating Login/Registration Page with servlets/MySQL in Eclipse

So here is my issue. I am working on a school project and I am basically hitting a wall. I cannot get my RegistrationServer to work at all. I can get it to run, and correctly display the Registration.jsp that it is built behind, but none of the information is entered into the database at all. In fact, I cannot even tell if that is where exactly I am failing. Here is the code for the Registration function:
Registration.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style>
div.container {
//width: 100%;
// border: 1px solid gray;
// padding:5px;
}
table, th, td {
//border: 1px solid black;
}
.textright{float:right;padding:10px}
</style>
<title>Registration</title>
<script>
function validate()
{
var firstname = document.form.firstname.value;
var lastname = document.form.lastname.value;
var username = document.form.username.value;
var password = document.form.password.value;
var address = document.form.address.value;
var contact = document.form.contact.value;
if (firstname==null || firstname=="")
{
alert("First Name can't be blank");
return false;
}
else if (lastname==null || lastname=="")
{
alert("Last Name can't be blank");
return false;
}
else if (username==null || username=="")
{
alert("Username can't be blank");
return false;
}
else if (password==null || password=="")
{
alert("Password can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
else if (address==null || address=="")
{
alert("Address can't be blank");
return false;
}
else if (contact==null || contact=="")
{
alert("Contact can't be blank");
return false;
}
}
</script>
</head>
<body bgcolor="#D3D3D3">
<form name="form" action="RegistrationServlet" method="post"
onsubmit="return
validate()">
<td style="float:left"><image
src="file:///G:/College/Winter%202018/CSC%20363/Computer%20logo.png"
width="100px" height="100px"></image></td>
<p style="float:right"><b> ${members[3]} <br> CSC 363<br>Final Project</b>
</p>
<td style="clear:float"></td>
<p style="align-text"left">Team</p>
<p style="float:left">${members[0]} <br> ${members[1]} <br>
${members[2]} </p>
<td style="close:float"></td>
<table style="float:right">
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Contact</td>
<td><input type="text" name="contact" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></input>
</tr>
</table>
</form>
</body>
</html>
RegistrationServlet
package com.mvc.RegistrationServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mvc.Bean.RegistrationBean;
import com.mvc.Dao.RegistrationDao;
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegistrationServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String[] members = new String[4];
members[0] = "Jamie W.";
members[1] = "Evan D.";
members[2] = "Tim D.";
members[3] = "Hardware Plus";
request.setAttribute("members", members);
request.getRequestDispatcher("/Registration.jsp").forward(request,
response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String userName = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
RegistrationBean registrationBean = new RegistrationBean();
registrationBean.setFirstName(firstName);
registrationBean.setLastName(lastName);
registrationBean.setUserName(userName);
registrationBean.setPassword(password);
registrationBean.setAddress(address);
registrationBean.setContact(contact);
RegistrationDao registrationDao = new RegistrationDao();
String userRegistered = registrationDao.registrationUser(registrationBean);
if(userRegistered.equals("SUCCESS"))
{
request.getRequestDispatcher("/ProductSalesPage.jsp").forward(request,
response);
}
else
{
request.setAttribute("errMessage", userRegistered);
request.getRequestDispatcher("/RegistrationServlet.jsp").forward(request,
response);
}
}
}
RegistrationDao
package com.mvc.Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mvc.Bean.RegistrationBean;
import com.mvc.RegistrationDB.RegistrationDB;
public class RegistrationDao {
public String registrationUser(RegistrationBean registrationBean)
{
String firstName = registrationBean.getFirstName();
String lastName = registrationBean.getLastName();
String userName = registrationBean.getUserName();
String password = registrationBean.getPassword();
String address = registrationBean.getAddress();
String contact = registrationBean.getContact();
Connection con = null;
PreparedStatement preparedStatement = null;
try
{
con = RegistrationDB.createConnection();
String query = "insert into
users(SlNo,firstName,lastName,userName,password,address,contact) values
(NULL,?,?,?,?,?,?)";
preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, firstName);
preparedStatement.setString(2, lastName);
preparedStatement.setString(3, userName);
preparedStatement.setString(4, password);
preparedStatement.setString(5, address);
preparedStatement.setString(6, contact);
int i= preparedStatement.executeUpdate();
if (i!=0)
return "SUCCESS";
}
catch(SQLException e)
{
e.printStackTrace();
}
return "Oops.. Something went wrong there..!";
}
}
RegistrationDB
package com.mvc.RegistrationDB;
import java.sql.Connection;
import java.sql.DriverManager;
public class RegistrationDB {
public static Connection createConnection()
{
Connection con = null;
String url = "jdbc:mysql#localhost:3306/project/users";
String username = "root";
String password = "password";
try
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
con = DriverManager.getConnection(url, username, password);
System.out.println("Printing connection object "+con);
}
catch (Exception e)
{
e.printStackTrace();
}
return con;
}
}
RegistrationBean
package com.mvc.Bean;
public class RegistrationBean
{
private String firstName;
private String lastName;
private String userName;
private String password;
private String address;
private String contact;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getContact() {
return contact;
}
}
Anything anyone can offer as far as why this servlet will not run would be gladly appreciated. The error messages that Eclipse throws are so generic, but the issue seems to be basically writing the registration information to the database. I can load the registration page and enter the information, and the if statements work because the page wont forward with blank text entry boxes or a password less than 6 characters. The problem is when you submit, and it throws HTTP Status 404 and says the requested resource is unavailable.
It might be because you're retrieving the incorrect parameter names in your RegistrationServlet.
For example: you are retrieving with request.getParameter("firstname") but your input have name="firstName". Note the upper case 'N' (java EE servers are case sensitive for URIs).
Try this in your RegistrationServlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName"); // upper case N
String lastName = request.getParameter("lastName"); // upper case N
String userName = request.getParameter("userName"); // upper case N
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
//...

Web app using java and angularjs

i'm trying to create simple market web application. I want to add a sign-in functionality to add users in my db, but i can't understand, how can i "call" my registration method (from java) in js script. Currently, the only thing that my web-app actually does is show records(which i added manually) from users-table.
Here is my db-manager:
`public class DatabaseManager {
public static String host = "localhost";
public static String port = "5432";
public static String dbname = "market";
public static String user = "postgres";
public static String pass = "123456";
public static String url = "jdbc:postgresql://"+host+":"+port+"/"+dbname+"?user="+user+"&password="+pass;
static {
try {
DriverManager.registerDriver(new org.postgresql.Driver());
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Can not connect to the database:\n"+e.getMessage());
}
return null;
}
public static void closeConnection(Connection connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}`
Auth - dto:
public class Auth {
public static class RegisterReq {
public String name;
public String lastname;
public String login;
public String pass;
public int age;
public String gender;
public RegisterReq(String name, String lastname, String login, String pass, int age, String gender) {
this.name = name;
this.lastname = lastname;
this.login = login;
this.pass = pass;
this.age = age;
this.gender = gender;
}
}
public static class RegisterResp {
public boolean status;
public RegisterResp(boolean status) {
this.status = status;
}
}
public static class LoginReq {
public String login;
public String pass;
public LoginReq(String login, String pass) {
this.login = login;
this.pass = pass;
}
}
public static class LoginResp {
public boolean status;
public LoginResp(boolean status) {
this.status = status;
}
}
}
Auth-class with sign-up method:
`
import static dto.Auth.*;
#Path("/auth")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class Auth {
#POST
#Path("/register")
public RegisterResp register(RegisterReq req) {
boolean result = false;
//sql
Connection connection = null;
try {
connection = DatabaseManager.getConnection();
Statement stmt = connection.createStatement();
String checkSql = "select e_mail from users";
ResultSet resultSet=stmt.executeQuery(checkSql);
while (resultSet.next()) {
if(req.login.equals(resultSet.getString(1))) return new RegisterResp(result);
}
//unsafe query
String sql = "INSERT INTO users" +
" (u_name, u_lastname, e_mail, password, age, gender, reg_date)" +
" VALUES (" +
req.name + ","+
req.lastname + ","+
req.login + ","+
req.pass + "," +
req.age + ","+
req.gender + ","+
new java.sql.Timestamp(new java.util.Date().getTime()) + ")";
result = stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) DatabaseManager.closeConnection(connection);
}
return new RegisterResp(result);
}`
Main page HTML file:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Market start page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="./resources/css/app.css">
</head>
<body ng-controller="UserController">
<div style="background: #8fb9ee" class="jumbotron">
<h1>Market homepage</h1>
<h2>Welcome!</h2>
<p align="center">
Register
Log in
</p>
</div>
<hr>
<div >
<ul>
<p style="font-size: xx-large" >Total user count: {{users.length}} </p>
<table class="TableStyle">
<tr class="RowHeaderStyle">
<th >Firstname</th>
<th >Lastname</th>
<th >E-mail</th>
<th >Age</th>
<th >Gender</th>
</tr>
<tr ng-repeat="user in users" class="RowStyle">
<td >{{user.name}}</td>
<td >{{user.lastname}}</td>
<td >{{user.e_mail}}</td>
<td >{{user.age}}</td>
<td >{{user.gender}}</td>
</tr>
</table>
</ul>
</div>
<input type="checkbox" ng-model="value"> admin ?
<div ng-if="value">Admin</div>
<div ng-if="!value">User</div>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-resource.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-route.js"></script>
<script src="./resources/js/app.js"></script>
</body>
</html>
Register HTML-file:
<h2>Register</h2>
<div ng-controller="RegisterController" align="center" class="container-fluid">
<table >
<tr>
<td>First name</td>
<td><input type="text" ng-model="fname"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" ng-model="lname"></td>
</tr>
<tr>
<td>E-mail</td>
<td><input type="text" ng-model="uemail"></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="text" ng-model="upass"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<select ng-model="ugend" >
<option>male</option>
<option>female</option>
</select>
</td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" ng-model="uage"></td>
</tr>
</table>
<button role="button" ng-click="AddUser()"> Confirm </button>
</div>
And app JS file with my silly tries to do something:
`angular.module('app', ['ngResource', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: './resources/partials/login.html',
controller: 'RegisterController'
}).
when('/register', {
templateUrl: './resources/partials/register.html',
controller: 'LoginController'
}).
otherwise({
redirectTo: '/'
});
}])
.controller('UserController', ['$scope', '$resource', function($scope, $resource) {
var User = $resource('/r/users');
var users = User.query(function() {
$scope.users = users;
});
}])
.controller('LoginController', ['$scope', '$resource', function($scope, $resource) {
}])
.controller('RegisterController', ['$scope', '$resource',"$http", function($scope,$http, $resource) {
//here should be something smart
$scope.AddUser = function() {
};
}]);`
I'm working in Intellij, and this is my first try to do something, so don't stone me =).
Roughly, your RegisterController should look like this:
.controller('RegisterController', ['$scope', '$resource', function($scope, $resource) {
var auth = $resource('/auth/:action', null, {
login: {
method: 'POST',
params: {
action: 'login'
},
},
register: {
method: 'POST',
params: {
action: 'register'
}
}
});
$scope.AddUser = function() {
// your data consumed from UI
var data = {
name: $scope.name
lastname: $scope.lastname,
login: $scope.login,
pass: $scope.pass,
age: $scope.age,
gender: $scope.gender
};
auth.register(null, data, function(resp) {
// your callback when response is received
// resp variable contains response data sent from server
if (resp.status) {
// registered successfully
} else {
// some error occurred
}
});
};
}]);
If i understood your question correcty. One way to go about that is to create an angular service to perform the ajax post ill paste an example from a current spring-boot angular app im developping. im using es6 but the conecpt is the same
So here is a snippet of the service
class UserService
{
constructor($http)
{
HTTP.set(this, $http);
}
// getGroups(groupId){
// return HTTP.get(this).get(`/api/v1/group/group/?id=${groupId}`).then(result => result.data.objects );
// }
//
// createUserInGroup(groupId,user){
// return HTTP.get(this).post(`/api/v1/group/user/${groupId}`,user);
// }
updateUser(userId,user){
return HTTP.get(this).put(`/api/v1/user/${userId}`, user);
}
You can tell im injecting the $http angular object to be able to perform the request, you'll have to do the same thing if you decide to go with making a service
In The controller, Im injecting the service
class NewGroupController{
constructor($timeout,$modalInstance, groupSvc,currentGroup){
GROUP_SERVICE.set(this, groupSvc);
MODAL_INSTANCE.set(this,$modalInstance);
TIMEOUT.set(this, $timeout);
CURRENT_GROUP.set(this,currentGroup);
With the Group Service in i can call the method and thats it.
Hope it helps

retrieve updated array list from jsp to action class in struts2

I am retrieving database values and putting them in an array list(al). This array list is getting displayed in a JSP page in the form of a table. I want to modify the values in JSP page and update the new value in the database using Struts2. How do i do that?
Main action class
public class HelloWorldAction extends ActionSupport implements SessionAware{
ProjectDb pd;
public ProjectDb getPd() {
return pd;
}
public void setPd(ProjectDb pd) {
this.pd = pd;
}
ArrayList<ProjectDb> al=new ArrayList<ProjectDb>();
public ArrayList<ProjectDb> getAl() {
return al;
}
public String status() throws Exception{
boolean flag=false;
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager
.getConnection("jdbc:ucanaccess://D:\\Db1.mdb");
username=(String) map.get("user");
PreparedStatement ps=conn.prepareStatement(
"SELECT * FROM StaleInGers WHERE (((StaleInGers.mailId)=(Select email from DBA where username='"+username+"' and email='"+email+"')))");
//ps.setString(1,username);
//ps.setString(2,password);
ResultSet rs=ps.executeQuery();
al=new ArrayList<ProjectDb>();
while(rs.next()){
pd =new ProjectDb();
pd.setProject(rs.getString("project"));
pd.setStatus(rs.getString("status"));
pd.setComments(rs.getString("comments"));
al.add(pd);
flag=true;
}
} catch (Exception e) {
System.out.println("Exception : " +e);
}
if(flag==true){
return "success";
}
else{
return "error";
}
}
}
This is POJO class
public class ProjectDb {
private String project,status,comments,email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
This is the JSP page where i display the array list
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4
/loose.dtd">
<html>
<head>
<style type="text/css">
table,td,th {
border: 1px solid green;
width:100%;
}
th {
background-color: green;
color: white;
}
</style>
</head>
<body>
<form action="update">
<table >
<tr>
<th>Project</th>
<th>Status</th>
<th>Comments</th>
</tr>
<s:iterator value="al" id="array" status="alStatus">
<tr>
<td><s:property value="%{project}"/></td>
<td><s:textfield name="array[%{#alStatus.index}].status" value="%{status}" theme="simple"
/></td>
<td><s:textfield name="array[%{#alStatus.index}].comments" value="%{comments}" theme="simple"
/></td>
</tr>
</s:iterator>
</table><br><br>
<input style="opacity: 0.7; border-radius: 5px; border: 0; width: 250px;
height:35px;
font-family: Goudy Old Style; font-size: 22px; background: #00CC80;"
type="submit" value="Submit">
</form>
</body>
</html>
The first that comes in mind is making the table fields of input type, and place the values that come from ArrayList on each input value paramether. After this make an update method (like satus() one), and using your pojo's setters update the input values triggering the update method on form action.
It should look something like this:
Update method in HelloWorldAction:
public void update(ProjectDB prjDb) throws Exception{
boolean flag=false;
PreparedStatement ps = null;
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager
.getConnection("jdbc:ucanaccess://D:\\Db1.mdb");
conn.setAutoCommit(false);
username=(String) map.get("user");
/*Selecting which field would be updated */
if(!"".equals(prjDb.getEmail().trim())){
ps=conn.prepareStatement(
"UPDATE StaleInGers SET email=? WHERE (((StaleInGers.mailId)=(Select email from DBA where username='"+username+"' and email='"+email+"')))");
ps.setString(1,prjDb.getEmail());
}
//else if(...){...} --> Treat all the cases, if email is not empty, and another field is not empty, if only one field is not empty, etc..
int i = ps.executeUpdate();
conn.commit();
if(i>0){ flag=true; }
}
} catch (Exception e) {
System.out.println("Exception : " +e);
}
if(flag==true){
return "success";
}
else{
return "error";
}
}
//Don't forget to close the connection and prepared statement
The fields must be populated from the array on action that gets you into this page (there you can make the updates) as you did in your JSP. This is the Demo example of the update method but it should work, i let you wrote the rest of the code by yourself.
Use var instead of id (that is deprecated) in the Iterator; in your case, it is not even needed BTW.
Ensure in your target action (update) you have a List<ProjectDb> (use the Interface List, not the implementation ArrayList) named array, with getter/setter;
use an <input type="hidden" /> to send the value that you are showing with <s:property />:
<td>
<s:hidden name="array[%{#alStatus.index}].project" value="%{project}" />
<s:property value="%{project}" />
</td>
Previously I need to pass javascript array to action class of struts 2, i tried with json, var arr1=["1", "2", "3"], in
$.getJSON('ajaxSaveDetails', {
javaArray : JSON.stringify(arr1)
}.fail(function(){
$(".error-txt").text("Error occured");
});
In Action class, i written private String javaArray ; and in method
jsonArray = (JSONArray)new JSONParser().parse(javaArray);
I got proper array.

I want to add "Edit" functionality. When I click Edit, it adds a duplicate record instead of editing

This is my Operations.java, products.Java class and Products.jsp file:
In which I implemented the Add and Edit functionality. The add button is working fine but the edit button is adding a duplicate record instead of editing the record. Please tell me how do I implement edit function in my program ?
package metier;
import java.util.ArrayList;
public class Operation {
private ArrayList<Produit> produits = new ArrayList<Produit>();
public ArrayList<Produit> getProduits() {
return produits;
}
public void setProduits(ArrayList<Produit> produits) {
this.produits = produits;
}
public void add(Produit p){
produits.add(p);
}
public void remove(Long id){
for(Produit p:produits){
if(p.getId()==id){ //equals
produits.remove(p);
break;
}
}
}
public void edit(Long id){
for(Produit p:produits){
if(p.getId()==id){
p.getId();
p.getName();
p.getContactno();
p.getSPS();
produits.add(p);
break;
}
}
}
public ArrayList getAll(){
return produits;
}
}
package metier;
public class Produit {
private Long id;
private String name, address, contactNo, SparePartsService;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactno() {
return contactNo;
}
public void setContactno(String contactNo) {
this.contactNo = contactNo;
}
public String getSPS() {
return SparePartsService;
}
public void setSPS(String SparePartsService) {
this.SparePartsService = SparePartsService;
}
public Produit() {
super();
// TODO Auto-generated constructor stub
}
public Produit(String name, String address, String contactNo, String SparePartsService) {
super();
this.name = name;
this.address = address;
this.contactNo = contactNo;
this.SparePartsService = SparePartsService;
}
public Produit(Long id, String name, String address, String contactNo, String SparePartsService) {
super();
this.id = id;
this.name = name;
this.address = address;
this.contactNo = contactNo;
this.SparePartsService = SparePartsService;
}
#Override
public String toString() {
return id + " - " + name + " - " + address + " - " + contactNo + " - " + SparePartsService + " .";
}
public void Show(){
System.out.println(toString());
}
}
<%# page import="web.ProduitBeans"%>
<%# page import="metier.Produit"%>
<%# page import="java.util.Iterator"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Getiteasy.Net</title>
</head>
<body>
<%
ProduitBeans produits;
if(request.getAttribute("modele") != null){
produits = (ProduitBeans) request.getAttribute("modele");
}else{
produits = new ProduitBeans();
}
%>
<h3>Tutorial MVC(Model, View, Controller)</h3>
<h5>Ajouter un nouveau produit</h5>
<form action="prodserv" method="post">
<table border="1" width="45%">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td>Contact No.</td>
<td><input type="text" name="contactNo"></td>
</tr>
<tr>
<td>Spare Parts Service(Yes/No)</td>
<td><input type="text" name="SparePartsService"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Valider"></td>
</tr>
</table>
</form>
<table border="1" width="60%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Contact No.</th>
<th>Spare Parts Service</th>
<th>Option</th>
</tr>
<%
Iterator<Produit> list = produits.getListe().iterator();
while(list.hasNext()){
Produit p = list.next();
%>
<tr>
<td><%=p.getId() %></td>
<td><%=p.getName() %></td>
<td><%=p.getAddress() %></td>
<td><%=p.getContactno() %></td>
<td><%=p.getSPS() %></td>
<td>
<form action="prodserv" method="post">
<input type="hidden" name="id" value="<%=p.getId() %>" >
<input type="hidden" name="action" value="supprimer" >
<input type="submit" value="supprimer"/>
</form>
<form action="prodserv" method="post">
<input type="hidden" name="id" value="<%=p.getId() %>" >
<input type="hidden" name="editaction" value="Edit" >
<input type="submit" value="Edit"/>
</form>
</td>
</tr>
<%
}
%>
</table>
What do you want your edit method to do? Look at your edit method. If you find a product with the ID you are just calling the getter methods and you are doing nothing with the data. After that you are just adding the same object again to your list. You need to define what data you want to edit and then overwrite the data with a setter method. And don't add the object again to your list.
Working with an ArrayList for this purpose is very unefficiant, you will be looping your list many many times which will take longer and longer as your list is growing. Better make use of a Map, it "maps" a key to a value so you can call that value directly by the predefined key and don't have to loop the whole list.
In your Operation class:
change the ArrayList<Produit> produits ... to Map<Long,Produit> = new HashMap<>()
(Also I would recommand you making it static, to ensure the you keep the same list across the board)
Add a private static Long idCounter=0L
Then when you Add a new Produit, do:
public void add(Produit p){
idCounter++;
p.setId(idCounter);
produits.put(idCounter,p);
}
Remove:
public void remove(Produit p){
produits.remove(p.getId());
}
Note.
No idcounter--; here because you don't know if it is the last one in your map, So baicly you will be skipping some id's if you removed alot of elements.
The id of the Produit that you want to remove has to be set on the p parameter.
Edit:
public void edit(Produit p){
produits.put(p.getId(),p);
}
Note.
The ID of the Produit that you want to remove has to be set on the p parameter.
getAll:
public Collection<Produit> getAll(){
produits.values();
}
In your JSP page:
You have to somehow tell your controller what action it has to do. You can do this by using an Action parameter.
You have done this for one case (Delete (=supprimer FR)).
<input type="hidden" name="action" value="supprimer" >
To edit you must do it again, so change:
<input type="hidden" name="editaction" value="Edit" >
to
<input type="hidden" name="action" value="Edit" >
Note. "name"-tag is the name of the parameter like number is the name of the variable Int number.
In your Controller (servlet):
your:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("action") != null) {
op.remove(Long.parseLong(req.getParameter("id")));
}
else { // Recuprer les information
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}
In the "else"-clause of you if-satement that checks if action-parameter is null, you only have the functionality to add a Produit.
you must add:
if(req.getParameter("action").equals("Add")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}else if (req.getParameter("action").equals("Edit")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
Long id = Long.ParseLong(req.getParameter("id"));
op.edit(new Produit(id, name, address, contactNo,SparePartsService));
}
Result:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("action") != null) {
op.remove(Long.parseLong(req.getParameter("id")));
}
// Recuprer les information
else if(req.getParameter("action").equals("Add")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}else if (req.getParameter("action").equals("Edit")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
Long id = Long.ParseLong(req.getParameter("id"));
op.edit(new Produit(id, name, address, contactNo,SparePartsService));
}
}
Note. You must add a new "else if"-clause for every possible action-parameter value that you want to implement.
I advise you to put the functionality that is within these if-clauses in a seperate private function, if not your doPost(...) function will get very long.
Or even better take a look at the Command-patern.

In struts 1.3 how to retrieve data from database and display it using DAO

*M new to struts. I am making simple login page that display username and password by retrieving it from database. I m using DAO.
I have LoginDAO.java, LoginAction.java and Displaydata.jsp pages. *
LoginDAO.java
public boolean login(String user,String pass) throws SQLException
{
Connection con = getConnection();
Statement st;
try {
st = con.createStatement();
st.executeQuery("select * from login where Username='" + user + "' and Password='" + pass + "'");
return true;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
LoginAction.java
public class LoginAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm rf= (DynaValidatorForm) form;
String username = rf.get("username").toString();
String password = rf.get("password").toString();
HttpSession session=request.getSession();
session.setAttribute("user", username);
Login dao= new Login();
if(dao.login(username,password))
{
System.out.println("GOT");
return mapping.findForward("success");}
else
{System.out.println("NOT");
return mapping.findForward("failure");
}
}
}
and also what do i write in Dislpaydata.jsp to display username and password in it dont want any java code in it.
Thankyou
Right. Some time ago I built an application with Struts 1.x and MySql with login.
LoginAction
public ActionForward login( ... ) throws Exception {
String forward;
final String mail = PropertyUtils.getProperty(form, "mail");
final String password = PropertyUtils.getProperty(form, "password");
if (LoginService.getInstance().validate(mail, password)) {
// Do something e.g. put name of user in session
forward = SUCCESS;
} else {
forward = ERROR;
}
return mapping.findForward(forward);
}
LoginService
public boolean validate(final String mail, final String password)
throws ServiceException {
try {
final boolean valid;
// Validate null and empty
// Validate with DB
final UserDAO dao = new UserDAO();
final User user = dao.findByPk(mail);
if (user == null) {
valid = false;
} else {
if (password.equals(user.getPassword())) {
valid = true;
} else {
valid = false;
}
}
return valid;
} catch (DAOException e) {
throw new ServiceException("Error validating user and password.", e);
}
}
UserDAO
private static final String FIND_BY_PK_SQL
= "SELECT mail, name, password, admin FROM user WHERE mail = ?";
public User findByPk(final String mail) throws DAOException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement(FIND_BY_PK_SQL);
ps.setString(1, mail); // PK, NOT NULL
rs = ps.executeQuery();
if (rs.next()) {
return fill(rs);
}
return null;
} catch (final SQLException e) {
throw new DAOException(e);
} finally {
// Close DB resources
}
}
private User fill(final ResultSet rs) throws SQLException {
final User user = new User();
user.setMail(rs.getString("mail"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setAdmin(rs.getBoolean("admin"));
return user;
}
In my case I have a table user with mail as a primary key. There are various forms.
More examples:
Building a Login Application
Struts Login Application Using Action Form Tutorial | DZone
Creating a Email Login Web Application with Struts
e.g. For show the name of variable user in session scope from the database:
LoginAction
if (LoginService.getInstance().validate(mail, password)) {
final HttpSession session = request.getSession();
final User user = UserService.getInstance().getUser(mail);
session.setAttribute("user", user);
forward = SUCCESS;
}
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
Welcome,
<bean:write scope="session" name="user" property="name" filter="false" />
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
</head>
<body bgcolor="#2EFEF7">
<form action="action" method="post" id="formDemo" name="MyForm">
<div id="header">
<h2 style="color: red;">Training</h2>
</div>
<hr>
<h3>Login</h3>
<div id="center" style="padding-top: 50px; padding-bottom: 220px;">
<table align="center">
<tr>
<th colspan="2"><h1 style="color: BLUE;">LOGIN</h1></th>
</tr>
<tr>
<th colspan="2"><h5 id="error" style="color: red;"></h5></th>
</tr>
<tr>
<td>UserID:</td>
<td><input type="text" size="40" name="UserId" maxlength="8"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" size="40" name="Password" maxlength="8"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Login"> <input type="button" id="reset"
value="Clear"></td>
</tr>
</table>
</div>
<hr>
<div id="footer">
<label>Copy right# 2000-2008 FUJINET, All Rights Reserved.</label>
</div>
</form>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate() {
if (document.MyForm.UserId.value === ""
|| document.MyForm.UserId.value === null) {
document.getElementById("error").innerHTML = "Please insert userId";
return false;
}
if (document.MyForm.Password.value === ""
|| document.MyForm.Password.value === null) {
document.getElementById("error").innerHTML = "Please insert password";
return false;
}
return (true);
}
$("#reset").click(function(event) {
document.MyForm.UserId.value = "";
document.MyForm.Password.value = "";
document.getElementById("error").innerHTML = "";
});
$("#formDemo").submit(function(event){
return validate();
});
</script>
</body>
</html>

Categories

Resources