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
Related
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");
//...
I am writing for this problem several times as I am not finding a solution and I really need it today before 12 o'clock. I am want to display a table with data taken from database in AngularJS for front-end and jersey RESTful services for back-end. All i got when I run my project in browser is a blank table. I really really need anyone of you to help me with my code.
list_main.js
var myApp = angular.module('mainApp', []);
myApp.controller('BooksController', ['$scope', '$http', function($scope, $http) {
$scope.bookList = null;
$scope.resMsg = null;
$scope.showBookList = function() {
var urlGetUsers = 'http://localhost:8080/BookCommerce/webapi/list';
var responEC = $http.get(urlGetUsers, {cache: true, transformResponse: function(data, headersGetter) {
try {
var jsonObject = JSON.parse(data);
keepGoing = true;
return jsonObject;
}
catch (e) {
console.log(e);
$scope.resMsg = "Error. Cannot Retrieve Data";
}
return {};
}});//end ajax
responEC.success(function(bookList, status, headers, config) {
$scope.bookList = bookList;
if ($scope.bookList == null || $scope.bookList.length == 0) {
$scope.resMsg = "No Data";
}
});
};
$scope.showBookList();
}]);
index2.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Of Books</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="js/list_main.js"></script>
</head>
<body>
<div class="row" data-ng-controller="BooksController" data-ng-app="myApp" data-ng-init="showBookList()" style="margin: 10px;">
<div class="col-md-7">
<div class="panel panel-primary">
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="exampleone">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="book in bookList">
<td>{{book.book_id}}</td>
<td>{{book.book_title}}</td>
<td>{{book.book_author}}</td>
<td>{{book.book_description}}</td>
<td>{{book.book_price}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
ListDAO.java
public class ListDAO {
public List<Book> findAll() {
List<Book> list = new ArrayList<Book>();
Connection c = null;
String sql = "SELECT * FROM book";
try {
c = ConnectionHelper.getConnection();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionHelper.close(c);
}
return list;
}
protected Book processRow(ResultSet rs) throws SQLException {
Book book = new Book();
book.setBook_id(rs.getInt("book_id"));
book.setBook_title(rs.getString("book_title"));
book.setBook_author(rs.getString("book_author"));
book.setBook_description(rs.getString("book_description"));
book.setBook_price(rs.getInt("book_price"));
return book;
}
}
ListResource.java
#Path("/list")
public class ListResource {
ListDAO dao=new ListDAO();
#GET
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Book> findAll() {
System.out.println("findAll");
return dao.findAll();
}
}
Please HELP me! Thank you!
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.
*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>
In my application I have a username with a textbox, a checkbutton and a password. After entering the username into the textbox, if I click on check button it should search in the MySQL database for the username, if it is available it should display the message if not an other message should be displayed.
How do I do that with JSP?
i tried the follwing code:
<form method="post" name="frm_addUser" action="./adduserserver.jsp"><br><br>
<table width="500px;" border="0" cellpadding="5" cellspacing="1" bgcolor="#f8f8ff" bordercolor="#333366" align="center">
<tr>
<td bordercolor="Gainsboro"><font size="4">User ID</font></td>
<td bordercolor="Gainsboro"><input name="userid" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4"> </font></td>
<!--<td><input value="Check availability" onclick="" class="btn_checkavail" type="button"></td></tr>-->
</td>
<td>
<input type="submit" value="check" name="check"
onclick="" /></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Pass Word </font></td>
<td bordercolor="Gainsboro"><input name="password" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Confirm Password </font></td>
<td bordercolor="Gainsboro"><input name="confirmpassword" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<%
try{
String username=request.getParameter("username");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","sumith");
st=con.createStatement();
sqlQuery="select distinct username from usernameexist where username='"+username+"'";
rs=st.executeQuery(sqlQuery);
int count=0;
while(rs.next())
{
count++;
}
if(count>0)
{
out.println("<html>");
out.println("<head>");
out.println("<title>MeterDetailsPage</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center' color='red'>");
out.println("<tr color='red'>");
out.println("<td ><font size=4 color=red >username Already Exist</font></td>");
out.println("</tr>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
else
{
if(username!=null )
{
if(!username.equals(""))
{
//st.executeUpdate("insert into usernameexist(username) values('"+username+"')");
out.println("<html>");
out.println("<head>");
out.println("<title>username</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center'>");
out.println("<tr>");
out.println("<td ><font size=4 color=green><b>available </b></font></td>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
}
}
st.close();
con.close();
}
catch(Exception e){}
%>
</table>
</form>
</body>
</html>
Try This it will work,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Index Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>
Enter Your Name: <input type="text" id="name" /><br>
Enter our user name :<input type="text" id="userName"><br>
Enter your Password :<input type="password" id="password"><br>
<input type="button" value="Submit" onclick="ajaxCall();">
<br>
<strong> Response</strong>:
<div id="ajaxGetUserServletResponse"></div><br>
</body>
</html>
Ajax file
function ajaxCall(){
var name = jQuery("#name").val();
var userName = jQuery("#userName").val();
var password= jQuery("#password").val();
alert(name);
alert(userName);
alert(password);
jQuery.ajax({
url : "GetUserServlet",
method: "GET",
type : "JSON",
data : "name="+name+"&userName="+userName+"&password="+password,// query parameters 1st
success : function(response){
$('#ajaxGetUserServletResponse').text(response);
}
});
}
Servlet
import java.io.IOException;
import java.util.ArrayList;
import javax.management.relation.RelationSupportMBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
userBean ub = new userBean();
String name = request.getParameter("name").trim();
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
System.out.println("name catched "+name);
System.out.println("username catched"+userName);
System.out.println("Password catched"+password);
ArrayList<userBean> list = new ArrayList<userBean>();
ub=new userBean();
ub.setName(name);
ub.setUserName(userName);
ub.setPassword(password);
list.add(ub);
response.setContentType("text/plain");
response.getWriter().print(list);
}
}
Pojo Class
public class userBean
{
private String name;
private String userName;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
}
My scenario was little bit different you can alter the code in index.jsp and add the call on button "Check Availability" and bring the response from servlet.
check your table name in query
select distinct username from usernameexist where username='"+username+"'";
make sure your table is usernameexist
and
String username=request.getParameter("username");
here parameter is userid not username
so use
String username=request.getParameter("userid");
Your should do below :
Make sure that your jsp is passing all fields including checked field to servlet. You can do form post which has all attributes.
Your servlet should read all parameters and if check-box is checked then you put appropriate logic in servlet (like querying your MySQL db)
Return proper response from your servlet so that jsp can show appropriate message. You can keep messages in your jsp/js and based on flag you can show appropriate message to user.
you can use as follows.. attach jquery file in source code
<script src="jquery-1.9.1.js">
IN Form
<input type="text" name="userName" id="userName" onBlur="checkId(this.value)">
<span id="status"></span>
<script type="text/javascript">
function checkId(member_id)
{
$.ajax({
type: "POST",
url: "processAjax.jsp", /* The request will be processed in this file.. */
beforeSend: function() {
$("#divIdStatus").html("geting name...");
},
data: "member_id=" + member_id ,
success: function(msg) {
$("#divIdStatus").html(msg);
}
});
}
IN processAjax.js
String member_id = (request.getParameter("member_id")).trim();
if (member_id.equals("")) {
out.print("! This is Required");
} else {
ResultSet result = // check in database if any record with this user name;
if (result.next()) {
out.print("! Not Available");
} else {
out.print("OK..");
}
}