Java Servlet not receiving values from JSP Form - java

This is my first time setting up a Java Servlet, I am trying to retrieve values into my Java Servlet from my input fields in my JSP Form when the user clicks a specific button. I also, am unsure if I used the proper practice for creating my Servlet. I simply right-clicked on my Apache Tomcat 8.0 server and then selected new Servlet.
Java Servlet:
#WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 3719628899527775749L;
public loginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// do some processing here...
// get response writer
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Your username is: " + username + "<br/>";
htmlRespone += "Your password is: " + password + "</h2>";
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
}
}
JSP:
<form name="loginForm" action="loginServlet" method="post" id="loginForm">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button id="loginButton" name="loginButton" type="submit">Login</button>
<button id="registerButton" name="registerButton" type="button">Register</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>

Your request attribute's name are uname and psw which are added on Jsp page. So you must change your doPost method like this.
String username = request.getParameter("uname");
String password = request.getParameter("psw");
Or
You must change your form in jsp page like this:
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>

Related

How to use inputs and post method

I'm starting to learn java web, and i need some insight on why my code isn't working
when i try to submit my code i notice that when i go to the pages where should be an alteration it doesn't show anything.
i'll show some code
Post Method
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String titulo = request.getParameter("titulo");
String imagem = request.getParameter("imagem");
String descricao = request.getParameter("descricao");
String categoria = request.getParameter("categoria");
Noticias noticia = new Noticias();
System.out.println(titulo);
noticia.setTitulo(titulo);
System.out.println(descricao);
noticia.setDescricao(descricao);
System.out.println(categoria);
noticia.setCategoria(categoria);
System.out.println(categoria);
noticia.setImagem(imagem);
Noticias.dados.add(noticia);
response.sendRedirect(categoria);
}
Get Method
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
Inputs
<form>
<div class="form-group">
<label for="titulo">Titulo</label>
<input class="form-control" id="titulo" placeholder="Titulo">
</div>
<div class="form-group">
<label for="imagem">Imagem</label>
<input class="form-control" id="imagem" placeholder="Imagem">
</div>
<div class="form-group">
<label for="descricao">Descrição</label>
<input class="form-control" id="descricao" placeholder="Descrição">
</div>
<div class="form-group">
<label for="categoria">Categoria</label>
<input class="form-control" id="categoria" placeholder="Categoria">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
my sysout's dont show any output.
and it doesn't show any alteration on the pages, i guess post isn't being initialized
If you are submitting form you have to mention method and action attributes into form tag.
<form action="servletname" method="post">
That servlet should be present into web.xml too.
You can follow this link https://www.journaldev.com/1877/servlet-tutorial-java

Updating database in JSP

I coded this Java code for my JSP page to update current login details of a user. Code is not showing any errors or exceptions but not updates the MySql database.
Help me to to implement this functionality;
My code:
<%
//variable declaration for encrypt and decrypt
byte [] input ;
byte [] keyBytes = "12345678".getBytes();
byte [] ivBytes ="input123".getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher;
byte[] cipherText;
int ctLength=0;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
if(request.getParameter("submit")!=null){
String cuser=request.getParameter("currentusername");
String user = request.getParameter("username");
String pwd = request.getParameter("password");
String cpwd = request.getParameter("confirmpassword");
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
input = pwd.getBytes();
key = new SecretKeySpec(keyBytes, "DES");
ivSpec = new IvParameterSpec(ivBytes);
cipher = Cipher.getInstance("DES/CTR/NoPadding","BC");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipherText = new byte[cipher.getOutputSize(input.length)];
ctLength+=cipher.update(input, 0, input.length, cipherText, 0);
ctLength+= cipher.doFinal(cipherText, ctLength);
String enpwd = new String(cipherText);
String sql2 = "update webadmin set username=? ,password=? where username='"+cuser+"' ";
if((cuser!=null &&cuser.length()>0)
&& (user!=null &&user.length()>0)
&& (pwd!=null && pwd.length()>0)
&& cpwd!=null && cpwd.length()>0) {
if((pwd.equals(cpwd))){
pst =conn.prepareStatement(sql2);
pst.setString(1, user);
pst.setString(2, enpwd);
pst.executeUpdate();
%>
<script language="JavaScript">
alert("Sucessfully Updated");
</script>
<%
}else{
%>
<script language="JavaScript">
alert("Passwords are not matching try again");
</script>
<%
}
}
}
}
%>
Note: I implement to encrypt the password and store that encrypted password to the database.
HTML form;
<form id="login-form" action="adminpg-mysettings.jsp" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="currentusername" id="currentusername" tabindex="1" class="form-control" placeholder="Current Username" value="" required="">
</div>
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="New Username" value="" required="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="New Password" required="">
</div>
<div class="form-group">
<input type="password" name="confirmpassword" id="password" tabindex="2" class="form-control" placeholder="Confirm New Password" required="">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="submit" id="submit" tabindex="4" class="form-control btn btn-login" value="Save">
</div>
</div>
</div>
</form>
First of, like everyone will tell you, it is a very bad idea to put Java in JSP. The correct way of operating is with a Servlet and requests stored in session. It will prevent malicious sql injections.
Second of, your security constraints should be handled in the web.xml and Servlet, which is best for back-end maintenance. Following good programming practice will prevent you from going crazy over bugging logs.
I can help you implement what you are trying to do with a Servlet, but before I do, I need to know the following:
The obvious: Do you have a Servlet?
Do you use JDBC/JNDI connectivity?
Do you have entity and session classes for user?
Which IDE/framework do you use to develop your app?
What server are you deploying to?
It is the most effective way of accomplishing what you want. Please provide with the answers and I will update my answer with some code :)
public class UpdateController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int id = Integer.parseInt(request.getParameter("id"));
request.setAttribute("id", new StudentDAO().getStudent(id));
request.getRequestDispatcher("update.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
Date dob = Date.valueOf(request.getParameter("dob")); // yyyy-mm-dd
String gender = request.getParameter("gender");
Student s = new Student();
s.setId(id);
s.setName(name);
s.setGender(gender);
s.setDob(dob);
StudentDAO db = new StudentDAO();
db.update(s);
response.sendRedirect("list");
request.setAttribute("students", new StudentDAO().getAll());
// request.getRequestDispatcher("list.jsp").forward(request, response);
}
public void update(Student s) {
try {
String sql = "UPDATE [dbo].[Student]\n"
+ " SET [name] = ?\n"
+ " ,[gender] = ?\n"
+ " ,[dob] = ?\n"
+ " WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, s.getName());
ps.setString(2, s.getGender());
ps.setDate(3, s.getDob());
ps.setInt(4, s.getId());
ps.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Update</title>
<% String id = request.getParameter("id");%>
</head>
<body>
<form action="update" method="post">
<table>
<tr>
<td>ID: <input type="text" name="id"
value="<%=id%>" readonly></td>
</tr>
<tr>
<td>Name: <input type="text" name="name"/></td>
</tr>
<tr>
<td>Gender: <input type="radio" name="gender" value="male"/> Male
<input type="radio" name="gender" value="female"/> Female </td>
</tr>
<tr>
<td>Dob: <input type="date" name="dob" /></td>
</tr>
</table>
<input type="submit" value="Create" />
</form>
</body>

Reading table html rows values to a servlet to another jsp page for editing

I want to get the values for the rows which is then sent to a Java servlet then read by another page and inserts those values into the text boxes for the user to edit and write it back into the text file.
So it gets read by ProductIO which reads the textfile.
Its then entered into a jsp table
<c:forEach var="product" items="${products}">
<tr>
<td ><c:out value='${product.code}'/></td>
<td ><c:out value='${product.description}'/></td>
<td >${product.priceCurrencyFormat}</td>
<td><form action="editproduct" method="post">
<input type="submit" value = "Edit">
</form>
</td>
<td><form action="deleteproduct" method="post">
<input type="submit" value = "Delete">
</form>
</td>
</tr>
</c:forEach>
The User Clicks either the delete or edit button which will then send action to either the deleteproduct servlet or the editproduct servlet(only asking about the edit for now)
The edit product servlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String url = "/editproduct.jsp";
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
String action = request.getParameter("action");
if (action == null) {
action = "editproduct"; // default action
} else if (action.equals("editproduct")) {
String productCode = request.getParameter("productCode");
String descString = request.getParameter("description");
//HttpSession session = request.getSession();
Product product = (Product) session.getAttribute("cart");
if (product == null) {
product = new Product();
}
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}
Which the three Values are put into three text boxes on the editProduct.jsp page(where im having a problem getting the values to insert into the text boxes for it to be written back to the text file with the new information)
<form action="Product" method="post" >
<input type="hidden" name="action" value="add">
<label>Code:</label>
<input type="text" name="code" value='<%=request.getAttribute("code")%>'
required><br>
<label >Description:</label>
<input type="text" name="desc" value='<%=request.getAttribute("description")%>'
required ><br>
<label >Price:</label>
<input type="text" name="price" value='<%=request.getAttribute("price")%>'
required ><br>
<label> </label>
<!--<input type="submit" value="Update Product" class="margin_left">-->
<!--<input type="submit" value="View Product" class="margin_left">-->
<button type="submit">Update</button><br>
I can share more code if needed.
You aren't calling request.setAttribute() with any of the attributes in your Servlet. I assume you meant to add something like
request.setAttribute("code", productCode);
request.setAttribute("description", descString);
request.setAttribute("price", product.getPrice());
Before forwarding the request.

Cannot pass multipart data to servlet when using jsp el

I am passing checkbox values, username , file as parameter to a servlet that uses MultipartRequest class from com.orielly.servlet package. I am using the jsp el in my jsp.
my jsp is
<c:set var="currentUser" value="${currentUser}" />
<div class="container">
<div class="panel panel-default" >
<div class="panel-body">
<div class="panel panel-default">
<div class="panel-body">
<form action="ProcessShareFileReq?username="${currentUser}" method="post" enctype="multipart/form-data">
<h4>Upload file here</h4>
<input type="file" class="form-control" required="required" name="file" value=""/>
<h4 class="page header">Share with</h4>
<ul class="list-group">
<c:forEach var="request" items="${requestList}">
<li class="list-group-item title">
<input type="checkbox" name="usersList" value="${request.senderFullName}" /><strong> ${request.senderFullName} </strong>
</li>
</c:forEach>
</ul>
<label class="label" for ="description">Description(Helps other users understand the content of file)</label>
<textarea id="description" name="fileDescription" rows="10" cols="5"></textarea>
<div class="break"></div>
<input type="submit" class="btn btn-default pull-left" value="Upload">
<input type="reset" class="btn btn-default pull-left" value="Reset">
</form>
</div>
</div>
</div>
</div>
</div>
my servlet
#WebServlet("/ProcessShareFileReq")
#MultipartConfig
public class ProcessShareFileReq extends HttpServlet {
private static final long serialVersionUID = 1L;
private String webTempPath;
public void init( ) {
webTempPath= "C://BEProject/Shared";
//webTempPath = getServletContext( ).getRealPath("/") + "data";
}
//Generates current time suitable for oracle timestamp
private static java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection currentCon =null;
PreparedStatement ps = null;
int result;
//list of users to share with
String[] UserList = request.getParameterValues("usersList");
//logged-in-user's username
String loggedInUser = request.getParameter("username");
//Shared file's description
String fileDescription = request.getParameter("fileDescription");
//adding path according to sharer's user-name
String userPath = webTempPath + "/" + loggedInUser;
//generate directory
boolean success =( new File(userPath)).mkdirs();
//make directory
if(success) {
System.out.println("Directory: " + webTempPath + " created");
}
//Renames file to the 'sharer_receipent_timestamp' pattern
//Get the uploaded file with multipartRequest
//file limit size of 50 MB
MultipartRequest mpr = new MultipartRequest(request,userPath,50 * 1024 * 1024);
//Database create operations.
Enumeration enum1 = null;
try {
currentCon = ConnectionManager.getConnection();
currentCon.setAutoCommit(true);
for(int i=0;i<UserList.length;i++)
{
String shareFileQuery = "insert into sharedfiles values(share_seq.NEXTVAL,?,?,?,?,?)";
ps = currentCon.prepareStatement(shareFileQuery);
//set the values to put in the query
ps.setString(1, loggedInUser);
ps.setString(2, UserList[i]);
enum1 = mpr.getFileNames( );
String filename = mpr.getFilesystemName((String) enum1.nextElement());
ps.setString(3, filename);
ps.setString(4, fileDescription);
ps.setTimestamp(5, getCurrentTimeStamp());
result=ps.executeUpdate();
if(result>0)
{
System.out.println("Database updated \n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
response.setContentType("text/html");
request.setAttribute("username", loggedInUser);
RequestDispatcher rd = request.getRequestDispatcher("/SharedFilesHistory");
rd.forward(request, response);
}
I have annotated the servlet with #MultipartConfig so that it can handle the file parameter.
But after adding this it goes upto to the last line and gives error as
java.io.IOException: Corrupt form data: premature ending
com.oreilly.servlet.multipart.MultipartParser.<init>(MultipartParser.java:207)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:223)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:110)
servlet.share.ProcessShareFileReq.doPost(ProcessShareFileReq.java:104)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
filter.authentication.AuthenticationFilter.doFilter(AuthenticationFilter.java:40)
When remvoving the MultipartConfig it gives a NullPointerException at the for loop since 'UserList' is null since no value is received in servlet from jsp.
Please help
I remember having some little issues when working with MultipartRequest (seems related to some bugs), which made me drop its usage in favor of the native Servelt 3.x Part and which may be a good alternative for you:
Inside your doPost method you can retrieve your file as a Part of the request using its name:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//...
Part filePart = request.getPart("file"); // Retrieves <input type="file" class="form-control" required="required" name="file" value=""/>
InputStream fileContent = filePart.getInputStream(); // Get an InputStream then let the file make its way to your storage location
}

The servlet doesn't come back to the previous page

This is my web servlet. its first job is to retrieve from the db a list of countries and print out in a select form element. for this point everything works. When I click the submit button in the form, I call the servlet through the action="/submit". Let suppose that I don't insert any username then when I submit the form. the validateSignUpForm return `true. Instead to return to signup page, I am in submit page. I don't understand. When the validationErrorFlag is true I should come back to signup page instead to be in submit page again. Where is the error?
#WebServlet(name = "SignUpServlet", urlPatterns =
{
"/signup"
})
public class SignUpServlet extends HttpServlet
{
#EJB
private UtilBeanInterface utilBean;
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
request.setAttribute("CountriesList", utilBean.getContriesList());
request.getRequestDispatcher("/WEB-INF/view/signup.jsp").forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
String confirm_password = request.getParameter("confirm_password");
String email = request.getParameter("email");
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String address = request.getParameter("address");
String city = request.getParameter("city");
String zipcode = request.getParameter("zip_code");
String country = request.getParameter("country");
String homenumber_code = request.getParameter("homenumber_code");
String homenumber = request.getParameter("homenumber");
String mobilenumber_code = request.getParameter("mobilenumber_code");
String mobilenumber = request.getParameter("mobilenumber");
boolean validationErrorFlag = false;
validationErrorFlag = utilBean.validateSignUpForm(username,
password,
confirm_password,
email,
name,
surname,
address,
city,
zipcode,
country,
homenumber_code,
homenumber,
mobilenumber_code,
mobilenumber,
request);
if(validationErrorFlag == true)
{
doGet(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo()
{
return "Short description";
}
}
JSP PAGE
<article class="container_12">
<section id="signupform" class="grid_5">
<h4>Registrazione membri</h4>
<p>(*) Campi richiesti</p>
<h6>I tuoi dati d'accesso su VolaConNoi.it</h6>
<form action="submit" method="POST">
<div>
<label>Username* <span class="advice">(max 16 caratteri)</span></label>
<input type="text" name="username" autofocus>
<c:if test="${!empty usernameInvalid}">
<p class="errorSignUp">Errore: inserisci un username valido</p>
</c:if>
<c:if test="${!empty usernameAlreadyExist}">
<p class="errorSignUp">Errore: l'username è già in uso</p>
</c:if>
</div>
<div>
<label>Password*</label>
<input type="password" name="password">
</div>
<div>
<label>Conferma Password*</label>
<input type="password" name="confirm_password">
</div>
<div>
<label>E-mail*</label>
<input type="email" name="email">
</div>
<br/>
<h6>Dati Personali</h6>
<div>
<label>Nome*</label>
<input type="text" name="name">
</div>
<div>
<label>Cognome/i*</label>
<input type="text" name="surname">
</div>
<div>
<label>Indirizzo*</label>
<input type="text" name="address">
</div>
<div>
<label>Città*</label>
<input type="text" name="city">
</div>
<div>
<label>CAP*</label>
<input type="text" name="zip_code">
</div>
<div>
<label>Paese*</label>
<select name="country">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.iso}">${country.nicename}</option>
</c:forEach>
</select>
</div>
<div>
<label>Fisso</label>
<select name="homenumber_code">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.phonecode}">${country.nicename} (+${country.phonecode})</option>
</c:forEach>
<input type="text" name="homenumber">
</select>
</div>
<div>
<label>Mobile*</label>
<select name="mobilenumber_code">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.phonecode}">${country.nicename} (+${country.phonecode})</option>
</c:forEach>
</select>
<input type="text" name="mobilenumber">
</div>
<div>
<input type="submit" value="Registrati"/>
</div>
</form>
<div id="signupfooter"></div>
</section>
</article>
Compare:
#WebServlet(name = "MainControllerServlet",
loadOnStartup = 1,
urlPatterns = {"/signup",
"/submit"})
with:
String url = "/WEB-INF/view" + userPath + ".jsp";
Even if userPath = "/signup"; you'll never get to the signup servlet, because you appeneded that ".jsp" in there.
Also, if you ever did get to /signup it looks like it would be an infinite loop forwarding to itself over and over.
BTW, it would probably be a lot simpler to actually make separate servlets for each different operation than to double up on them and do this kind of string manipulation.

Categories