Unable to format date properly - java

I have an issue with formatting the date.
In my addstudent.jsp file I am asking user ti enter their date of birth. This I am doing using input type="text".Add the format to enter is dd-mm-yyyy. Now I have to store the date in yyyy-mm-dd format as mysql stores in yyyy-mm-dd format.
I did this in addprocess.jsp file. But something is wrong which I do not understand. When I give 08-05-2009 as input, I am getting 2009-01-08
as output to store in mysql database. What am I doing wrong?
This is my addstudent.jsp file.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Adding Student</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function validateform(){
var errorString="";
var name=document.myform.name.value;
var email=document.myform.email.value;
var parentemail=document.myform.parentemail.value;
if (name==null || name=="" || !(/^[A-Za-z\s]+$/.test(name))){
document.getElementById("error").innerHTML=errorString+"Name can have only alphabets and spaces";
return false;
}
function validateEmail(email){
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)| (".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if(!validateEmail(email)){
document.getElementById("error").innerHTML=errorString+" Your email is not valid";
return false;
}
if(!validateEmail(parentemail)){
document.getElementById("error").innerHTML=errorString+" Your parent's email is not valid";
return false;
}
}
</script>
</head>
<body>
<div id="outer">
<%#include file="header.jsp" %>
<%# page import="java.util.*"%>
<%# page import="java.util.regex.*"%>
<%#page import="java.sql.*"%>
<div id="error"></div>
<div id="main">
<div id="box">
<form name="myform" method="post" action="addprocess.jsp" onsubmit="return validateform();">
<table>
<tr><td style="color:navy;"><B> Login Form</B></td> </tr>
<tr><td><br></td></tr>
<tr><td>User Name:</td><td><input type="text" name="name" placeholder="Enter your name"/></td></tr>
<tr><td><br></td></tr>
<tr><td>Email Id:</td><td><input type="text" name="email" placeholder="Enter Email ID"/></td></tr>
<tr><td><br></td></tr>
<tr><td>Parent Email Id:</td><td><input type="text" name="parentemail" placeholder="Enter Parent's Email ID"/></td></tr>
<tr><td><br></td></tr>
<tr><td>Date Of Birth:</td><td><input type="text" name="dateofbirth" placeholder="dd-mm-yyyy"/></td></tr>
<tr><td><br></td></tr>
<tr><td>Address:</td><td><input type="text" name="address" placeholder="Enter your address"/></td></tr>
<tr><td><br></td></tr>
<tr><td> </td><td><input type="submit" value="Sign in"></td></tr>
</table>
</form>
<br>
</div>
</div>
</div>
</body>
</html>
And this is addprocess.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<%# page import="java.util.*"%>
<%# page import="java.util.regex.*"%>
<%#page import="java.sql.*"%>
<%#page import="java.text.ParseException"%>
<%#page import="java.text.SimpleDateFormat"%>
<%#page import="java.text.DateFormat"%>
<%#page import="java.util.Date"%>
%>
<%
String name=request.getParameter("name");
String email=request.getParameter("email");
String parentemail=request.getParameter("parentemail");
SimpleDateFormat format = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date util_Date = format.parse( request.getParameter("dateofbirth") );
java.sql.Date dateOfBirth = new java.sql.Date( util_Date.getTime() );
System.out.println(dateOfBirth);
String address=request.getParameter("address");
%>
</body>
</html>
Thanks in advance.

"mm" in date formatting is minute; "MM" in date formatting is month.

Related

How can i get the data of the input hidden field whose name equals to a method and a string in java

Here is a sample jsp page with a form.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="h.abc" %>
<%
abc p = new abc();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="abcd.jsp" method="POST">
<input type="hidden" name="<%=p.getName()%>+'Name'" value='y'>
<input type='text' name='<%=p.getName()%>' >
<input type='submit' value='submit'>
</form>
</body>
</html>
Here is the abc class in the 'h' package.Please pardon the naming.It's only for illustration purposes.
public class abc {
public String name="abc";
public abc()
{
}
public String getName()
{
return name;
}
}
And this is the abcd.jsp target page.Here i am trying to get the value of the input field.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="h.abc" %>
<%
abc p = new abc();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String s = p.getName();
out.println(request.getParameter(s+"Name"));
out.println(request.getParameter(s));
%>
</body>
</html>
I am unable comprehend why the input field is not returning 'y' as its value.rather it is returning null.
change the code in first jsp
<input type="hidden" name="<%=p.getName()%>Name" value='y'>
you need put your abc instance in HttpServletRequest'attributes by calling setAttribute("you_key", abcInstance) method. And then you can get abc instance in your jsp pages by calling req.getAttribute("your_key") or using el expression

Why can't I retrieve an attribute from the Model but I'm able to from JSP?

I'm learning spring mvc and understand the use of the Model and ModelAttribute. However, I can't retrieve the Model's attribute so I resorted to using the JSP param value. What am I doing wrong? I checked the model still had a value for the attribute using #ModelAttribute("username") User user / user.username and sure enough it does.
Controller
package login.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class LoginUser {
#RequestMapping("/")
public String showMenu()
{
return "menu";
}
#RequestMapping("login")
public String loginUser(Model model)
{
User newUser = new User();
model.addAttribute("user", newUser);
return "login-user";
}
#RequestMapping("processUser")
public String processUser(Model model)
{
Option newOption = new Option();
model.addAttribute("option", newOption);
return "process-login";
}
}
User
package login.user;
public class User {
private String username;
private char password[];
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public char[] getPassword() {
return password;
}
public void setPassword(char[] password) {
this.password = password;
}
}
login-user.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value="/resources/css/style.css" />" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login User</title>
</head>
<body>
<div>
<form:form action="processUser" modelAttribute="user">
<table>
<tr>
<td>Username:</td>
<td>
<form:input path="username" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<form:input type="password" path="password" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="Login" />
</td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
process-login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="option">
<h3>Welcome ${param.username}. Please choose an activity below</h3> <---- changed from ${user.username}
<div>
<form:select path="option">
<form:option value="Email" label="Email"></form:option>
<form:option value="Enter Recipe" label="Enter Recipe"></form:option>
<form:option value="Retrieve Recipe" label="Retrieve Recipe"></form:option>
</form:select>
</div>
</form:form>
</body>
</html>
Just change your last #RequestMapping method as follows:
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user, Model model)
{
Option newOption = new Option();
model.addAttribute("user", user);
model.addAttribute("option", newOption);
return "process-login";
}
Now use ${user.username} in jsp.
The spring model data is stored in the standard Java request scope. If you are trying to get the username, you need to add it in the request scope again. So, you can write the processUser method as follows.
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user,Model model)
{
Option newOption = new Option();
// do stuff with user data
newOption.setUsername(user.getUsername());
model.addAttribute("option", newOption);
return "process-login";
}
So, you should be able to get it in the jsp as ${option.username}.

data is not print on tabe

Data is not printed in the table
Bean class name is address and user_id_fk is retrieved from user_id with the help of session
#RequestMapping("/address")
public ModelAndView address(HttpServletRequest request , HttpServletResponse response ,ModelAndView modelAndView){
HttpSession session=request.getSession();
String user_id_fk = (String)session.getAttribute("user_id");
UMService a = new UMserviceimp();
address ad=new address();
ad.setUser_id_fk(Integer.parseInt(user_id_fk));
ad=a.addr(ad);
modelAndView.addObject("studentbean",ad);
modelAndView.setViewName("address");
return modelAndView;
}
When we use this then the data is printed to the console:
System.out.println("address" +ad.getUser_id_fk());
System.out.println("line_1"+ad.getLine_1());
System.out.println("line_2"+ad.getLine_2());
System.out.println("line_3"+ad.getLine_3());
System.out.println("city"+ad.getCity());
System.out.println("state"+ad.getState());
System.out.println("pincode"+ad.getPin_code());
System.out.println("country"+ad.getCountry());
System.out.println("address_type"+ad.getAddress_type());
<!--address.jsp-->
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding``="ISO-8859-1"%>
<%#page import="com.cms.org.um.bean.address"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table border="1" align="left">
<tr>
<th>line_1</th>
<th>line_2</th>
<th>line_3</th>
<th>city</th>
<th>state</th>
<th>country</th>
<th>pin_code</th>
<th>address_type</th>
</tr>
<c:forEach items="${studentbean}" var="u">
<tr>
<td>${u.line_1}</td>
<td>${u.line_2}</td>
<td>${u.line_3}</td>
<td>${u.city}</td>
<td>${u.state}</td>
<td>${u.country}</td>
<td>${u.pin_code}</td>
<td>${u.address_type}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
<!-- end snippet -->
To get field value from object "u" you must do something like this:
<c:forEach items="${studentbean}" var="u">
<tr>
<td><%${u.line_1}%></td>
<td><%${u.line_2}%></td>
<td><%${u.line_3}%></td>
<td><%${u.city}%></td>
<td><%${u.state}%></td>
<td><%${u.country}%></td>
<td><%${u.pin_code}%></td>
<td><%${u.address_type}%></td>
</tr>
</c:forEach>

Modifying existing object in one JSP file in another

I want to add another user in registration JSP file to my HashMap which is created in my homepage, but it seems the another HashMap is being created when I'm trying to register user.
How to access the HashMap from homepage JSP file in another?
This is my base class:
package com.jakub.spring;
import java.util.HashMap;
public class registeredUsers {
public HashMap<String, String> userSource;
public registeredUsers() {
userSource=new HashMap<String, String>();
}
public void register(String name, String password) {
userSource.put(name, password);
}
public String userExists(String user) {
String passwordFromSource = userSource.get(user);
if(passwordFromSource != null) {
return passwordFromSource;
}else
return "";
}
}
This is my homepage:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body bgcolor="#CCCFFF">
<form method="post" action="validate.jsp">
<p align="left">Podaj login:</p>
<input type="text" name="name" />
<p align="left">Podaj haslo:</p>
<input type="text" name="password" />
<input type="submit" value="Zaloguj" />
</form>
Rejestracja
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
out.println("Dostepni uzytkownicy w systemie: \n");
out.print(registeredUsers.userSource.keySet());
%>
</body>
</html>
This is my registration page:
<%# page language="java" contentType="text/html; charset=ISO-8859-2"
pageEncoding="ISO-8859-2"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-2">
<title>Konto utworzone</title>
</head>
<body>
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
registeredUsers.register(request.getParameter("name"),request.getParameter("password"));
out.print("Konto zostało utworzone");
out.print(registeredUsers.userSource.keySet());
%>
Powrót do strony glownej
</body>
</html>
Use ConcurrentHashMap instead of HashMap because it's in Application scope and that can be accessed simultaneously by multiple threads at a time and it results in ConcurrentModificationException.
Please have a look at Thread Safe JSP-Servlet Q&A

MVC - Sending Value of a field with request/session via a JSP

I'm trying to make a list of members of type Party, and linking their memberID to an update page which automatically gets the memberID of the one which was clicked.
I've already written code in the servlet to display a view of all of the members, with each of their IDs linked to a page called UpdateParty.jsp however what I want is for the ID clicked to be passed on with the request so that it can be used in the UpdateParty.jsp as a parameter so that the user does not have to enter it.
I'm using postgres for my SQL if anyone wants to know.
Servlet code which produces a list of all party members:
else if (request.getParameter("listallmembers") != null) {
try {
User sessionuser = (User) session.getAttribute("User");
String u = sessionuser.getUsername();
ArrayList<Party> p = new ArrayList<Party>();
ResultSet rs = this.findAllMembers(u);
while (rs.next()) {
Party party = new Party();
party.setMemberID(rs.getString("memberID"));
party.setPartyFirstname(rs.getString("partyFirstname"));
party.setPartySurname(rs.getString("partySurname"));
party.setUsername(rs.getString("username"));
p.add(party);
}
request.setAttribute("members", p);
request.getRequestDispatcher("ViewPartyMembers.jsp").forward(request, response);
} catch (Exception e) {
out.print(e);
e.printStackTrace(out);
}
Code for ViewPartyMembers.jsp:
<%#page import="HolidayExchange.Party"%>
<%#page import="HolidayExchange.User"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<%
List<Party> l = (List<Party>) request.getAttribute("members");
if(l!=null){
out.println("<table>");
out.println("<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>");
for(int i = 0; i < l.size();i++){
out.println("<tr><td>"+ l.get(i).getMemberID() +
"</td><td><a href='UpdateParty.jsp'>"+ l.get(i).getPartyFirstname() +
"</a></td><td>"+ l.get(i).getPartySurname() +
"</td><td>" + l.get(i).getUsername() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}else{
%>
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
<%
}
%>
</body>
</html>
Here's something a little more sane for you. It uses the JSTL Expression Language and tag library.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<c:if test="${!empty members}">
<table>
<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>
<c:forEach items="${members}" var="member">
<tr><td>${member.memberID}</td>
<c:url value="link" value="UpdateParty.jsp">
<c:param name="memberId" value="${member.memberID}"/>
</c:url>
<td>${member.partyFirstname}</td>
<td>${member.partySurname}</td>
<td>${member.username}</td>
</tr>
</c:forEach>
</table>
</c:if>
<c:if test="${empty members}">
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
</c:if>
</body>
</html>
If you want the ID to be available on the UpdateParty.jsp your link should look like:
<a href='UpdateParty.jsp?id=" + l.get(i).getMemberID() + "'>"+ l.get(i).getPartyFirstname()"</a>
So the id property will be available in the JSP as a request parameter.
Anyway, I recommend you not use scriptlet in your JSP and instead point directly to a JSP point to a Controler/Action

Categories