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.
Related
I have to submit name from the form and receive the value in GET method.
Received value in URL should be shown up on top of form as a list.
I want to show all input from form submit as unordered list.
But my code only shows the latest input.
Friend class has
private String friend and getter setters.
#Controller
public class FriendController {
#GetMapping(value = "/index")
public String friendForm(#RequestParam(value = "friend", required = false) Friend friend, Model model) {
List<Friend> fList = new ArrayList<Friend>();
fList.add(friend);
model.addAttribute("friends", fList);
model.addAttribute("friend", new Friend());
return "result";
}
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Friends List</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1 th:text="'My Friends'"></h1>
<ul>
<li th:each="friend: ${friends}" th:text="${friend}"></li>
</ul>
<h1 th:text="'Add a new friend to List'"></h1>
<form action="#" th:action="#{/index}" th:object="${friend}"
method="get">
<table>
<tr>
<td>Name: <input type="text" th:field="*{friend}" /></td>
</tr>
</table>
<p>
<input type="submit" value="Submit" />
</p>
</form>
</body>
</html>
I can't get the checkbox value of "no_del_file" into the servlet.
here is my JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>List of Command menu</title>
</head>
<body>
<div><b>${reply}</b></div>
<div id="wrapper">
<div id="menu">
<form action="runButtonCommand" method="post" name="myform">
<a href="runButtonCommand?param1=list apps" >List1</a><br/><br/>
<a href="runButtonCommand?param1=list data" >List2</a><br/><br/>
<br/><br/>
no del:
<%String test = (String)request.getParameter("no_del_file"); %>
<%String checked = "";%>
<%
if ("on".equals(test)) {
checked="checked=\"on\"";
} %>
<input type="checkbox" name="no_del_file" <%=checked%>>
<br />
</form>
</div>
<div id="output">
<p>Output:</p>
<textarea style="resize: none;" data-role="none" rows="40" cols="120" name="outputarea">
${data}
</textarea>
</div>
</div>
</body>
</html>
And here is the Servlet part where I try to get the checkbox value:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String[] tester= request.getParameterValues("no_del_file");
System.out.println("Start: "+tester);
performTask(request, response);
}
However it doesn't matter if I use getParameterValues, getParameter or getAttribute I always get null if checked or unchecked. How can I get that value?
Thanks for your help.
Viking
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.
I am new to Ajax, Jquery, JSON stuff. I have created one login page in jsp servlet technology. On login page, when user presses submit button, data gets collected in JSON and transferred to controller through AJAX. Now, in controller if on some condition, login name found to be correct, then it should use RequestDispatcher to dispatch it to success page. However if condition not satisfied, then it should write the message in JSON object and return it as content type json. Now the problem is that I am able receive JSON data on controller, but not able to redirect on success and also not able to show alert box to user if he entered wrong data. Below are the files:
login.jsp
<%# 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>Insert title here</title>
<script>
function validateAndSet()
{
var jsonRequest = {};
var login_name = $.trim($('#loginName').val());
var password = $.trim($('#password').val());
if(login_name=='' || login_name.length==0 ){
alert("Please enter login name.");
$('#loginName').focus();
return false;
}
if(password=='' || password.length==0 ){
alert("Please enter password.");
$('#password').focus();
return false;
}
jsonRequest["login_name"] = login_name;
jsonRequest["password"] = password;
return jsonRequest;
}
</script>
</head>
<body>
<jsp:include page="commonResources/Header.jsp">
<jsp:param value="none" name="headerMenu"/>
</jsp:include>
<script>
$(document).ready(function(){
$("#but").click(function(){
var formData=validateAndSet();
var strUrl="rwcntrlr.do?action=loginForm";
$.post(strUrl, {jsonData: JSON.stringify(formData)},function(response){
response = jQuery.parseJSON( response);
if(response.status=='NOT OK')
{
alert("not ok");
}
else{
alert('OK');
}
});
});
});
</script>
<br><br>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div class="container-fluid">
<div class="panel panel-default" id="p1">
<div class="panel-heading"><h3>Login</h3></div>
<div class="panel-body">
<center>
<table>
<tr>
<td height="50">LoginName:</td><td height="50"><input type="text" id="loginName" name="loginName"/></td>
</tr>
<tr>
<td height="20">Password:</td><td height="20"><input type="password" id="password" name="password"/></td>
</tr>
<tr><td height="50" colspan="2" align="right"><input type="submit" id="but" name="subBut" value="Go>" /></td></tr>
</table>
</center>
</div>
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
</body>
</html>
controller servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formName=request.getParameter("action");
if(formName.equalsIgnoreCase("loginForm")){
String strJSONData = request.getParameter("jsonData");
System.out.println(strJSONData);// data received correctly...
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(strJSONData);
String login_name = requestedJSONObject.getString("login_name");
String password = requestedJSONObject.getString("password");
if(login_name.equalsIgnoreCase("u2")){
RequestDispatcher rd=request.getRequestDispatcher("employeeSection/employeeDailySheet.jsp");
response.setContentType("text/html");
rd.forward(request, response);
}
else{
jsonResponse.put("status", "NOT OK");
response.setContentType("application/json");
response.getWriter().write(jsonResponse.toString());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I presses submit button on login.jsp, nothing happens. No console error is shown. What should I do to resolve this problem.
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.