get from address using javamail api? - java

Right now I'm creating email client using javamail API, in which when I click on Reply button then the address of From field is not coming in To field.
DisplayMessage.jsp
<%# page import="user.*" %>
<%# page import="javax.mail.*" %>
<%# page import="javax.mail.internet.*" %>
<%# page import="javax.activation.*" %>
<%# page import="java.io.*" %>
<%
String sendmessage=(String)request.getAttribute("sendmessage");
if(sendmessage==null)
{
sendmessage="";
}
if (session == null) {
response.sendError(404, "Session expired");
return;
}
userinfo info = (userinfo)session.getAttribute("userinfo");
Session sessio = info.getSession();
Store store = sessio.getStore("imap");
store.connect(info.getHostname(),info.getusername(),info.getpassword());
Folder folder = store.getFolder(info.getUrl());
folder.open(Folder.READ_WRITE);
Message[] message = folder.getMessages();
int count = folder.getMessageCount();
int unread = folder.getUnreadMessageCount();
Integer messageno=Integer.parseInt(request.getParameter("messageno"));
%>
<html><head><title>Home Page</title></head>
<body>
<table width="940" bgcolor="#GSDFES">
<tr><td><input type="submit" name="button" class="button" onclick="javascript:deletemail(<%=messageno%>)" value="Delete"/></td>
<tr><td>From : <%= message[messageno].getFrom()[0] %></td></tr>
<tr><td>Subject : <%= message[messageno].getSubject() %></td></tr>
<tr><td>Date : <%= message[messageno].getSentDate() %></td></tr>
<tr><td>ContentType : <%= message[messageno].getContentType() %></td></tr>
<tr><td>
<%
InputStream stream = message[messageno].getInputStream();
while (stream.available() != 0) {
%>
<%
char str=((char)stream.read());
if(str=='\n')
{ %><br/><% continue;} %>
<% if(str==' ')
{ %> <% } %>
<%= str %>
<%
}
%>
</table>
<button class="button" name="reply" onClick="javascript:loadreplymessage(<%=messageno%>)">Reply</button><button class="button" onClick="javascript:loadforwardmessage(<%=messageno%>)" name="forward">Forward</button>
</body>
</html>
Function is written in different file home.jsp:
function loadcomposemail()
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject(Microsoft.XMLHTTP);
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("tableview").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","composemail.jsp",true);
xmlhttp.send();
}
function loadreplymessage(i)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject(Microsoft.XMLHTTP);
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("tableview").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","composereplymail.jsp?messageno="+i,true);
xmlhttp.send();
}
composereplymail.jsp:
<%# page import="user.*" %>
<%# page import="javax.mail.*" %>
<%# page import="javax.mail.internet.*" %>
<%# page import="javax.activation.*" %>
<%# page import="java.io.*" %>
<%
String sendmessage=(String)request.getAttribute("sendmessage");
if(sendmessage==null)
{
sendmessage="";
}
if (session == null) {
response.sendError(404, "Session expired");
return;
}
userinfo info = (userinfo)session.getAttribute("userinfo");
Folder folder=store.getFolder(info.getUrl());
int count = folder.getMessageCount();
int unread = folder.getUnreadMessageCount();
Integer messageno=Integer.parseInt(request.getParameter("messageno"));
Message[] message = folder.getMessages();
String ssubject=message[messageno].getSubject();
**//String from=message[messageno].getFrom()[0]; //program stops working when uncomment this line**
%>
<html><head>
<title>Home Page</title>
<link rel="stylesheet" type="text/css" href="styleforcomposemail.css" />
</head>
<body>
<center>
<form action='sendmail' method='post'>
<table>
<tr bgcolor='#800517'>
<td colspan='2'><b><h3><center>Compose Your Mail Here</center></h3></b></td>
</tr>
<tr height="15" bgcolor='#CFECEC'>
<td><b>From :</td>
<td><label for="login"><%= info.getsendfrom() %></label></td>
</tr>
<tr height="15" bgcolor='#CFECEC'>
<td><b>TO :</td>
<td><input type='text' name='sendto' class='Large' value='' /></b>Add "," For Sending Multiple Mails</td>
</tr>
<tr height="15" bgcolor='#CFECEC'>
<td><b >CC :</td>
<td><input type='text' name='cc' class='Large' /></b></td>
</tr>
<tr height="15" bgcolor='#CFECEC'>
<td><b>Subject :</td>
<td><input type='text' name='subject' class='Large' value='Re : <%=ssubject%>' /></td>
</tr>
<tr bgcolor='#CFECEC'>
<td colspan='2'><textarea id="textAreaa" onmouseover="javascript:setTextToTextArea('<%=data%>')" rows='32' cols='135' name='data' on>
Display Message Data here...come on..!!
</textarea></td>
</tr>
<tr height="15" bgcolor='#CFECEC'>
<td colspan='2'><input type='submit' class='button' name='Submit' value='Submit'/>
<input type='submit' class='button' name='Draft' value='Save As Draft'/>
<input type='reset' class='button' value='Reset' name='Reset'/>
<input type='reset' class='button' value='Discard' name='Reset'/>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

The getFrom() method returns an array of Address objects, not an array of Strings.
Try:
String from=message[messageno].getFrom()[0].toString();
Also, your program is missing all kinds of error handling. In particular,
some messages might not have a From address.

Another way to fetch data from forms is to create id of each field and get by getParameter(): request.getParameter("field-id");
Example: String subject = request.getParameter("subject");

Related

The type java.lang.Charsequence cannot be resolved. It is indirectly referenced from required .class file

<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://jakarta.apache.org/struts/tags-bean"
prefix="bean"%>
<%# taglib uri="http://jakarta.apache.org/struts/tags-html"
prefix="html"%>
<%# taglib uri="http://jakarta.apache.org/struts/tags-logic"
prefix="logic"%>
<%# page import="de.fhg.fokus.hss.db.model.*, java.util.* " %>
<jsp:useBean id="resultList" type="java.util.List" scope="request"></jsp:useBean>
<jsp:useBean id="maxPages" type="java.lang.String" scope="request"></jsp:useBean>
<jsp:useBean id="currentPage" type="java.lang.String" scope="request"></jsp:useBean>
<jsp:useBean id="rowPerPage" type="java.lang.String" scope="request"></jsp:useBean>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" type="text/css" href="/hss.web.console/style/fokus_ngni.css">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><bean:message key="result.title" /></title>
<script type="text/javascript" language="JavaScript">
function submitForm(pageId){
document.IMSU_SearchForm.crtPage.value = pageId;
document.IMSU_SearchForm.submit();
}
function rowsPerPageChanged(){
document.IMSU_SearchForm.crtPage.value = 1;
document.IMSU_SearchForm.submit();
}
</script>
</head>
<body>
<table id="title-table" align="center" weight="100%" >
<tr>
<td align="center">
<h1> IMS Subscription - Search Results </h1>
<br/><br/>
</td>
</tr>
</table> <!-- title-table -->
<table id="main-table" align="center" valign="middle" >
<tr>
<td>
<table id="result-table" class="as" width="600" border="0" cellspacing="1" align="center" style="border:2px solid #FF6600;">
<tr class="header">
<td class="header"> ID </td>
<td class="header"> Name </td>
<td class="header"> S-CSCF Name </td>
<td class="header"> Diameter Name </td>
</tr>
<%
if (resultList != null && resultList.size() > 0){
IMSU imsu;
int idx = 0;
Iterator it = resultList.iterator();
while (it.hasNext()){
imsu = (IMSU) it.next();
%>
<tr class="<%= idx % 2 == 0 ? "even" : "odd" %>">
<td>
<%= imsu.getId() %>
</td>
<td>
<a href="/hss.web.console/IMSU_Load.do?id=<%= imsu.getId() %>">
<%= imsu.getName() %>
</a>
</td>
<td>
<%= imsu.getScscf_name() %>
</td>
<td>
<%= imsu.getDiameter_name() %>
</td>
</tr>
<%
idx++;
} //while
} // if
else{
%>
<tr>
<td>
<bean:message key="result.emptyResultSet" />
</td>
</tr>
<%
}
%>
</table> <!-- result-table -->
</td>
</tr>
<tr>
<td colspan="3" class="header">
<html:form action="/IMSU_Search">
<table id="rows-table" align="center">
<tr>
<td>
<%
int length = Integer.parseInt(maxPages) + 1;
int cPage = Integer.parseInt(currentPage) + 1;
for (int iy = 1; iy < length; iy++) {
if (cPage != iy) {
%>
<%=iy%>
<%
} else {
%>
<font style="color:#FF0000;font-weight: 600;">
<%=String.valueOf(iy)%>
</font>
<% }
}
%>
</td>
<td>
<bean:message key="result.rowsPerPage" /><br>
<html:hidden property="crtPage"></html:hidden>
<html:select property="rowsPerPage" onchange="javascript:rowsPerPageChanged();">
<option value="20"
<%= rowPerPage.equals("20") ? "selected" : "" %> >20 </option>
<option value="30"
<%= rowPerPage.equals("30") ? "selected" : "" %> >30 </option>
<option value="50"
<%= rowPerPage.equals("50") ? "selected" : "" %> >50</option>
<option value="100"
<%= rowPerPage.equals("100") ? "selected" : "" %> >100</option>
</html:select>
</td>
</tr>
</table> <!-- rows-table -->
</html:form>
</td>
</tr>
</table> <!-- main-table -->
</body>
</html>
I am trying to run a appliaction, I am accessing the application through a web interface but at some part I am getting the following error:
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: Unable to compile class for JSP
An error occurred at line: 116 in the jsp file: /pages/user/imsu_search_result.jsp
Generated servlet error:
The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:328)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:397)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:288)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:556)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:293)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1063)
org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:263)
org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:386)
org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:318)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:229)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.
Please find the attached jsp file
Please provide your suggestion to resolve the issue.
Thanks
1) Check your compiler and JVM versions as I believe they mismatch OR
2) Compile your all classes with newer version of 1.8 or
3) downgrade to Java 1.7

login page using session in jsp

I've created a login environment using jsp. index.jsp, login.jsp. I take username and password from database. If user name and password matches with the database it does login process perfectly. When user give wrong name or password it shows a error message invalid name or passwordand redirect to the login page. Nothing's wrong, but I am facing a problem when I login first. The place where the error message is shown after submitting wrong name or password that place is showing null.
Why null is showing?
Below is my code
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Example</title>
</head>
<body>
<form action="login.jsp" method="post">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2" align ="left">Login Here</th> <h5><%=request.getAttribute("errorMessage")%> </h5>
</tr>
</thead>
<tbody>
<tr>
<td>User Name</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" value="" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>
login.jsp
<%# page import ="java.sql.*" %>
<%
String userid = request.getParameter("uname");
String pwd = request.getParameter("pass");
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "postgres", "root");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select * from member where uname='" + userid + "' and pass='" + pwd + "'");
if (rs.next()) {
session.setAttribute("userid", userid);
response.sendRedirect("success.jsp");
} else {
request.setAttribute("errorMessage", "Invalid user or password");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
%>
You can use this in your index.jsp
<% if ((String) request.getAttribute("errorMessage") != null) {%>
<h3 style="color: red;"><%=(String) request.getAttribute("errorMessage")%></h3>
<%
}
%>
Instead of this
<%=request.getAttribute("errorMessage")%>
please check condition before showing error, if request parameter is null then it should not be rendered else it would be rendered, modify you code according to below snippet
<thead>
<tr>
<th colspan="2" align ="left">Login Here</th>
<h5>
<%if(request.getParameter("errorMessage")!=null){%>
<%=request.getParameter("errorMessage")%><%}%>
</h5>
</tr>
</thead>
The errorMessage attribute will not be available in request for the first time. Kindly check for a null and then display the message.
<%=request.getAttribute("errorMessage")%>
The below piece of code could help you.
<tr>
<th colspan="2" align ="left">Login Here</th>
<h5>
<%
String errorMsg = request.getAttribute("errorMessage");
if (errorMsg != null) {
%>
<%=errorMsg%>
<%
}
%>
</h5>
</tr>
As errorMessage attribute is null in the request when you load it first time, so you are getting null. You need to add null check for it. You can do this way
<th colspan="2" align ="left">Login Here</th>
<% if (request.getAttribute("errorMessage") != null) {
out.println("<h5>" + request.getAttribute("errorMessage") + "</h5>");
}%>
Correct your code in login.jsp
write session.setAttribute("errorMessage", "Invalid user or password");
instead of request.setAttribute("errorMessage", "Invalid user or password");
..
null message show because of this.

Getting exception : java.lang.NullPointerException on my jsp page

i am posting my code in which i am getting the java.lang.NullPointerException exception.
<%# page contentType="text/html;charset=UTF-8" %>
<%# page errorPage="myError.jsp?from=customers.jsp" %>
<%# page import="java.sql.*" %>
<html>
<head>
<title>Insurance Quoting System</title>
</head>
<body>
<basefont face="Arial">
<!-- JSP Declarations -->
<%! ResultSet rs = null; %>
<!-- JSP Scriptlet -->
<%
try {
Class.forName("com.mysql.mysql.Driver");
Connection db = DriverManager.getConnection("jdbc:mysql://localhost:3306/quoting","root","root");
Statement s = db.createStatement();
rs = s.executeQuery("select * from customer");
}
catch (Exception e) {
// For now, just report the error to the system log
System.out.println(e.toString());
}
%>
<!-- Template text -->
<table width="550" border="0" align="center">
<tr>
<td bgcolor="#006633">
<div align="center">
<font size="6" color="#FFFFFF">
<b>Insurance Quoting System</b>
</font>
</div>
</td>
</tr>
<tr>
<td>
<p> </p>
<p> </p>
<p align="center"><b>Customers</b></p>
<table width="290" border="0" align="center">
<%
try {
while (rs.next()) {
%>
<!-- JSP Expressions used within template text -->
<tr>
<td width="20"><%= rs.getInt(1) %></td>
<td width="70"><%= rs.getString(2) %></td>
<td width="70"><%= rs.getString(3) %></td>
<td width="40">
<a href="custMaint.jsp?id=<%= rs.getString(1) %>&action=edit">
edit
</a>
</td>
<td width="40">
<a href="custMaint.jsp?id=<%= rs.getString(1) %>&action=delete">
delete
</a>
</td>
<td width="40">
<a href="custMaint.jsp?id=<%= rs.getString(1) %>&action=newQuote">
new quote
</a>
</td>
</tr>
<%
}
}
catch (SQLException e) {
// For now, just report the error to the system log
System.out.println(e.toString());
}
%>
</table>
</td>
</tr>
<tr>
<td>
<p> </p>
<p align="center">New Customer</p>
</td>
</tr>
</table>
</body>
</html>
i am making one jsp page its giving some error java.lang.NullPonterException on my jsp page pls tell me the ans if any one have .
The only thing I can think of that is causing this is that you are catching an exception in your first try-catch block and then trying to use the ResultSet as if it's been initialized, but it's still null, so you are getting NPE. Check to see if your Database operations work correctly.

java.lang.IllegalStateException: getAttributeNames: Session already invalidated

Getting error:
java.lang.IllegalStateException: getAttributeNames: Session already invalidated.After logout from parent window.
LogOutUserAction.java
public String execute() throws Exception {
System.out.println("inside :: LogOutUserAction------");
//HttpServletRequest request = null;
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session =request.getSession(true);
session.removeAttribute("loggedInUser");
request.getSession(false).invalidate();
session=null;
return "logout";
}
LoginInterceptor
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context
.get(HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) context
.get(HTTP_RESPONSE);
HttpSession session = request.getSession(true);
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
/*user logged out from the parent window then set the message
for click on the popup window*/
if(session == null){
System.out.println("set the attribute");
request.setAttribute("SessionExpired","Your have already logged out");
}
Object user = session.getAttribute(USER_HANDLE);
String loginOut = request.getParameter(LOGIN_OUT);
System.out.println("loginOut---->"+loginOut);
if (user == null) {
// The user has not logged in yet.
System.out.println(" inside if ");
// Is the user attempting to log in right now?
String loginAttempt = request.getParameter(LOGIN_ATTEMPT);
/* The user is attempting to log in. */
if (!StringUtils.isBlank(loginAttempt)) {
return invocation.invoke();
}
return "login";
} else {
return invocation.invoke();
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
if (request.getAttribute("SessionExpired")!= null)
{
System.out.println("After Session invalid");
}
%>
<html>
<head>
<title>Login</title>
<sx:head cache="true"/>
<script type="text/javascript">
</script>
<script type="text/javascript" language="javascript" src="js/login.js"></script>
<style type="text/css">
.style1 {font-family: Verdana, Arial, Helvetica, sans-serif}
.style2 {
color: #000099
}
</style>
</head>
<body bgcolor="#CODFFD" background="<%request.getContextPath();%>images/watermark_new.jpg">
<br>
<br>
<br>
<br>
<br>
<br>
<div align="center"><span class="style1">USER LOGIN</span>
<br>
<br>
<br>
<s:form action="checkUserLogin.action" validate="true" name = "loginForm">
<s:hidden name="loginAttempt" value="%{'1'}" />
<table border="0" cellspacing="1" cellpadding="0" width="350" >
<tr>
<td align="center">
<b>Login ID</b>
</td>
<td>
<table>
<s:textfield id="id" name="loginId" value="" />
</table>
</td>
</tr>
<tr>
<td align="center">
<b>Password</b>
</td>
<td>
<table>
<s:password id="password" name="loginPassword" value="" showPassword="true"/>
</table>
</td>
</tr>
<tr><td colspan="2" align="center">
<table>
<s:submit value="Login" onclick = "return getRoleList()"/>
</table>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<table>
<s:a href="changePasswordScreen.action" >Change Password</s:a>
</table>
</td>
</tr>
</table>
</s:form>
</div>
<br>
<br>
<br>
</body>
</html>
Need to display message on popup window (when i click on any link) as i mentioned on my login jsp after logout from parent window.
Interceptors can execute code before and after an Action is invoked. When is yours being invoked? I would imagine what's happening is this:
In LogOutUserAction.java you invalidate the session
LoginInterceptor.intercept is then executed. This tries to get an attribute from the session object that you invalidated hence the IllegalStateException.
Why are you invalidating the session? Your LoginInterceptor is using the presence of the USER_HANDLE attribute to indicate whether or not the user is logged in. I would remove this attribute in your LogOutUserAction but don't invalidate the session.

unable to compile class for JSP

Iam working on a project in JSP using netbeans.
Iam getting the following error......but i didn't find the java any files..please provide me something.The error is:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 205 in the generated java file
Syntax error, insert "Finally" to complete TryStatement
An error occurred at line: 206 in the generated java file
Syntax error, insert "}" to complete ClassBody
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:439)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:349)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:589)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
The files i used are:
addNewUser.jsp:
<%# page language="java" %>
<%# page session="true" %>
<%# page import="java.util.*" %>
<HTML>
<head>
<LINK href="styles.css" type="text/css" rel="stylesheet">
</head>
<SCRIPT LANGUAGE="JavaScript">
<!--
history.go(+1);
function validate(){
x = document.NewUser.uid;
y = document.NewUser.pwd;
z = document.NewUser.auth;
var ed=x.value;
var pd=y.value;
var ad=z.value;
var pattern = /^([a-zA-Z0-9\_\.]{4,10})$/;
var Apattern = /^([0-3]{1})$/;
if(!(pattern.test(ed))){
alert("Invalid username");
return false;
}
else if(!(pattern.test(pd))){
alert("Invalid password");
return false;
}
else if(!(Apattern.test(ad))){
alert("Invalid Authentication");
return false;
}
else
return true;
}
//-->
</SCRIPT>
<br><br>
<body Class=Grad>
<center>
<BR><BR><br><br>
<FONT FACE="Century Gothic">
<FONT size="2" color="blue" FACE="Century Gothic">
<FORM NAME="NewUser" ACTION="AddNewUser1.jsp" METHOD="POST" onsubmit="return validate()">
<TABLE Border=0 align=center>
<TR class=row_title ALIGN="center">
<TH COLSPAN="2"> Add user</TH>
</TR>
<TR class=row_even>
<TD>UserID * </TD>
<TD><input TYPE=text name=uid size="10" maxlength="10"></TD>
</TR>
<TR class=row_odd>
<TD>Password * </TD>
<TD><input TYPE=password name=pwd size="10" maxlength="20"></TD>
</TR>
<TD><input type=hidden name=auth value=2>
<TR class=row_even>
<TD><INPUT TYPE=submit name=submit value="Submit">
</TD>
<TD><INPUT TYPE=reset name=resett value="Reset" >
</TD>
</TR>
</TABLE>
<A align="center" href="Login.jsp">BACK TO HOME</A>
</FORM>
</BODY>
</HTML>
addNewUser1.jsp:
<%# page language="java" %>
<%# page session="true" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.util.Random" %>
<html>
<head>
<LINK href="styles.css" type="text/css" rel="stylesheet">
<SCRIPT LANGUAGE="JavaScript">
<!--
history.go(+1);
//-->
</SCRIPT>
</head>
<jsp:include page="MultiLevelmenu.htm"/><br><br><body Class=SC>
<center>
<BR><BR>
<FONT FACE="Century Gothic">
<!--Declaration of varaibles-->
<%! String errormsg ;%>
<%! String disluserid ;%>
<%! String dislpwd ;%>
<%! int auth ;%>
<%
/*Retreiving user id and password*/
disluserid = request.getParameter("uid");
if(disluserid == null)
disluserid = "";
dislpwd = request.getParameter("pwd");
if(dislpwd == null)
dislpwd = "";
String sauth = request.getParameter("auth");
if(sauth == null)
auth=0;
auth = Integer.parseInt(sauth);
//System.out.println(disluserid+dislnewpwd+dislpwd);
%>
<%
/*Declaration of variables*/
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
String Userid,Password;
try
{
/*Getting the connection variable from session*/
con=(Connection)session.getAttribute("connection");
stmt = con.createStatement();
String Query = "SELECT * from student where studentid = \'"+disluserid+"\'";
System.out.println(Query);
rs = stmt.executeQuery(Query);
}
catch(Exception e)
{
System.out.println("Exception"+e);
/* If user provides valid username & password then update the new password to database*/
if(rs.next())
{%>
<script>
for(i=1;i<=6;i++) document.write("<br>");
</script>
<H3 align="center"> User already exists</H3>
<BR>
<center>
Back
</center>
<%
}
else{
String UpdateQuery =
"Insert into student values(\'"+disluserid+"\',\'"+dislpwd+"\',"+auth+")";
//System.out.println(UpdateQuery);
int rowsAffected=stmt.executeUpdate(UpdateQuery);
//System.out.println("Rows Affected = " + rowsAffected);
if(rowsAffected==1)
{%>
<script>
for(i=1;i<=10;i++) document.write("<br>");
</script>
<H3 align="center">User Created Successfully </H3>
Create Another User
<br/>
Home
<BR>
<%}
/* If user provides invalid password or username*/
else{%>
<script>
for(i=1;i<=6;i++) document.write("<br>");
</script>
<H3 align="center">Unable to create user please try again </H3>
<BR>
<% } %>
<%
}
%>
</FONT>
</center>
</BODY>
</html>
try {
/*Getting the connection variable from session*/
con=(Connection)session.getAttribute("connection");
stmt = con.createStatement();
String Query = "SELECT * from student where studentid = \'"+disluserid+"\'";
System.out.println(Query);
rs = stmt.executeQuery(Query);
} catch(Exception e) { System.out.println("Exception"+e);
In the above code section you are not completing the try's catch block.

Categories