This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 7 years ago.
I have a JSP page with a textarea and a button, a servlet and a new jsp:
My 3 problems are:
My analysis.jsp is empty. My borwser opens a new tab but without the text "Hello World"
The variable "sql" in my java class is empty too. It should contain the text from my textarea
How can I hand over after my variable sql isn't empty (after analyze) new new code to a new jsp
index.jsp
<form action="ServletName" method="post" target="_blank">
<div class="form-group">
<label for="codeEditor" style="margin-top: 15px;">Code:</label>
<textarea name="codeEditor" class="form-control" id="codeEditor" rows="15" style="resize: none;"></textarea>
</div>
<div class="analysisButton">
<button type="submit" id="startAnalysis" class="btn btn-default btn-block" style="margin-top: 10px;">Start analysis</button>
</div>
</form>
ServletName.java
protected void doPost(...) ...{
String sql = request.getParameter("codeEditor");
response.sendRedirect("/analysis.jsp");
}
analysis.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
Many thanks in advance
UPDATE: nevermind the variable sql isn't empty <(^,^<) but the other 2 questions are open :)
Yes, this may be as simple as
JSP
<form action="some_url" method="post" >
<inputarea name="sqlQuery" >
<input type="submit" value="Sql query" >
<form >
In your servlet, you'll have something like
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
...//check that the request is correct
String query = request.getParameter("sqlQuery");//name of textarea
try{
Connection conn = getConnection();//Search SO for how to get a connection
PreparedStatement stmt = conn.prepareStatement(query);
//if your query has any arguments(?) (e.g select * from tbl where id=?), then you should set them too
//stmt.setInt(1, 1000);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
//get database dana here
int someIntVal = rs.getInt("intColumn");
String someStr = rs.getString("someStringColumn");
}catch(SQLException e){
//handle exception
}
}
You could do this using a simple form submit:
<form method="POST" action="/myServletPath">
<inputarea name="sqltext" ...
Your servlet (with url mapping 'myServletPath') can then, in the doPost method:
String sql = request.getParameter("sqltext")...
And then do whatever you want.
WARNING: If this is code for your production application, then be aware of SQL injection attacks. This is typically code you wouldn't write for any application that trusts users other than yourself.
Related
I have a Servlet and jsp project in which it takes the name and pass. when I want it to save it in the MySQL database using JDBC mysql-connector, it shows this error. Please help me I'm stuck in this for a long time.
Screenshots are at the bottom of the page...
I'm using IntelliJ JetBrains and tomcat 10.
__ This is the servlet class π __
#WebServlet(name = "ServletOne", value = "/ServletOne")
public class ServletOne extends HttpServlet {
private Connection con;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
//get all the data incoming from the request(user)..
String name = request.getParameter("user_name");
String password = request.getParameter("user_password");
String email = request.getParameter("user_email");
if (con == null) {
try {
//load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
//create a connection to jdbc
Connection con = DriverManager.getConnection("jdbc:mysql://localhost3306/register", "root", "root");
//query
String q = "insert into user(name, password, email) values(?,?,?)";
PreparedStatement preparedStatement = con.prepareStatement(q);
//set values
preparedStatement.setString(1, name);
preparedStatement.setString(2, password);
preparedStatement.setString(3, email);
//fire query
preparedStatement.executeUpdate();
out.println("<br><h1>ur information have been saved into MySQL Database :)</h1>");
} catch (Exception e) {
e.printStackTrace();
out.println("<h3>An Error has occurred while connecting to MySQL Database.</h3>");
}
} else
out.println("Database connection terminated");
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
__ signup.jsp file π __
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>signup</title>
<!-- importing the css materialize library -->
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<body style="background: url(Images/GenshinMona.jpg); background-size: contain; background-attachment: fixed;">
<div class="container">
<div class="row">
<div class="col m6 offset-m3">
<div class="card">
<div class="card-content">
<h3 style="margin-top:10px;" class="center-align">Register Here</h3>
<%--
creating our own form...
** method is for do and post,
** action is for the servlet class name
--%>
<div class="form center-align">
<form method="post" action="ServletOne">
<input type="text" name="user_name" placeholder="Enter your name">
<input type="password" name="user_password" placeholder="Enter your password">
<input type="email" name="user_email" placeholder="Enter your email address">
<br> <br>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right"></i>
</button>
<br> <br>
<button type="reset" class="reset pink darken-4">Reset All</button>
</form>
</div>
<%--creating our own loader i.e. a circle loading thingy--%>
<div class="loader center-align" style="margin-top: 10px; display: none;">
<div class="progress">
<div class="indeterminate"></div>
<h5>Please wait while we save ur data...</h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<%--Jquery Library--%>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<%--check to see if the jquery library works or not--%>
<script>
$(document).ready(function() {
console.log("Jquery working properly. Page is ready!")
})
</script>
</body>
</html>
__ index.jsp π __
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<h1><%= "Hello World!" %>
</h1>
<br/>
Hello Servlet
</body>
</html>
__ web.xml π __
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
</web-app>
When I comment out the jdbc part, and let's say I want to show all the info, it'll work. But when I want to save it in the database, it refuses and throws exception.
like this π out.println(name + password + email);
================================================================
These are the screenshots of it (both the stackTrace and in the web)π
before submitting:
before submitting..
after submitting..
And the stack traces π
before submitting..
after submitting and the exceptions...
sorry the question has gotten really long. really appreciate your answerπππ
Connection con = DriverManager.getConnection("jdbc:mysql://localhost3306/register", "root", "root");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/register", "root", "root");
i am working on java application where user's login and predict football matches , i create an admin jsp to get all teams name from stored table in database to set this week matches and set the final results later when the matches finish to compare them with users results and calculate points , top users etc ...
my admin.jsp where i choose matches team from jstl foreach loop and set the final result later to compare them with user prediction results.
<%#page import="pws.daoImp.UsersDaoImp"%>
<%#page import="java.lang.String"%>
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="pws.beans.Users"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<% request.getAttribute("admminresult");
%>
<%
List<String> teams1 = new ArrayList();
UsersDaoImp udi = new UsersDaoImp();
List<String> admminresult = new ArrayList();
admminresult = udi.getadminresult();
request.setAttribute("admminresult", admminresult);
List<String> teams = new ArrayList();
teams = udi.getallteams();
request.setAttribute("teams", teams);
%>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Match Prediction</title>
</head>
<body>
<div>
<h1 class="title">Welcome to Match Prediction Site </h1>
<div id="logo" >
<img src="images/cl.png" alt="Smiley face" width="142" height="142">
</div>
</div>
<form action ="AdminUserHandling" method = "post" >
<div class="form-lables">
<h1><select name="clteam1" >
<c:forEach items="${teams}" var="teams" >
<option name="clm1g1" value="${teams}">
${teams}
</option>
</c:forEach>
</select> Vs <select name="clteam1" >
<c:forEach items="${teams}" var="teams" >
<option name="clm1g1" value="${teams}">
${teams}
</option>
</c:forEach>
</select> </h1>
<label for="user_lic">Goals : </label><input id="user_lic" name="clm1g1" type="number" min="" max="10" step="1" value ="1"/>
<label for="user_lic">Goals : </label><input id="user_lic" name="clm1g2" type="number" min="" max="10" step="1" value ="1"/>
</div>
<input type ="submit" value="Submit" />
</form>
</body>
</html>
and my servlet code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UsersDaoImp udi = new UsersDaoImp();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String team1 = request.getParameter("clteam1");
String team2 = request.getParameter("clteam2");
String team1gl = request.getParameter("clteam1gl");
String team2gl = request.getParameter("clteam2gl");
Users user = (Users) request.getSession().getAttribute("user");
System.out.println(team1);
System.out.println(team2);
udi.adminhandling(team1, team2,team1gl,team2gl); //save teams name and goals in database
processRequest(request, response);
}
}
my question is that i set the teams name and final result in admin page jsp but have problem to pass them to users jsp dynamically , iam running out of ideas to do so any help would be much appreciated.
You can use RequestDispatcher.
Defines an object that receives requests from the client and sends
them to any resource (such as a servlet, HTML file, or JSP file) on
the server. The servlet container creates the RequestDispatcher
object, which is used as a wrapper around a server resource located at
a particular path or given by a particular name.
RequestDispatcher rd = request.getRequestDispatcher("/path/to/your/users.jsp"); // mention correct path to your user.jsp here
request.setAttribute("teams",teams);
rd.forward(request, response);
Or
You can set the object into Session.
HttpSession session = request.getSession(false);
session.setAttribute("teams",teams);
This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 3 years ago.
I have a JSP which will let a user register for an account at my website. If the user submits wrong or illegal info into the JSP, then I want to return the same JSP with an appropriate error message next to/above each wrongly filled (form) fields.
If possible, highlight the wrongly filled form field - this feature is not necessary though.
I have given a sample below to show what I need. I understand that the sample must be using something like javascript, but I don't know all that client side scripting. I only want to use JSP to do it. As I said, I want to sort of return the JSP form to the user after marking all the mistakes and how to correct them.
How do I do this ? I only need some initial direction. I will make the code myself and post it here later.
Thanks.
EDIT - I don't want the drop down box. I don't want red borders around wrongly entered fields. I only want to display the error messages (in red color) next to the relevant fields.
Here is some sample code -
<%# page language="java" contentType="blah..." pageEncoding="blah..."%>
<!DOCTYPE html PUBLIC "blah...">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user"><br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
RegServlet -
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static String okUser = "loser";
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(user.equalsIgnoreCase(okUser) == false){
//Do something MAGICAL to set an error next to username field of Form.jsp, then forward.
RequestDispatcher view = request.getRequestDispatcher("/jsp/Form.jsp");
view.forward(request, response);
}
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax Validation</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- or download to a directory -->
<!-- <script src="js/jquery-1.9.1.js"></script> -->
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#user').change(function() {
var userName = jQuery(this).val();
jQuery.ajax({
type : 'GET',
url : 'AjaxUserCheck',
data : {user:userName},
dataType : 'html',
success : function(data) {
if(jQuery.trim(data)=='1')
{
jQuery("#userLabel").html("Sorry! username is taken");
//write other stuff: border color ...
}
else if(jQuery.trim(data)=='0')
jQuery("#userLabel").html("user name available");
else
alert(data); //possible error
},
error : function(xhr,status,error){
console.log(xhr);
alert(status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user" id="user">
<label id="userLabel"></label>
<br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
---------Servlet------
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
//if(dao.isUserExist(user)){
if(user.equals("java")){ // check for db if userid exists in DB print '1' else '0'
out.print("1");
}
else
out.print("0");
have the page post to itself, like this login.jsp fragment:
<div class="error">
<%
String usrName = "" + request.getParameter("username");
String usrPass = "" + request.getParameter("password");
if (isValid(usrName,usrPass){
openUserSession(usrName); //here you open a session and set the user, if the session doesn't have an user redirect to login.jsp
response.sendRedirect("index.jsp"); //user ok redirect to index (or previous page)
} else {
out.print("Invaid user or password");
}
%>
</div>
<form action="login.jsp" method="POST"> <!-- login.jsp post to itself -->
<input type="text" name="username" id="username"/>
<input type="password" name="password" />
<input type="submit" value="login" name="login" />
<input type="submit" value="register" name="register" />
</form>
I have a JSP page :
employee5_searchByName.jsp
<%#page import="java.util.Iterator"%>
<%#page import="java.util.List"%>
<!-- EMPLOYEE wants to search items by their name -->
<!DOCTYPE html>
<html>
<head>
<title>Employee - Search for items by name</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
<script src="js/jquery.autocomplete.js"></script>
<style>
input
{
font-size: 120%;
}
</style>
</head>
<body>
<h1>Employee - Search for items by name</h1>
<h1>
Search for items by name
</h1>
<fieldset>
<legend>Please enter the item's name :</legend>
<form action="Employee5_After">
Item's name : <input type="text" name="prod_name" id="myProduct"><br>
<script>
$("#myProduct").autocomplete("autocompleteFromDb.jsp");
</script>
<input type="submit" value="Register">
</form>
</fieldset>
</body></html>
It forwards to this servlet :
Employee5_After
package controller.employee;
/**
* Retrieve the record of a given product by its name
* using hibernate
* #author X
*
*/
#WebServlet("/Employee5_After")
public class Employee5_After extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// grab the product's name that the user entered
String productName = request.getParameter("prod_name");
// create DB instance
DatabaseInventory inventory = new DatabaseInventory();
// get the details
String details = inventory.getProductDetailsByName(productName);
HttpSession session = request.getSession();
// forward answer to JSP
synchronized(session)
{
if (details != null) // then the product has been found
{
session.setAttribute("foundProd", details);
String addressPath = "/WEB-INF/results/employee/employeeResult5.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(addressPath);
dispatcher.forward(request, response);
}
}
}
}
That servlet is doing his stuff , and then forwards to a 2nd JSP ,called :
employeeResult5.jsp
<!-- Employee - get a description of a product by its name -->
<!DOCTYPE html>
<html>
<head><title>The details for the product you requested are below</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<h1>Here are the details from the product you request :</h1>
<h2>${foundProd}</h2>
<h1>We wish you well - bye bye!</h1>
<fieldset>
<legend>Go back to Employee's web-page</legend>
<form action="blablabla">
Press here to continue
</form>
</fieldset>
</body></html>
I guess that I can use the <% and %> in the JSP to do the logic side of the servlet (contacting to DB and retrieve data) . How can I avoid using a servlet in between , and just pass the data from one JSP to another JSP ?
You can use the request.redirect(URL) method to do it.
Or you can use request. forward(req, resp).
See example
Separate the business logic from the font end, there is no need to redirect to an intermediate servlet. The best practice is to put the business logic in a separate class and instantiate that class in the destination page. Here is one example:
mainPage.jsp - create the page similar to your employee5_searchByName.jsp. Now this page posts the data you enter.
Create a backing class called - dbData.java (DatabaseInventory in your case)- put all your database query here and functions to retrieve what your want. A function like public String searchText(String param) (similar to getProductDetailsByName(productName)) which will essentially fetch your search results from database.
Now the most important part - Instantiate this class in your destination SearchResults.jsp page and show whatever data you get in a manner similar to this:
<%#page import="mysource.dbData"%>
<%
searchParam = request.getParameter("searchStr");
dbData data = new dbData();
String result = data.searchText(searchParam);
%>
<HTML>
<BODY>
The result is: <% out.print(result); %>
</BODY>
</HTML>
The industry standard is to follow an MVC Architecture. Following that will create applications which are clear to understand and easy to maintain.
Try this code to forward with parameteres
<jsp:forward page="URL">
<jsp:param nama="param1" value="hello"/>
<jsp:param nama="param2" value="hello2"/>
<jsp:param nama="param3" value="hello3"/>
<jsp:param nama="param4" value="hello4"/>
.
........... and so on
</jsp:forward
I am new to java.I am creating dynamic web Application in eclipse EE IDE with MYSQL database. I want to connect my database to app so far I have created JSP page for view. Below is my JSP code and Servlet for connection. I am not able to connect to database with this. My JSP page work fine. But I think problem is with Servlet. And also advice to I need to made the two java file one for Servlet and other for getting data from JSP page.
Thanks in advance.
Servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get user_name and pass_word from the JSP page
String toolfirst=request.getParameter("tname1");
String toolsecond=request.getParameter("tname2");
String toolvalue=request.getParameter("tvalue");
//Print the above got values in console
System.out.println("The username is" +toolfirst);
//Setting connection Parameters
String connectionparams=βjdbc:mysql://localhost:3306/toolβ;
//database name
String db=βtoolβ;
//Mysql user name and password whichever you have given during installation
String uname=βrootβ
String psword=ββ
//Declaring classes required for Database support
Connection connection=null;
ResultSet rs;
try {
// Loading the available driver for a Database communication
Class.forName("org.gjt.mm.mysql.Driver");
//Creating a connection to the required database
connection = DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
//Add the data into the database
String sql = "insert into usertable values (?,?)";
PreparedStatement prep =
connection.prepareStatement(sql);
//Setting the values which we got from JSP form
prep.setString(1, tname1);
prep.setString(2, tname2);
prep.executeUpdate();
prep.close();
}catch(Exception E){
//Any Exceptions will be caught here
System.out.println(βThe error is==β+E.getMessage());
}
finally{
//After the entire execution this block will execute and the connection with database gets closed
connection.close();
}
}
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>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="NewServlet">
<a id="add" href="javascript:void(0)">Add another Credit card</a>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr class="person">
<td><input type="text" name="tname1" id="name" /></td>
<td><input type="button" value="name" /></td>
<td><select name="tvalue">
<option>value1</option>
<option>value2</option></select>
<td><input type="text" name="tname2" id="name" /></td>
</tr>
</tbody>
</table>
<input type="submit" value="submit" >
</form>
Logout
</body>
</html>
without having a detailed errormessage I would say that you have a compile error here:
connection = DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
it should be at least:
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tool", root, psword);
btw remove the ResultSet. You dont use it.
You have a comma at the end of this statement with no value after it. I think your number of arguments are incomplete. I also assume the userID and password needs to be somewhere in the argument list.
DriverManager.getConnection(jdbc:mysql://localhost:3306/tool, root, );
Whoops - someone answered the question before I could post this. Guess I need to type faster.