Validating a form using JSP - java

I'm completely new to JSP and am creating a simple form and validating it through JSP.
Here's my code :-
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<%#page import="java.io.* , java.sql.* , java.util.* , javax.servlet.*" %>
<body>
<h1>Login Page by JSP</h1>
<hr>
<form method="post" action="index_jsp">
Enter name : <input type="text" name="user">
Enter password : <input type="password" name="pass">
<input type="submit" value="login">
</form>
<%
String user = request.getParameter("user");
String pass = request.getParameter("pass");
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
%>
<br>
Click here !
</body>
</html>
But each and every time I run it , I get a NullPointerException .
What am I doing wrong ? Immediate help would be appreciated !
Thanks!

First bit of advice, since you're new to JSP: Don't write scriptlet code. That's all the stuff between <% and %>. It's a 1998 vintage technology that should be discouraged. Learn JSTL and Model-2 MVC instead.
You need a servlet to orchestrate those JSPs. Every web MVC framework that I know of has what's called a front controller servlet to manage the communication and orchestration. You should, too.
You have the form POST in this JSP, sending the HTTP request to index_jsp (bad name). It's executing in the browser on the client machine.
I would expect you to send this to a servlet on the server side that gets the HTTP request, gets the username and password out, compares the values to a database to see if the user is indeed registered. Then I'd either send the next view or route to the "sorry" page. That's not what you're doing.

Don't do equals checks on the variables, rather do them against the constants:
if("admin".equals(user) && "admin".equals(pass)) {
response.sendRedirect("wel.html");
}
This way you cannot get the NPE.

Change this line
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
with
if(user!=null){
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
}

You are not checking null for request attributes.
replace
String user = request.getParameter("user");
String pass = request.getParameter("pass");
with
String user = request.getParameter("user") != null ? request.getParameter("user") : "";
String pass = request.getParameter("pass") != null ? request.getParameter("pass") : "";

change codeļ¼š
if("admin".equals(user) && "admin".equals(pass)) {
response.sendRedirect("wel.html");
}
When you first run jsp,it will execute the code,but user and pass is null.

Related

How to solve HTTP Status 404

I'm trying to write a simple web app in JSP that allows user to choose 2 numbers in the range 1-100 from 2 drop-down lists and then print out those numbers. However, I keep receiving the error message:
Below is my code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Game Table</title>
</head>
<body>
<form method="post">
#rows:
<select name="row">
<%
for(int i=1;i<=100;i++){
out.println("<option value="+"\""+i+"\""+">"+i+"</option>");
}
%>
</select>
#columns:
<select name="column">
<%
for(int i=1;i<=100;i++){
out.println("<option value="+"\""+i+"\""+">"+i+"</option>");
}
%>
</form>
<%
String row=request.getParameter("row");
String column=request.getParameter("column");
if(row!=null && column!=null){
out.println(row+" "+column);
}
%>
</body>
Thank you so much
well, problem is in navigation not in your code. For not showing dropdown menu so use proper url mapping to run your jsp like http://localhost:8080/yourwebprojectname/game.jsp game.jsp is assumption of your following above code page name.
Your code have many error like missing of action="" like
<form method="post" action="book.jsp">
</Select> tag above the form
Main problem is you dont have any button or use of ajax to show the output that you trying to display via Scriptlet
for simple solution add a button inside your form
<input type="submit" value="show" name="show"/>
add code something like this inside your Scriptlet
if("show".equals(request.getParameter("show"))){
if(row!=null && column!=null){
out.println(row+" "+column);
}
}
I am not completely sure, but it might be returning 404 (not found) because you are not submitting this data correctly. See, there is no "action" atribute indicating where it should go (e.g. "save.jsp").
Hope it helps! :)

Send data from JSP to Java program

I'm a beginner to JSP (started today) and wanted to send some data (which I have got in a JSP file from an HTML form) to a JAVA program where I could use it.
Peterclass is the name of the Java program I'm gonna be making/using.
Suppose my JSP file is like this:
<%# page import="com.example.Peterclass"%>
<%# page import="java.util.*"%>
<html>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
<h1>
Hello, <%=username%>!
</h1>
</body>
</html>
and I wanted to receive the values of username and password variables in a JAVA program (I'm using Tomcat server for the purpose). How shall I do it? Please be as simple as you can be.
Thank you.
First of all, you will need a so called "Servlet" to work with request and response Parameter.
Here is a first tutorial on how to create and use servlets:
Click here
Another tip for you:
It is not state of the art to use so called Scriptlets.
Scriptlets is a form of Java-Code in JSP Sites:
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
You can easily get the parameter you set in your Servlet with:
${requestScope.<<PARAMETERNAME>>}
e.g. ${requestScope.username}
or if your parameter is in the HTTPSession:
${sessionScope.<<PARAMETERNAME>>}
your jsp side would look like this afterwards:
<html>
<body>
<h1>
Hello, ${requestScope.username}!
</h1>
</body>
So, to come back to your question:
In your Servlet you can set the Parameter with
request.setParameter(<<PARAMETERNAME>>,<<VALUE>>)
In this Servlet you can call normal Java-Functions. First step for you is to read through tutorials :)

Pass selected value from dropdown using JSP

I need to implement some basic dropdown using jsp and java, but I can't find more info how to do that. So I never write something using JSP and when I didnt find nothing that help the last options for me was to ask.
I want to get the selected value and when click the button to send the value to anoher .jsp file ("selector.jsp in my case")
Please folks help me with some easy solution.
p.P.: Sorry for my english (:
index.jsp
<FORM method="post" action="selector.jsp">
<select name="select" id="dropdown">
<%
Test t = new Test();
t.getList().add("a");
t.getList().add("b");
t.getList().add("c");
for(int i=0; i < t.getList().size(); i++){
%>
<Option value="<%t.getList().get(i);%>"><%=t.getList().get(i)%></Option>
<%}%>
</select>
<input type="submit" value="click">
selector.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
You selected:
<%
request.getParameter("select");
request.getParameterValues("select");
%>
</body>
</html>
I found a solution by removing
value="<%t.getList().get(i);%>"
from and leave the code just with
<Option><%=t.getList().get(i)%></Option>
but i don't know why... if someone can explain will be great.
Thx! (:
As you have indicated in your post, the problem is solved by replacing
value="<%t.getList().get(i);%>"
with
<Option><%=t.getList().get(i)%></Option>
The reason that works is as follows:
In your first form, <%t.getList().get(i);%>, you have a JSP scriptlet. This is Java code that is executed inline. In your case, this executes the "get" method. Note however that the get method returns a value, but this value is not output into the response stream.
In your second form, you have formed a JSP expression by using "<%=". "<%=" is shorthand for "out.println", thus you have provided shorthand for the following:
<Option><% out.println(t.getList().get(i)) %></Option>
This writes the return value of the method call to the output stream. So that when this output reaches the browser, there is an actual value within the Option tags.

Passing parameters from JSP page to a java method to persist to a database

I am trying to create a registration JSP page which when submit is clicked I would like it to pass the information entered to an addUser method in a java class
This is my JSP Page:
<%# 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>Registration</title>
</head>
<body>
<center>
<h2>Signup Details</h2>
<form action="RegisterUser.java" method="post">
<br/>Username:<input type="text" name="username">
<br/>Password:<input type="password" name="password">
<br/>Email:<input type="text" name="email">
<%= String name = request.getParameter("username");
String pass = request.getParameter("password");
String email = request.getParameter("email");
User u = new User();
u.setName(name);
u.setPassword(pass);
u.setEmail(email);%>
<br/><input type="submit" value="Submit" action="RegisterUser.addUser(u)">
</form>
</center>
</body>
</html>
When Submit is clicked I want to add the details to a database using the following method
public class RegisterUser {
private static final String PERSISTENCE_UNIT_NAME = "User";
private static EntityManagerFactory factory;
private User user;
public void addUser(User user){
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// Create new user
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
em.close();
You have to create a Servlet that processes your form and calls the addUser() method.
You can't invoke a Java method directly from JavaScript.
Here's a good tutorial on the subject.
http://www.tutorialspoint.com/servlets/servlets-form-data.htm
You generally pass request data to Servlet which acts as controller and depending on request it delegates logical calls to services class
Check out the complete flow with example and nice explanation on servlet wiki page
You need to work with a Servlet that will work as Controller in your Model. The View, the JSP in your case, should be able to communicate with your Model using a Servlet.
For a good separation between the Model, Controller and the View you can use Spring MVC. Here is a good example that you can follow as start point: http://www.mkyong.com/spring-mvc/spring-mvc-hello-world-example.
Did you try closing down eclipse and opening it again? If not try restarting eclipse. It works for me every time.

Using Dropdown box in JSP code

<html>
<body>
<form action="Test1.jsp" method="post">
<select name="source" onchange="">
<option value="rss">RSS LINK</option>
<option value="other">OTHER LINK</option>
</select>
Enter URL to be added <input type="text" name="url" size=50>
Enter the Source Name of the URL<t><input type="text" name="source1" size=50>
<input type="Submit" name="submit1" value="Add URL in DB">
</form>
</body>
</html>
The above code is stored in Addurl1.jsp file which calls the other jsp file named Test1.jsp.
The code under Test1.jsp is as follows
<%# page import="myfirst.*" %>
<%
String url1=request.getParameter("url");
String source1=request.getParameter("source1");
myfirst.SearchLink p=new myfirst.SearchLink();
String result=p.addURL(url1,source1);
out.println(result);
System.out.println(result);
%>
Test1.jsp calls addURL(String, String) function of SearchLink.java program.
In the dropdownbox of Addurl1.jsp program, if the user selects RSS link, the addURL() method must be called. If the user selects OTHER LINK, there is another method named addURL1() in the same java program which must be called.
Please let me know how the above codes can be modified inorder to achieve my task.
Thanks in advance!
At first it is better to change Addurl1.jsp into a servlet and implement the doPost method. Jsp files are supposed to only contain the presentation layer and no Java code. Java code should go in servlets (or controllers if you are using an MVC framework).
What you are asking can easily be achieved with an if statement:
final String RSS_LINK = "rss";
final String OTHER_LINK = "other";
String url1=request.getParameter("source");
String result="";
if (url1 != null && url1.equals(RSS_LINK)) {
result=p.addURL(url1,source1);
}
else if (url1 != null && url1.equals(OTHER_LINK)) {
result=p.addURL1(url1,source1);
}

Categories