I am trying to call getParameter. Everything is ok, but when I click the edit link it gives a NullPointerException. Why does it not get the value?
JSP CODE:
<%#page import="teacher.TeacherBAL"%>
<%#page import="teacher.TeacherBean" %>
<%#page import="java.util.*" %>
<%# 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Display Data</title>
</head>
<body>
<table border=1>
<th>Name</th>
<th>Degree</th>
<th>Delete</th>
<th>Edit</th>
<%
ArrayList teachers = (ArrayList) request.getAttribute("allRecord");
if (teachers != null) {
int a = 0;
for (; a < teachers.size(); a++) {
TeacherBean teacherBea = (TeacherBean) teachers.get(a);
%>
<tr>
<td><%=teacherBea.getName()%></td>
<td><%=teacherBea.getDegree()%></td>
<td>
Delete
</td>
<td>
Edit
</td>
</tr>
<%}
}
%>
</table>
</body>
Servlet Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String edit= request.getParameter("click");
String del = request.getParameter("delete");
String req= request.getParameter("show");
if(del!=null){
int dele = Integer.parseInt(del);
TeacherBAL.getTeacher().remove(dele);
request.setAttribute("allRecord", TeacherBAL.getTeacher());
RequestDispatcher rd= request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
else if(req.equals("ok")){
request.setAttribute("allRecord", TeacherBAL.getTeacher());
RequestDispatcher rd= request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
else if(edit!=null){
int num = Integer.parseInt(edit);
PrintWriter out = response.getWriter();
out.print(num);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name= request.getParameter("names");
String degre= request.getParameter("degre");
if(name!=null && degre!=null){
TeacherBAL.setTeacher(new TeacherBean(name,degre));
RequestDispatcher rd= request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
You are getting a null pointer exception because you did not pass the values of delete and show when you clicked the edit button. Because of this, del and req are null and you are getting an exception on req.equals("ok").
Related
I can`t understand one thing when i send request to get object by name from db,
it always return me null. I surf all sites try to fix it with session and etc. Nothing to work.
Any ideas?
enter image description here
This is my Servlet class:
#WebServlet(value = "/display", name = "IndexServlet")
public class IndexServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if(!(request.getParameter("mysql")==null)) {
MySQLRepository sql = new MySQLRepository();
Headline object = sql.getByHeadline(request.getParameter("mysql"), DatabaseConnection.initDatabase());
request.setAttribute("id", object.getId());
request.setAttribute("headline", object.getHeadline());
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("out.jsp");
requestDispatcher.forward(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is index.jsp:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>MySQLSolrProject</title>
</head>
<!DOCTYPE html>
<body>
<form action="out.jsp" method="get">
<p>Headline:</p>
<label>
<input type="text" name="mysql">
</label>
<%--<br>
<p>Full text:</p>
<label>
<input type="text" name="solr">
</label>--%>
<br><br>
<input type="submit" value="Search" formmethod="get">
</form>
</body>
</html>
This is out.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Out</title>
</head>
<body>
<h2>Text is:</h2>
<table>
<tr><th>Id</th><th>Headline</th><th></th></tr>
<tr><td><%=session.getAttribute("id")%></td>
<td><%=session.getAttribute("headline")%></td>
</tr>
</table>
<p>Return to search</p>
</body>
</html>
the error was that Tomcat version 10.* didn't want to work with version 4 servlets
I downgraded Tomcat to version 9.* and it worked.
I am working on a Login and registration form. I have successfully created the Login and Registration form and linked them together. Now I created a separate page for admin where I want to display my database. But I am not able to move to the admin page. Whenever i input my admin credentials it always shows a blank page. I am a newbie both to Java and stackoverflow so I dont know how to ask proper questions. I pasted all my code here. My main problem is in Login.java . I am using eclipse and tomcat 8.5.
Things I have tried till now:-
1) RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
2)HttpServletResponse.sendRedirect("/WEB-INF/admin.jsp")
3)response.sendRedirect("WEB_INF/admin.jsp");
Registeration.java
public class Registeration extends HttpServlet {
private static final long serialVersionUID = 1L;
public Registeration(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException{
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String age = request.getParameter("age");
String gender = request.getParameter("gender");
String event = request.getParameter("event");
String sql = "insert into
registeration(usernam,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root", "");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ps.setString(3,age);
ps.setString(4,gender);
ps.setString(5,event);
ps.executeUpdate();
PrintWriter out = response.getWriter();
out.println("You have successfully registered!");
out.flush();
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.include(request, response);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Registeration.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<img src="unilogo.PNG" style="width:40%">
<body>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
Age : <input type="text" name="age" required="required" /><br>
Gender : <select name="gender">
<option>Male</option>
<option>Female</option>
<option>Transgender</option>
</select><br>
Event : <select name="event" multiple="multiple">
<option>Mr.Tanwar Body Building</option>
<option>Fashion Show</option>
<option>Dance</option>
<option>Singing</option>
<option>Coding</option>
</select><br>
<input type="submit" value="REGISTER" />
<input type="reset" value="RESET" /><br>
<a href="${pageContext.request.contextPath}/login.jsp">Click
here
to go to the login page</a>
</form>
</div>
</body>
</html>
Login.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<div align="center">
<form action="Login" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
<input type="submit" value="Login" />
<input type="reset" value="RESET" /><br>
<a
href="${pageContext.request.contextPath}/registeration.jsp">Click here
to
go to the Registration page</a>
</form>
</div>
</body>
</html>
Login.java
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String dbName = null;
String dbPassword = null;
String sql = "select * from registeration where usernam =
? and password = ?";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root",
"");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ResultSet rs = ps.executeQuery();
PrintWriter out = response.getWriter();
while(rs.next()){
dbName = rs.getString(2);
dbPassword = rs.getString("password");
if(usernam.equals("admin") &&
password.equals("password")){
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
}
if(usernam.equals(dbName) &&
password.equals(dbPassword)) {
out.println("You have successfully logged
in!");
out.println("Age:"+rs.getString(4)+"
Gender:"+rs.getString(5)+" Event:"+rs.getString(6));
}
else {
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/registeration.jsp");
rd.forward(request, response);
}
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>Registeration</display-name>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>jdbc.registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/regServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>jdbc.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
My login page is supposed to redirect me to admin.jsp when i enter my admin details. But all i get is a blank page. My url after entering admin details"http://localhost:8080/Registeration/Login". I am getting the required output when enter the login id which are stored in DB.
Im trying pass specific element from my Model to servlet to jsp.
This is working in my servlet: System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]) When I go to http://localhost:8080/Comparebet/Controller
But I dont know what Im doing wrong since I dont get it to my jsp. All tutorials ive been watching is mostly input parameters or they put code in the JSP.
UPDATE EDIT
Tried with this in my JSP and I get "null"
<%= request.getAttribute("rank1") %>
SERVLET
#WebServlet("/Controller")
public class Controller extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ArrayList<String> sortedDomainList = new BeanModel().getSortedDomainList();
BeanModel beanModel = new BeanModel();
request.setAttribute("rank1", beanModel.getSortedDomainList().get(0).split(";")[1]);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
//TESTING SERVLET
System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]);
System.out.println("CONTROLLER CALLED");
// System.out.println(${rank1});
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
}
}
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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>CompareBet</title>
</head>
<body>
<form action="/Controller/*" method="get">
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
</form>
</body>
</html>
In your JSP try this, instead of rank1.getSortedDomainList().get(0).split(";")[1]
<h1>${request.rank1 } </h1>
You have already done beanModel.getSortedDomainList().get(0).split(";")[1] in your servlet and have added the result to the request scope object.
Try to replace this line in your jsp:
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
To this:
<h1>${rank1} </h1>
In JSP you can access this data using the expression language like ${rank1}.
And take it out from the <form like this:
<form action="/Controller/*" method="get">
...
</form>
Try to use <h1><%= request.getParameter("rank1")%></h1>
I've an InitializeServlet that creates and instantiates a HttpSession then redirects to a JSP (betFinalize.jsp). Here I can work on my session. When from that JSP I redirect (through a form) to another Servlet, FinalizeServlet I loose my session. I cannot figure out why. Following code.
InitializeServlet.java
public class InitializeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String result = request.getParameter("result");
Bet s = new Bet();
s.setFirstLastName(fName + " " + lName);
s.setResult(result);
s.setMultiplier(calculateMultiplier());
request.getSession(true).setAttribute("bet", s);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/betFinalize.jsp");
rd.forward(request, response);
}
private double calculateMultiplier() {
return 0.8;
}
}
betFinalized.jsp
<%# page import="it.unibo.tw.model.beans.Bet"%>
<%# page import="it.unibo.tw.model.beans.Bets"%>
<%# page session="true"%>
<jsp:useBean id="bet" class="it.unibo.tw.model.beans.Bet" scope="session"></jsp:useBean>
<jsp:useBean id="finalizedBets" class="it.unibo.tw.model.beans.Bets" scope="application"></jsp:useBean>
<!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">
</head>
<body>
<h1>Hi, <%= bet.getFirstLastName() %></h1>
<h2>Current bet: <i><%= bet.toString() %></i></h2>
<form action="finalize" method="get">
<input id="import" type="number" name="import" onkeyup="calculateWin()" ><br />
<input id="win" type="text" name="win" readonly ><br />
<input type="submit">
</form>
<hr />
<ul>
<% for(Bet s : finalizedBets.getList()) { %>
<li><%= s.toString() %></li>
<% } %>
</ul>
</body>
<script>
function calculateWin() {
var multiplier = <%= bet.getMultiplier() %>
var imp = document.getElementById("import").value
document.getElementById("win").value = imp * multiplier
}
</script>
</html>
FinalizeServlet.java
public class FinalizeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
double vincita = Double.parseDouble(request.getParameter("win"));
Bet s = (Bet) request.getSession().getAttribute("bet");
if(s != null) {
// NEVER REACH HERE
s.setWin(vincita);
s.setFinalized(true);
Bets scommesseFinalized = (Bets) getServletContext().getAttribute("scommesseFinalized");
scommesseFinalized.getList().add(s);
}
request.getSession().invalidate();
RequestDispatcher rd = getServletContext().getRequestDispatcher("/start.html");
rd.forward(request, response);
}
}
You're trying to get the wrong attribute. When you set the session variable you have:
request.getSession(true).setAttribute("scommessa", s);
When you try to read it:
request.getSession().getAttribute("bet");
it should be:
request.getSession().getAttribute("scommessa");
instead.
Encode the session id in the action of the form as below:
<form action="<%=response.encodeURL("finalize")%>" method="get">
I know similar questions have been asked earlier but for some reason it is not working. I am just trying to check if user has entered both the fields on the login page or not. If not, then I want to display the message on jsp saying that they need to enter both the credentials. Here is my JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!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>Login</title>
</head>
<body>
<h2>Some App</h2>
<form action="login" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="uname"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="pass" name="pass"></td>
</tr>
</table>
<br> <input type="button" value="Submit">
</form>
<c:out value= "${error}"/>
</body>
</html>
Then here is the servlet:
#WebServlet("/login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//Getting values from the form
String username = request.getParameter("uname");
String password = request.getParameter("pass");
System.out.println("Username is: "+ username);
System.out.println("Password is: "+ password);
//User user = new User();
if((username.equals(""))|| password.equals("")){
String message = "Please enter both the credentials";
request.setAttribute("error", message);
//RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
//rd.forward(request, response);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
else{
RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
//Setting values in the session
session.setAttribute("username", username);
session.setAttribute("password", password);
}
}
Since I am trying to experiment with maven, here is my pom.xml file with dependency added for jstl jar:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
Why does that c:out tag not print anything? What am I doing wrong? Any help will be appreciated. Thank You.
You are mixing two styles of returning a response to the client. Try passing the error message using this code:
if((username == null)|| password == null) {
String message = "Please enter both the credentials";
request.setAttribute("error", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
The rule of thumb is that you have to use request.setAttribute() with forward() and request.getSession().setAttribute() with response.sendRedirect().
try ${sessionScope['error']} instead of ${error}. If that worked then you may have another attribute in another scope with the same name 'error'
You should also check if username or password are empty. i.e. (username != null && username.trim().isEmpty())
Suggestions from everyone was very valuable. There were a few things that I was doing wrong: incorrect servlet mapping (#WebServlet fixed it), changed code to what #NaMaN and #bphilipnyc replied and the biggest mistake due to which I wasn't able to reach servlet was that I had input type as button in jsp. I changed it to input type submit, and then it worked. Thank you guys for replying. Really appreciate it.