When i try to send email with following code it shows me exception
Exception or Error:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
Code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="java.io.*" %>
<%# page import="java.lang.Object" %>
<%# page import="java.sql.*" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.util.*"%>
<%# page import="javax.mail.*"%>
<%# page import="javax.mail.internet.*"%>
<%# page import="javax.activation.*"%>
<% /*
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require "PHPMailer.php";
require "Exception.php";
require "SMTP.php";
session_start();
session_destroy();
session_start();
$_SESSION['mail']="";
?>
<?php
$cookie_name = "mail";
$cookie_value = $_POST['mail'];
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
// $_SESSION['mail']=$_COOKIE[$cookie_name];
?>
*/
%>
<!DOCTYPE html>
<html>
<head>
<!-- Basic Page Info -->
<meta charset="utf-8" />
<title>DeskApp - Bootstrap Admin Dashboard HTML Template</title>
<!-- Site favicon -->
<link
rel="apple-touch-icon"
sizes="180x180"
href="vendors/images/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="vendors/images/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="vendors/images/favicon-16x16.png"
/>
<!-- Mobile Specific Metas -->
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
<!-- Google Font -->
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght#300;400;500;600;700;800&display=swap"
rel="stylesheet"
/>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="vendors/styles/core.css" />
<link
rel="stylesheet"
type="text/css"
href="vendors/styles/icon-font.min.css"
/>
<link rel="stylesheet" type="text/css" href="vendors/styles/style.css" />
<!-- Global site tag (gtag.js) - Google Analytics -->
<script
async
src="https://www.googletagmanager.com/gtag/js?id=G-GBZ3SGGX85"
></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "G-GBZ3SGGX85");
</script>
<!-- Google Tag Manager -->
<script>
(function (w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({ "gtm.start": new Date().getTime(), event: "gtm.js" });
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != "dataLayer" ? "&l=" + l : "";
j.async = true;
j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, "script", "dataLayer", "GTM-NXZMQSS");
</script>
<!-- End Google Tag Manager -->
</head>
<body>
<div class="login-header box-shadow">
<div
class="container-fluid d-flex justify-content-between align-items-center"
>
<div class="brand-logo">
<a href="login.php">
<img src="vendors/images/deskapp-logo.svg" alt="" />
</a>
</div>
<div class="login-menu">
<ul>
<li>Login</li>
</ul>
</div>
</div>
</div>
<div
class="login-wrap d-flex align-items-center flex-wrap justify-content-center"
>
<div class="container">
<div class="row align-items-center">
<div class="col-md-6">
<img src="vendors/images/forgot-password.png" alt="" />
</div>
<div class="col-md-6">
<div class="login-box bg-white box-shadow border-radius-10">
<div class="login-title">
<h2 class="text-center text-primary">Forgot Password</h2>
</div>
<h6 class="mb-20">
Enter your email address to reset your password
</h6>
<form method="POST" action="forgot-password.jsp">
<div class="input-group custom">
<input
type="text"
class="form-control form-control-lg"
placeholder="Email"
name="email"
/>
<div class="input-group-append custom">
<span class="input-group-text"
><i class="fa fa-envelope-o" aria-hidden="true"></i
></span>
</div>
</div>
<div class="row align-items-center">
<div class="col-5">
<div class="input-group mb-0">
<!--
use code for form submit
<input class="btn btn-primary btn-lg btn-block" type="submit" value="Submit">
-->
<button
class="btn btn-primary btn-lg btn-block"
name="reset" type="submit"
>Submit</button
>
</div>
</div>
<div class="col-2">
<div
class="font-16 weight-600 text-center"
data-color="#707373"
>
OR
</div>
</div>
<div class="col-5">
<div class="input-group mb-0">
<a
class="btn btn-outline-primary btn-lg btn-block"
href="login.php"
>Login</a
>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- js -->
<script src="vendors/scripts/core.js"></script>
<script src="vendors/scripts/script.min.js"></script>
<script src="vendors/scripts/process.js"></script>
<script src="vendors/scripts/layout-settings.js"></script>
<!-- Google Tag Manager (noscript) -->
<noscript
><iframe
src="https://www.googletagmanager.com/ns.html?id=GTM-NXZMQSS"
height="0"
width="0"
style="display: none; visibility: hidden"
></iframe
></noscript>
<!-- End Google Tag Manager (noscript) -->
</body>
</html>
<%
String Email="";
try{
// Database Connection Code
String ConnectionUrl="jdbc:mysql://localhost:3306/";
String DbName="rms";
String DbUserName="root";
String DbPassword="";
Connection con=DriverManager.getConnection(ConnectionUrl+DbName,DbUserName,DbPassword);
//Check Connection is Established or not
if(con!=null)
{
System.out.println("Connection Successfully Established");
}
else
{
System.out.println("Connection Not Established");
}
Email=request.getParameter("email");
Statement statement=con.createStatement();
String Sql="SELECT * FROM tbluser where emailid='"+Email+"'";
System.out.println(Sql);
ResultSet resultset=statement.executeQuery(Sql);
if(resultset!= null)
{
if(resultset.next())
{
if(resultset.getString("emailid").equals(Email)){
//destory session if session is already set
//session.invalidate();
try{
//Creating a result for getting status that messsage is delivered or not!
String to="tomail#gmail.com";
String subject="Test Email";
String message="This is a test email sent from JSP.";
String from="mymail#gmail.com";
String pass="XXXXXXXX";
String host="smtp.gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session se = Session.getDefaultInstance(props, null);
MimeMessage mimeMessage = new MimeMessage(se);
mimeMessage.setFrom(new InternetAddress(from));
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
mimeMessage.setSubject(subject);
mimeMessage.setText(message);
Transport transport = se.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("REsult");
//System.out.println(result);
}
else
{
System.out.println("Invalid Mail ID");
}
}
else
{
System.out.println("Email is Invalid");
}
}
}
catch(Exception e){
e.printStackTrace();
}
%>
As you know Google is stop supporting less secure feature and i want to send mail with gmail then how should i implement it ??
And why this is showing error like Could not connect to port what is error??
Is there any error that i am using college/university public wifi??
I am expecting that i need to know why this error occur and what is solution of it?
Related
I have trouble with CSS in JSP pages.
CSS files are not loaded in any page.
I have this JSP page which is a registration form for a student.
I have a page works correctly but that page has no information from my database.
The rest of pages include some lines and some data from the database.
I really don't know where the problem is so I need your help :(
Student form :
<%#page import="java.util.List"%>
<%#page import="tables.Optionn"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="${pageContext.request.contextPath}">
<link href="Style/bootstrap.css" rel="stylesheet" type="text/css">
<link href="Style/font-awesome.css" rel="stylesheet" />
<link href="Style/style.css" rel="stylesheet">
<link href="Style/style-responsive.css" rel="stylesheet">
<% List<Optionn> option = (List<Optionn>) request.getAttribute("option_list");%>
<title>Etudiant</title>
</head>
<body>
<div class="container" id="registration_form">
<form method="post" class="form-login" action="//localhost:8086/GestionPfe/reg_etudiant">
<h2 class="form-login-heading" >ajouter un Etudiant!</h2>
<div class="login-wrap">
Option: <br> <select name="opt" class="form-control">
<%for (Optionn tempop : option) {%>
<option value=<%=tempop.getIdOption()%> > <%=tempop.getNomOption()%></option>
<%}%>
</select><br>
Nom: <br> <input name="nom_etudiant" type="text" class="form-control">
<br>
Prenomt: <br> <input name="prenom_etudiant" type="text" class="form-control">
<br>
Niveau: <br> <input name="niveau_etudiant" type="text" class="form-control">
<br>
Date De Naissance: <br><input name="date_naissance_etudiant" type="date" class="form-control">
<br>
Numero D'inscription: <br> <input name="num_inscription_etudiant" type="text" class="form-control">
<br>
Adresse: <br> <input name="adresse_etudiant" type="text" class="form-control">
<br>
Email: <br><input name="email_etudiant" type="email" class="form-control">
<br>
Mot De Pass: <br><input name="mot_de_pass_etudiant" type="password" class="form-control">
<br>
Telephone: <br><input name="telephone_etudiant" type="text" class="form-control">
<br>
<button type="submit" class="btn btn-theme btn-block"><i class="fa fa-lock"></i> SIGN IN</button>
</div>
</form>
</div>
</body>
</html>
Student Servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String op= request.getParameter("opt");
String nom_etudiant= request.getParameter("nom_etudiant");
String prenom_etudiant= request.getParameter("prenom_etudiant");
String niveau_etudiant= request.getParameter("niveau_etudiant");
String num_inscription_etudiant= request.getParameter("num_inscription_etudiant");
String date_naissance_etudiant= request.getParameter("date_naissance_etudiant");
String adresse_etudiant = request.getParameter("adresse_etudiant");
String email_etudiant = request.getParameter("email_etudiant");
String mot_de_pass_etudiant = request.getParameter("mot_de_pass_etudiant");
String telephone_etudiant = request.getParameter("telephone_etudiant");
try {
int idop=Integer.parseInt(op);
int tel=Integer.parseInt(telephone_etudiant);
SimpleDateFormat simpledate=new SimpleDateFormat("yyy-MM-dd");
Date birthdayDate = simpledate.parse(date_naissance_etudiant);
Optionn opt = new Optionn();
opt = (Optionn) session.get(Optionn.class,idop);
Etudiant etudiant=new Etudiant(opt,nom_etudiant,prenom_etudiant,niveau_etudiant, mot_de_pass_etudiant,num_inscription_etudiant,birthdayDate,adresse_etudiant,email_etudiant,tel);
session.save(etudiant);
session.getTransaction().commit();
session.close();
response.sendRedirect("Jsp/home.jsp");
} catch (ParseException ex) {
Logger.getLogger(reg_agent.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Add ".." to all your path,
<link href="../Style/style.css" rel="stylesheet">
Try this :
try {
int idop=Integer.parseInt(op);
int tel=Integer.parseInt(telephone_etudiant);
SimpleDateFormat simpledate=new SimpleDateFormat("yyy-MM-dd");
Date birthdayDate = simpledate.parse(date_naissance_etudiant);
Optionn opt = new Optionn();
opt = (Optionn) session.get(Optionn.class,idop);
Etudiant etudiant=new Etudiant(opt,nom_etudiant,prenom_etudiant,niveau_etudiant, mot_de_pass_etudiant,num_inscription_etudiant,birthdayDate,adresse_etudiant,email_etudiant,tel);
session.save(etudiant);
session.getTransaction().commit();
session.close();
RequestDispatcher dispatcher = request.getRequestDispatcher("Jsp/home.jsp");
dispatcher.forward(request, response);
} catch (ParseException ex) {
Logger.getLogger(reg_agent.class.getName()).log(Level.SEVERE, null, ex);
}
Below is my code where i would be using to pass data to another domain. I am having this problem where with request.getParameter("accType"); the value could not be retrieved. However , other value is working fine, the names are correct and form has a post method on it, can anybody help me with this? Thanks in advance.
<%--
Document : viewEmployee
Created on : Jan 23, 2018, 12:06:44 AM
Author : AaronLee
--%>
<%#page import="java.sql.ResultSet"%>
<%# page import = "da.employeeDA" %>
<jsp:useBean id="employeeDA" class="da.employeeDA" scope="application" ></jsp:useBean>
<jsp:setProperty name="employeeDA" property="*" />
<%--import domain page--%>
<%# page import = "domain.employee" %>
<jsp:useBean id="employee" class="domain.employee" scope="application" ></jsp:useBean>
<jsp:setProperty name="employee" property="*" />
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%!
ResultSet rs = null;
%>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<%--import css--%>
<link href="font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="css/website.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%--Bootstrap CSS--%>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<title>Account Details</title>
</head>
<body>
<div class="wrapper">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="homepage.jsp">Document</a>
</div>
<ul class="nav navbar-nav">
<li>+ Document</li>
<li class="active">+ Claim</li>
<li>Search Document</li>
<li>Search Claim</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Account<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Log Out</li>
</ul>
</li>
</ul>
</div>
</nav>
<div class="content">
<%
//login session
String username = null;
if (session.getAttribute("username") == null) {
response.sendRedirect("Login.jsp");
username = null;
return;
} else {
username = session.getAttribute("username").toString();
}
%>
<% try {
rs = employeeDA.searchEmployee(username);
} catch (Exception ex) {
ex.getMessage();
}
if (rs.next()) {
%>
<form method="POST" action="viewEmployee.jsp" >
Account Type :<br/>
<input type="text" value="<%=rs.getString("ACCTYPE")%>" name="accType" disabled /><br/><br/>
Employee ID :<br/>
<input type="text" value="<%=rs.getString("EMPLOYEEID")%>" name="employeeID" disabled/><br/><br/>
Name : <br/>
<input type="text" value="<%=rs.getString("EMPLOYEENAME")%>" name="employeeName"/><br/><br/>
Contact Number :<br/>
<input type="text" value="<%=rs.getString("EMPLOYEECONTACTNO")%>" name="employeeContactNo"/><br/><br/>
<div class="panel-group" id="panelGrp">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#collapse1">Password</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">Current Password :<br/>
<input type="text" class="form-control"/><br/>
New Password : <br/>
<input type="password" class="form-control" name="password"/><br/>
Confirm Password : <br/>
<input type="password" class="form-control" /><br/>
<input type="submit" value="Change Password" name="selection" class="btn btn-primary btn-lg btn-square" id="changepw"/>
</div>
</div>
</div>
</div>
<input type="submit" value="Update" id="changepw" name="selection" class="btn btn-primary btn-lg btn-square"/>
</form>
<%}%>
</div>
<div class="footer"></div>
</div>
</body>
</html>
<%if (request.getMethod().equals("POST")) {
if("Update".equals(request.getParameter("selection"))){
try{
employeeDA.updateEmployee(employee);
}catch(Exception ex){
ex.getMessage();
}
}else if("Change Password".equals(request.getParameter("selection"))){
try{
employeeDA.changePassword(username,request.getParameter("password"));
}catch(Exception ex){
ex.getMessage();
}
}
}
out.println(request.getParameter("accType"));
out.println(employee.getAccType());
%>
disabled elements in a form will not be submitted. You may have to use readonly.
Im trying to write information to a database just using jsp pages but I keep running into this error;
information storage was unsuccessful java.sql.SQLException: Must specify port after ':' in connection string
This is the code that I have;
<%#page import="java.sql.*" %>
<%#page import="java.util.Date" %>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Player Register</title>
<link rel='stylesheet' href= 'styles.css'>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2 align="center"> Register</h2>
<form class="my_form" action="playerDisplay.jsp" method="POST">
<fieldset>
<legend>Please Enter Your Details</legend>
<h1 class="h1a">New Player</h1>
<p>
<label class="labela" for="login">Name:</label>
<input type="text" name="Name" id="Name" value="Name"required>
</p>
<p>
<label class="labela" for="login">Surname:</label>
<input type="text" name="Surname" id="Surname" value="Surname"required>
</p>
<p>
<label class="labela" for="login">PPS Number:</label>
<input type="text" name="PPS_Number" id="PPS_Number" value="PPS_Number"required>
</p>
<p>
<label class="labela" for="login">Grade:</label>
<input type="text" name="Grade" id="Grade" value="Grade"required>
</p>
<p>
<label class="labela" for="login">Email:</label>
<input type="text" name="Email" id="Email" value="Email"required>
</p>
<p>
<label class="labela" for="password">Password:</label>
<input type="password" name="password" id="Password" value="123456"required>
</p>
<p>
<input type="checkbox" name="mailingList" value="yes">Yes, add me to your mailing list<br>
</p>
<div style="text-align: center">
<input type="submit" name="submit">
<input type="reset" name="reset">
</div>
</fieldset>
</form>
</body>
</html>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="CSS/styles.css" rel="stylesheet" type="text/css"/>
<script src="js/libs/jquery/jquery.js"></script>
<style>
table, td, th {
border: 1px solid black;
}
td {
padding: 15px;
}
#optionalFieldset {
display: none;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Your Space</title>
<link rel='stylesheet' href= 'styles.css'>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
$(document).ready(function () {
$("#optionalCheck").click(function () {
$("#optionalFieldset").slideToggle("slow");
});
});
</script>
</head>
<body>
<fieldset>
<legend>Your Info</legend>
<%
String Name=request.getParameter("Name");
String Surname=request.getParameter("Surname");
String PPS_Number=request.getParameter("PPS_Number");
String Grade=request.getParameter("Grade");
String Email=request.getParameter("Email");
String Password=request.getParameter("Password");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn=DriverManager.getConnection("jdbc:mysql://http://danu6.it.nuigalway.ie:3306/mydb1899/players", "mydb1899a", "mydb1899a");
PreparedStatement ps = conn.prepareStatement("INSERT INTO players(Name,Surname,PPS_Number,Grade,Email,Password) VALUES(?,?,?,?,?,?)");
ps.setString(1,Name);
ps.setString(2,Surname);
ps.setString(3,PPS_Number);
ps.setString(4,Grade);
ps.setString(5,Email);
ps.setString(6,Password);
ps.executeUpdate();
out.println("Your information was successfully stored in our database");
conn.close();
ps.close();
}
catch(Exception e) {
out.println("information storage was unsuccessful " + e);
}
%>
</fieldset>
Home
</body>
</html>
Is there any way that I can do it this way and if so is there a solution to the error I have?
I think you do not want the http:// in there, for a proper URL you would want either MySQL:// -OR- http:// not both.
I am guessing your proper string is going to be :
jdbc:mysql://danu6.it.nuigalway.ie:3306/mydb1899/players
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
That is the format for connection URLs. Does yours work with that?
I want to add payments to my clients database but when I add the payments I got this error "GET NOT SUPPORTED" I don't know what's the problem. Can you guys help me?
#Controller
public class PaymentsController {
#Autowired
private UsersService usersService;
#Autowired
private PaymentsService paymentsService;
#RequestMapping(value = "/addPayments", method = RequestMethod.POST)
public String addPayments(HttpServletRequest request, ModelMap map) {
String user = request.getParameter("userId"); // this is the identifier for the user of this payment
String transactName = request.getParameter("transactName");
String paid = request.getParameter("paid");
String unpaid = request.getParameter("unpaid");
String balance = request.getParameter("balance");
String total = request.getParameter("total");
//.... get all other attributes you've passed from the form through request.getParameter("");
//next, check whether or not a user with the userId from the screen exists in the db
Users userObject = usersService.getUsers(user);
//.getUsersByUserId(user);
if (userObject != null) {
// this means that we have a valid user to insert the payment to
UsersPayments payment = new UsersPayments();
payment.setUsers(userObject);
payment.setTransactName(transactName);
payment.setPaid(paid);
payment.setUnpaid(unpaid);
payment.setBalance(balance);
payment.setTotal(total);
//.... set the other properties of UsersPayment object
paymentsService.addPayments(payment);
}
else {
// you have an error right here
}
map.put("paymentsList", paymentsService.getAllPayments());
return "payments";
}
}
payments.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# include file="/WEB-INF/jsp/includes.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="<c:url value="/resources/css/design.css" />" rel="stylesheet">
<link href="<c:url value="/resources/css/customized.css" />" rel="stylesheet">
<link href="<c:url value="/resources/css/bootstrap.css" />" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Canadian Immigration Consultancy</title>
</head>
<body>
<div id="wrapper">
<div id="logo">
<img src="<c:url value="/resources/images/logo4.png" />" height="200px" width="230px"/>
<img src="<c:url value="/resources/images/header06.jpg" />" height="200px" width="765px"/>
</div>
<div class="red">
<div align="center" id="slatenav">
<ul>
<li>Home</li>
<li>View All</li>
<li>Reports</li>
<li>Add Leads</li>
<li><spring:message code="user.logout"/></li>
</ul>
</div>
</div>
<div id="balance" >
<form action="addPayments" method="POST">
<div class="well well-sm box16">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Payments</h3>
</div>
<div class="panel-body">
<div class="form-group">
<br><div class="col-sm-2 control-label">Transaction Name</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="transactName" autofocus />
</div>
</div>
<div class="form-group">
<br><div class="col-sm-2 control-label">Amount Paid</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="paid" />
</div>
</div>
<div class="form-group">
<br><div class="col-sm-2 control-label">Unpaid</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="unpaid" />
</div>
</div>
<div class="form-group">
<br><div class="col-sm-2 control-label">Total Balance</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="balance" />
</div>
</div>
<div class="form-group">
<br><div class="col-sm-2 control-label">Total Amount</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="total" />
</div>
</div>
<div class="save">
<input type="submit" class="btn btn-success" value="Save" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>
You only seem to have one handler mapping, and it's POST. Add another handler mapping for the same url path with GET. Consider the "POST Redirect GET" pattern as well.
In my web application, I have a home page where the options available to the user are placed in a fixed sidebar in the top of the screen, and each one of this options are opened inside of a tag <div> in this same page.
My problem is: when this content is a form, and I submit it to the server, after the processing, the output page isn't opened in this <div>, but in the entire navigation space. What I want is a way of capture this return and display it in the same <div> it was originated.
the code for my home page is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<title>HorarioLivre</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="navbar-fixed-top.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body onload="close_page()">
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HorarioLivre</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Evento</li>
<li>Lista Horarios</li>
<li>Cadastra Horarios</li>
<li>Usuarios</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
${usuario.nome} <b class="caret"></b>
<ul class="dropdown-menu">
<li>Perfil</li>
<li>Configurações</li>
<li>Sair</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<div class="page-header">
<h1></h1>
</div>
<div class="panel panel-default" id="results">
<div class="panel-heading">
<div align="right"><button type="button" class="btn btn-lg btn-danger" onclick="close_page()">Fechar</button></div>
</div>
<div class="panel-body" id="content">
Panel content
</div>
</div>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function load_page(url){
$('#results').css("display", "block");
$('#content').load(url);
$('#container').draggable();
}
function close_page(){
$('#results').css("display", "none");
$('#content').empty();
}
</script>
</body>
</html>
I am using Spring, and the pages linked here are handled by Controller. By example,the page "cadastra_evento.html" is:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Lista de Eventos</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="alert alert-info">
<strong>Eventos</strong> Segue a lista de eventos cadastrados.
</div>
<div class="container">
<div class="row">
<div class="col-md-3">Nome</div>
<div class="col-md-3">Descrição</div>
<div class="col-md-3">Periodo</div>
<div class="col-md-3">Duração</div>
</div>
<c:forEach var="item" items="${lista}">
<div class="row">
<div class="col-md-3"><c:out value="${item.nome}"/></div>
<div class="col-md-3"><c:out value="${item.descricao}"/></div>
<div class="col-md-3"><c:out value="${item.data_inicial}"/> - <c:out value="${item.data_final}"/></div>
<div class="col-md-3"><c:out value="${item.duracao}"/></div>
</div>
</c:forEach>
</div>
<div class="alert alert-info">
<strong>Novo</strong> Cadastre um novo evento.
</div>
<form method="post" action="cad_evento.html">
<input type="text" name="nome" placeholder="Nome" size=20 maxlength=40> <br/>
<input type="text" name="descricao" placeholder="Descrição" size=30 maxlength=100> <br/>
<h3>Periodo da Data</h3>
inicio: <input name="data_inicial" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
final: <input name="data_final" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
<h3>Periodo do Horário</h3>
inicio: <input name="hora_inicial" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
final: <input name="hora_final" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
<input type="text" name="duracao" placeholder="duração" size=20 maxlength=2> <br/>
<button type="submit" class="btn btn-lg btn-primary">Cadastrar</button>
</form>
</body>
</html>
To finish, the page "cad_evento.html" used as action for the form above, is handled by method of same name from Controller:
#RequestMapping(value="/cad_evento", method=RequestMethod.POST)
public ModelAndView cadastra_evento(#RequestParam("nome") String nome, #RequestParam("descricao") String descricao, #RequestParam("data_inicial") String data_inicial, #RequestParam("hora_inicial") String hora_inicial, #RequestParam("data_final") String data_final, #RequestParam("hora_final") String hora_final, #RequestParam("duracao") int duracao) {
if(sessao != null)
{
if(sessao.getUsuario().temAutorizacao("cad_evento"))
{
Date d_inicio = new Date(Date.parse(data_inicial));
Date d_final = new Date(Date.parse(data_final));
Time h_inicio = new Time(Time.parse(hora_inicial));
Time h_final = new Time(Time.parse(hora_final));
EventoDAO evento = new EventoDAO(nome, descricao, d_inicio, d_final, h_inicio, h_final, duracao, sessao.getUsuario());
int saida = evento.cadastra();
if(saida == 0)
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Erro ao cadastrar o evento");
return mav;
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/listagem_evento");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Usuário sem permissão de acesso");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/usuario_login_page");
return mav;
}
}
Someone have any thoughts about how to do that?
Well, spring mvc just open new page with a content you set in ModelAndView. If you want to load somthing just in some part of page ( in this case ) there pure javascript / jquery ajax is needed. So steps needed here:
Add javascript which will do ajax request to controller
Controller need to return JSON ( #ResponseBody can help you )
You have to do some DOM manipulation using javascript/jquery to put JSON answer to your div.