I am trying to create a page that will code that will take in student information from html and use java servlets to catch the information and put into Google Cloud Datastore.
I have the HTML working but whenever I try to run it the page just refreshes and doesn't put anything into the cloud datastore.
I am new to servlets so I'm not sure what I am missing.
Below is the jsp file (i.e add_student.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>Insert title here</title>
</head>
<body>
Add Student
Search Student
Update Student
Delete Student
<form method="post">
<p>Student Number <input name="student_number" type="number" required /></p>
<p>First Name <input name="f_name" type="text" required/></p>
<p>Last Name <input name="l_name" type="text" required/></p>
<p>Address (temporary) <input name="temp_address" type="text" required/></p>
<p>Address (permanent) <input name="perm_address" type="text" required/></p>
<p>Home Number <input name="home_number" type="number" required/></p>
<p>Mobile Number <input name="mobile_number" type="number" required/></p>
<p>Date of Birth <input name="birth_date" type="date" required/></p>
<p>Gender <p>Gender: <br>
<input type="radio" name="gender" value="M" required checked> Male<br>
<input type="radio" name="gender" value="F" required> Female<br>
<p>Major <input name="major" type="text" required/></p>
<p>Course <input name="course" type="text" required/></p>
<p>Study Mode <p>Study Mode: <br>
<input type="radio" name="study_mode" value="full_time" checked> Full-Time<br>
<input type="radio" name="study_mode" value="part_time" required> Part-Time<br>
<p>Start Date <input name="start_date" type="date" required /></p>
<p>End Date <input name="end_date" type="date" required /></p>
<p>Add Student <input name="submitButton" type="submit" value="addStudent" /></p>
</form>
</body>
</html>
Here's the java Servlet file (i.e add_studentServlet.java)
package assignment_redo;
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.*;//import the datastore files from google
#SuppressWarnings("serial")
public class add_studentServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
String title ="Using the GET Method to Read Form Data!";
String student_number = req.getParameter("student_number");
String f_name =req.getParameter("f_name");
String l_name=req.getParameter("l_name");
String perm_address = req.getParameter("perm_address");
String temp_address = req.getParameter("temp_address");
String home_number = req.getParameter("home_number");
String mobile_number = req.getParameter("mobile_number");
String birth_date = req.getParameter("birth_date");
String gender = req.getParameter("gender");
String major = req.getParameter("major");
String course = req.getParameter("course");
String study_mode = req.getParameter("study_mode");
String start_date = req.getParameter("start_date");
String end_date = req.getParameter("end_date");
// //creating an object of type DatastoreService
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//creating a new entity of type employee
Entity student = new Entity("Student", student_number);
//set its properties
student.setProperty("f_name", f_name);
student.setProperty("l_name", l_name);
student.setProperty("student_number", student_number);
student.setProperty("temp_address", temp_address);
student.setProperty("perm_address", perm_address);
student.setProperty("home_number", home_number);
student.setProperty("mobile_number", mobile_number);
student.setProperty("birth_date", birth_date);
student.setProperty("gender", gender);
student.setProperty("major", major);
student.setProperty("course", course);
student.setProperty("study_mode", study_mode);
student.setProperty("start_date", start_date);
student.setProperty("end_date", end_date);
//insert student entity into Datastore
datastore.put(student);
//display success message now
resp.getWriter().println("Student with id "+student_number+" added to the system!");
}
}
You have to indicate in your jsp that you are submitting the form to your servlet:
<form action="addStudent" method="post">
This makes the assumption that in the web.xml you have configured your servlet as follow:
<servlet>
<servlet-name>add_studentServlet</servlet-name>
<servlet-class>assignment_redo.add_studentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add_studentServlet</servlet-name>
<url-pattern>/addStudent</url-pattern>
</servlet-mapping>
Then you have to put your code in the doPost of your servlet, not in the doGet.
Related
I am trying to get an Employee's info from a database with a user-input ID number in the html page hello.html and display the info in another html file helloResponseDB.html, but it seems that when I submit the ID number, it leads me to different html page helloResponse.html, which displays a user-input word. Please could you help me?
Controller Code:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
#Controller
public class HelloController {
#Autowired
private HelloService helloService;
#GetMapping("/hello")
public String getHello() {
return "hello";
}
#PostMapping("/hello")
public String
postRequest(#RequestParam(name="text1",required=false)String str, Model model) {
model.addAttribute("sample",str);
return "helloResponse";
}
#PostMapping("/hello/db")
public String
postDbRequest(#RequestParam(name="text2")String str, Model model) {
int id = Integer.parseInt(str);
Employee employee = helloService.findOne(id);
model.addAttribute("id",employee.getEmployeeId());
model.addAttribute("name",employee.getEmployeeName());
model.addAttribute("age",employee.getAge());
return "helloResponseDB";
}
}
hello.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<metacharset="UTF8"></meta>
<title>Hello World</title>
</head>
<body>
<h1>Hello World</h1>
<form method="post" action="/hello">
Enter a word:
<input type="text" name="text1 th:value="${text1_value}"/>
<input type="submit" value="Click"/>
</form>
<br/>
<form method="post" actioin="/hello/db">
Enter Employee's ID:
<input type="number" name="text2" th:value="${text2_value}"/>
<input type="submit" value="Click"/>
</form>
<body>
</html>
First you correct the action spelling in 2nd form in your hello.html also use th:action for form action as you have used Thymeleaf. Also, you have not closed your name="text1" in your first form.
i.e
<input type="text" name="text1 th:value="${text1_value}"/>
change it to
<input type="text" name="text1" th:value="${text1_value}"/>
<form th:action="#{/hello}" method="post">
Enter a word:
<input type="text" name="text1" th:value="${text1_value}">
<input type="submit" value="Click">
</form>
<br/>
<form th:action="#{/hello/db}" method="post" >
Enter Employee ID:
<input type="number" name="text2" th:value="${text2_value}" >
<input type="submit" value="Click" >
</form>
This is my code:
<%# 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>Insert title here</title>
</head>
<body>Select Payment Method<BR><BR>
<font size=""><marquee behavior="alternate">PAYMENT GATEWAY</marquee></font>
<form action="S2ShowPay.jsp" method="post">
<input type="radio" value="NET BANKING" name="payment" >NET BANKING<br><br>
<input type="radio" value="DEBIT CARD PAYMENT" name="payment">DEBIT CARD<BR><br>
<input type="radio" value="CASH ON DELIVERY" name="payment" >CASH ON DELIVERY<br><br>
<input type="submit" value="NEXT"/>
</form>
</body>
</html>
I want to navigate to netbanking.jsp when I click on Net Banking radio button and Debit.jsp repectively, using only jsp and some javascript.
Please help.
Im not sure what's your expected result, Perhaps you can try this. Correct me if im wrong.
Using location.href
function fnPayment()
{
if(document.getElementById("a").checked ==true || document.getElementById("b").checked ==true)
{
location.href = "http://www.google.com"; //your jsp file
}
}
</script>
<input type="radio" value="NET BANKING" name="payment" id="a">NET BANKING<br><br>
<input type="radio" value="DEBIT CARD PAYMENT" name="payment" id="b">DEBIT CARD<BR><br>
<input type="radio" value="CASH ON DELIVERY" name="payment" id="c">CASH ON DELIVERY<br><br>
Using response redirect
Since you have created S2ShowPay.jsp, you can pass parameter to it once you clicked next button and put response redirect based on the parameter.
<input type="radio" value="NET" name="payment" >NET BANKING<br><br>
<input type="radio" value="DEBIT" name="payment">DEBIT CARD<BR><br>
<input type="radio" value="CASH" name="payment" >CASH ON DELIVERY<br><br>
S2ShowPay.jsp
String payment_ind = request.getParameter("payment");
if(payment_ind.equals("NET") || payment_ind.equals("DEBIT") )
{
response.sendRedirect("netbanking.jsp");
}
Add this code within head tag:
<script type="text/javascript">
function redirectPage(use,rname){
for (var val = 0, r1=use.elements; val < r1.length; val++)
if(r1[val].name==rname&&r1[val].checked)
use.action=r1[val].value;
}
</script>
Change your form tag like this:
<div>
<form action="#" method="post" onsubmit="redirectPage(this, 'r1');">
<input type="radio" name="r1" value="netbanking.jsp">NET BANKING<br><br>
<input type="radio" name="r1" value="Debit.jsp">DEBIT CARD<BR><br>
<input type="radio" name="r1" value="cashondelivery.jsp">CASH ON DELIVERY<br><br>
<input type="submit" value="Next"/>
</form>
</div>
Select the desired radio button and then clicking Next button will redirect to respective page.
I'm having a difficulty in getting the value on my drop down list from jsp. I'm getting a Null value of String which is "" only. But if I use only textbox for the department It will work. I'm having a hard time of finding where is the error in my code.
This is my JSP file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.18.custom.min.js"></script>
</head>
<body>
<form method="POST" action='PersonnelController' name="frmAddData" class="form">
<fieldset>
<legend id="myLegend">User</legend>
<label for="firstname">First Name :</label>
<input type="text" name="firstname"
value="<c:out value="${data.firstname}" />" /><br />
<label>Last Name :</label>
<input type="text" name="lastname"
value="<c:out value="${data.lastname}" />" /><br />
<!--<label>Department Name :</label>
<input type="text" name="department_id"
value="<c:out value="${data.department_id}" />" /><br />-->
<label>Department Name :</label>
<select name="personnel">
<c:forEach items="${personnels}" var="personnel">
<option value="${personnel.department_id}"><c:out value="${personnel.department_name}" /></option>
</c:forEach>
</select>
</fieldset>
<input type="submit" value="Submit" class="submit"/>
</form>
</body>
</html>
This is for Servlet:
private DepartmentDao dd;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<DepartmentBean> personnels = dd.getAllDepartmentName();
request.setAttribute("personnels", personnels);
request.getRequestDispatcher("/WEB-INF/personnel.jsp").forward(request, response);
}
}
and this is my DAO:
public List<DepartmentBean> getAllDepartmentName() {
List<DepartmentBean> departments = new ArrayList<DepartmentBean>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select department_name,id from department ORDER BY department_name");
while (rs.next()) {
DepartmentBean department = new DepartmentBean();
department.setPeople_manager_name(rs.getString("department_name"));
departments.add(department);
}
} catch (SQLException e) {
e.printStackTrace();
}
return departments;
The problem is that you're not fulfilling the necessary fields in your DepartmentBean object reference in the dao class. You're only filling people_manager_name field, and in your JSP you're requesting the data for department_id and department_name, which will call DepartmentBean#getDepartment_id() and DepartmentBean#getDepartment_name() methods.
Change this in getAllDepartmentName method:
while (rs.next()) {
DepartmentBean department = new DepartmentBean();
department.setDepartment_name(rs.getString("department_name"));
department.setDepartment_id(rs.getInt("department_id"));
departments.add(department);
}
Here's a useful link about how expression language works.
I have a very basic login servlet
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("marti") && password.equals("bosch")) {
response.sendRedirect("login_success.jsp");
} else {
RequestDispatcher rd = getServletContext().getRequestDispatcher(
"/login.html");
PrintWriter out = response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
When I call the servlet it from the login.html:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
<p>Username: <input type="text" name="username"> </p>
<p>Password: <input type="password" name="password"> </p>
<p><input type="submit" value="Login"></p>
</form>
</body>
</html>
if I input the correct user name and password, the browser correctly renders login_success.jsp. However, when I do not enter the right user name and password, the browser shows the unrendered html as plain text:
<font color=red>Either user name or password is wrong.</font>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
<p>Username: <input type="text" name="username"> </p>
<p>Password: <input type="password" name="password"> </p>
<p><input type="submit" value="Login"></p>
</form>
</body>
</html>
How can I make the LoginServlet place the message under in the right place (after the body tag)? Thanks
Exactly, you need to put it as a content of an HTML document:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<font color=red>Either user name or password is wrong.</font>
<form action="LoginServlet" method="post">
<p>Username: <input type="text" name="username"> </p>
<p>Password: <input type="password" name="password"> </p>
<p><input type="submit" value="Login"></p>
</form>
</body>
</html>
Additionally, a <font> tag is deprecated in HTML5.
EDIT:
So either you need to sendRedirect to the page where an error message is included:
response.sendRedirect("login_error.jsp"); //containing exactly the same html I posted
Or modify your form JSP, so it renders an additional error message after the authentication failure. You can accomplish that by passing a parameter from a Servlet to JSP. Refer to this thread.
I would like to determine which link is being click, and set a request attribute accordingly; to be processed in the controller. The controller is generic. It will dispatch to another page according to the attribute set in the JSP. How can I achieve this?
EDIT:
I have followed the BalusC's advice where
Register
Login
RandomController :
#WebServlet(name = "RandomController", urlPatterns = {"/RandomController/*"})
public class RandomController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int theRandom = 0;
Random myRandom = new Random();
RequestDispatcher dispatcher = null;
String pathInfo = request.getPathInfo();
String contextPath = request.getContextPath();
String dispatchesPath = contextPath + pathInfo;
System.out.println(pathInfo);
System.out.println(contextPath);
System.out.println(dispatchesPath);
theRandom = myRandom.nextInt(MAX_RANDOM);
request.setAttribute("random", theRandom);
if(pathInfo.equals("/Login")) {
dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
dispatcher = request.getRequestDispatcher("Register.jsp");
dispatcher.forward(request, response);
}
}
}
I have tried this approach but the Exception about maximum depth for nested request dispatchers : 20 is throw.
The generic controller is RandomController which servers two produces random number and set as attribute in request object and sent it to login or register page.
Login.jsp :
<%--
Document : Register
Created on : May 28, 2011, 5:49:35 PM
Author : nicholas_tse
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!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>Online Store Register Page</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<jsp:useBean id="randomBean" class="Helper.RandomInt"
scope="request">
</jsp:useBean>
<h1>Online Store</h1>
<p></p>
<div align="right">
<h3>
<c:if test="${not empty sessionScope.username}">
! Welcome ${sessionScope["username"]} !
<form action="LogoutController" method="POST">
<input type="submit" name="submit" value="Logout"/>
</form>
</c:if>
</h3>
</div>
<ul id="nav_list">
<li>Home</li>
<li>Product</li>
<li>Add Stock</li>
<li>Shopping Cart</li>
<li>Order Status</li>
<li>Register</li>
<li>Login</li>
</ul>
<br></br>
<p></p>
<c:if test="${!not empty sessionScope.username}">
<div id="registerForm" align="center"
style="border:1px solid black; width:760px" >
<form name="RegisterForm" action="RegisterController"
method="POST">
<p>
Username : <input type="text" id="username" name="username">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Password : <input type="password" id="password" name="password"
</p>
<p>
Name : <input type="text" id="name" name="name">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Address : <input type="text" id="address" name="address">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
State :
<select>
<option>Selangor</option>
<option>Kuala Lumpur</option>
<option>Cyberjaya</option>
<option>Putrajaya</option>
</select>
</p>
<p></p>
<input type="submit" name="submit" value="Register">
<input type="reset" name="clear" value="Clear">
<p></p>
</form>
</div>
</c:if>
</body>
</html>
Without further info the only suggestion I can think of is to add a querystring to your URLs. Like this:
Page 1
This way you can look at the actiuon parameter in the request to determine what to do in your controller.
You can add a request parameter. This can be done in 2 ways depending on whether your form has a method of POST or GET.
You have implemented the submit buttons in the forms with a name attribute of submit and different value attributes. This should mean that the requests will include a submit parameter in the query string or the POST form data. On the server side, you can use this to figure out which of the submit buttons was clicked.