Java: error parsing datetime (JSP, servlets) - java

I am trying to read a datetime value from a JSP form in my servlet:
ConcertController:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if ("add_concert".equals(action)) {
Concert concert = new Concert();
...
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
java.util.Date parsed = new java.util.Date();
try {
parsed = format.parse(request.getParameter("concert_datetime"));
} catch (ParseException e) {
e.printStackTrace();
}
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
concert.setConcertTime(sqlDate);
..
));
concert.setTicketprice(Double.parseDouble(request.getParameter("concert_ticketprice")));
ConcertTable.insertConcert(concert);
request.getRequestDispatcher("ConcertsController?action=get_all_concerts").forward(request, response);
}
}
.jsp:
<form action="ConcertController?action=add_concert" method="post"
name="concertAddForm" id="formAddConcert"
enctype="multipart/form-data">
<h2>Add new concert</h2>
<div class="panel panel-success">
<div class="col-md-6 form-group">
<label>Concert name:</label> <input type="text" name="concert_name"
placeholder="Concert Name" class="form-control" required>
</div>
...
<div class="col-md-6 form-group">
<label>Date / Time:</label> <input type="text"
name="concert_datetime" placeholder="dd/MM/yyyy HH:mm"
class="form-control" required>
</div>
</div>
<br> <input type="submit" id="addConcertBtn"
class="btn btn-primary btn-large" value="Add concert">
</form>
but I keep getting an HTTP status 500:
java.lang.NullPointerException
java.text.SimpleDateFormat.parse(Unknown Source)
java.text.DateFormat.parse(Unknown Source)
I tried with 12/12/2000 20:00.
What am I doing wrong?

Eutherpy, if you don't need to upload files in your form, just get rid of
enctype="multipart/form-data"
Since it forces your form to be sent in multipart part format.
Otherwise, if you do need to upload files, there were several answers already.
You can have a look at this answer.

Related

HTTP method POST is not supported by this URL Java servlet

Can someone please tell me why i am getting error:HTTP Status 405 – Method Not Allowed ?
I am trying accomplish that after method doPost() ,user will be redirected to "/logout" controller ,where is invalidate session.
It's funny because method is called ,do everything what should do(update user in database), but after send to user error 405.Another where i use doPost() (for example: LoginController) working well ,but when i try compere and find bug ,i dont see any :<
<div class="container">
<div class="col-md-8 col-md-offset-2">
<form method="post" action="account">
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" class="form-control" id="email"
value="${sessionScope.loggedUser.email}" required aria-describedby="emailHelp"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input name="password" type="password" minlength="5" maxlength="40" required class="form-control"
id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="repeatPassword">Repeat Password</label>
<input name="repeatPassword" type="password" minlength="5" maxlength="40" required class="form-control"
id="repeatPassword" placeholder="Password">
</div>
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Save changes"/>
</form>
</div>
</div>
#WebServlet("/account")
public class AccountController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
String repeatPassword = req.getParameter("repeatPassword");
if (email == null || password == null || repeatPassword == null) {
doGet(req, resp);
return;
}
if (password.equals(repeatPassword)) {
HttpSession session = req.getSession();
User user = (User) session.getAttribute("loggedUser");
user.setEmail(email);
String sha1hexPassword = DigestUtils.sha1Hex(password);
user.setPassword(sha1hexPassword);
UserService service = new UserService();
try {
service.update(user);
} catch (UpdateObjectException e) {
e.printStackTrace();
}
req.getRequestDispatcher("/logout").forward(req, resp);
} else {
req.setAttribute("errorMessage", "Passwords not the same");
req.setAttribute("fragment", "account");
req.getRequestDispatcher("WEB-INF/index.jsp").forward(req, resp);
}
}
}
Thanks for any hint.
Your doGet() method call is inside the server doPost() code. You should redirect the response, doGet is for recieving a GET request and any query string.
Problem solved. Here:
req.getRequestDispatcher("/logout").forward(req, resp);
i should do
resp.sendRedirect(req.getContextPath()+"/logout");
because in "/logout" i have only doGet() method ,and if i use "getRequestDispatcher()" its try to find doPost() method.

How to get Localdate as parameter?

I have a form which looks like this:
<form th:action="#{/viewExpenses}" method="post" class="form-horizontal">
<div class="form-group">
<label for="date" class="control-label col-md-3">Date:-</label>
<div class="col-md-9">
<input type="date" class="form-control" id="date" th:name="date"/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-3 col-md-4">
<button class="btn btn-primary">View Details</button>
</div>
</div>
</form>
Now when I submit this form I wish to get the date value as LocalDate. So on my controller I did:
#RequestMapping(value = "/viewExpenses", method = RequestMethod.POST)
public String expenseDetails(Model model, #RequestParam("date")
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
BigDecimal totalExpense = new BigDecimal(0);
List<Expenditure> e = expenditureService.viewExpenseDetails(date);
for (Expenditure exp : e) {
totalExpense = totalExpense.add(exp.getAmount());
}
model.addAttribute("showExpenditure", true);
model.addAttribute("totalExpense", totalExpense);
model.addAttribute("expenses", e);
return "finance/expensedetails";
}
For now I get date value in my controller as null. I have tried changing pattern of #DateTimeFormat but it is still not working.
what might be the correct way to receive date parameter?
This looks like the binding here is not happening.you can try using spring:form tag and bind the controller object via modelAttribute.

nullpointer in sending json data

I having a problem in sending json data from front end bootstrap to express servlet. Here is what i have tried. I use ajax to send data from my form to servlet class with json. please give my hand to solve this problem .here is my form to register student:
<html>
<head>
<link rel="stylesheet" type="text/css" href="resources/css/bootstrap.min.css">
<script type="text/javascript" src="resources/js/jquery.min.js"></script>
<script type="text/javascript" src="resources/js/bootstrap.min.js"> </script>
<script type="text/javascript">
function registerStudent() {
var firstName = $("#firstName").val();
var lastname = $("#lastname").val();
var phone = $("#phone").val();
var email = $("#email").val();
var studentCode = $("#studentCode").val();
$.ajax({
type : "POST",
url : "/RegisterStudent",
data :{data: "firstName=" + firstName + "lastname=" + lastname + " phone=" + phone + "email=" + email+"studentCode"+studentCode},
success : function(data) {
var ht = data.msg;
$("#resp").html(ht);
},
error : function(data) {
alert("Some error occured.");
}
});
}
</script>
</head>
<body>
<div class="container">
<div class="card " style="width:750px;margin:0px auto">
<div class="card-header">Student Register</div>
<div class="card-body">
<form data-toggle="validator" role="form" method="post" >
<div class="form-group">
<label class="control-label" for="firstName">Name</label>
<input class="form-control" data-error="Please enter name field." id="firstName" placeholder="Name" type="text" required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="lastname" class="control-label">lastname</label>
<input type="text" class="form-control" id="lastname" placeholder="lastname" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="phone" class="control-label">phone</label>
<div class="form-group">
<input type="text" data-minlength="5" class="form-control" id="phone" data-error="fill your phone" placeholder="phone" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label" for="email">email</label>
<textarea class="form-control" data-error="Please enter email field." id="email" placeholder="email" required=""></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="studentCode" class="control-label">studentCode</label>
<div class="form-group">
<input type="text" class="form-control" id="studentCode" data-error="fill your studentCode" placeholder="studentCode" required>
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
<button onclick="registerStudent();" type="button" class="btn btn-success btn-block">Register</button>
<div class="text-center" id="resp" style="margin-top: 14px;"></div>
</div>
</div>
and this is my servletclass for send data to database .
#WebServlet(urlPatterns = "/RegisterStudent")
public class RegisterStudentController extends HttpServlet {
StudentServiceInter service = new StudentServiceImpl();
ObjectMapper mapper = new ObjectMapper();
String json = "";
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Student student = new Student();
req.getSession().setAttribute("student", student);
resp.sendRedirect("/addStudent.jsp");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String jsonData = req.getParameter("data");
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
out.println(jsonData);
out.close();
}
}
Try this...
$.ajax({
type: 'GET',
url: '<?php echo base_url(); ?>"/RegisterStudent"', // your syntax
data: {
'firstName ': firstName ,
'lastName' :lastname,
'phone': phone,
'email' : email,
'studentCode' : studentCode,
},
success : function(data) {
var ht = data.msg;
$("#resp").html(ht);
},
error : function(data) {
alert("Some error occured.");
}
});
One problem is that, client-side, you are not creating json, and server side you try to parse a json. Json format doesn't have equal (=) sign.
A valid object is:
data = {
data: {
firstName: 'Name',
lastName: 'Surname',
phone: '123-4456',
email: 'a#b.c',
studentCode: 12345
}
};
and before sending it you should do JSON.stringify(data).

multipart form-data not working properly

In My JSP page I have three seperating forms with enctype ="multipart/form-data". On each of these forms I am uploading a file.
The first form is uploading the file correctly with type as application/pdf. But, the remaining two forms uploading the files as application/octet-stream.
The code as follows
<div id="form1" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form1" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
<div id="form2" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form2" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
<div id="form3" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form3" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
My Servlet code as
#MultipartConfig(maxFileSize = 16177215)
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(req, res);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String action = request.getParameter("action");
if(action.equals("form1"))
{
Part filePart = request.getPart("file");
if (filePart != null)
{
System.out.println("File Parts Not Null");
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
System.out.println("File name is : "+filename);
inputStream = filePart.getInputStream();
}
}
if(action.equals("form2"))
{
Part filePart = request.getPart("file");
if (filePart != null)
{
System.out.println("File Parts Not Null");
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
System.out.println("File name is : "+filename);
inputStream = filePart.getInputStream();
}
}

Problems with bootstrap form and POST Method

i was making a simple page with a formulary using bootstrap and Eclipse (With JBoss).
Html code(Just < body > part):
<div class="jumbotron">
<div class="container">
<form method="POST" class="form-inline" action="validarIngresoAdmin.htm">
<h4>Ingrese sus datos:</h4>
<input type="text" class="form-control input-sm" placeholder="Email" name="txtEmail">
<input type="password" class="form-control input-sm" placeholder="Password" name="txtPsw">
<button type="submit" class="btn btn-danger">Iniciar sesi&#243n</button>
</form>
</div>
but when i try to get the attributes txtEmail and txtPsw they return null.
Eclipse code:
private void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter pw = response.getWriter();
String email = (String)request.getAttribute("txtEmail");
String pass = (String)request.getAttribute("txtPsw");
}
¿Why 'email' and 'pass' attributes return null?
P.S: Sorry about my english.
Thanks.
To retrieve http variables, you should be using getParameter rather than getAttribute.

Categories

Resources