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.
Related
I'm develop simple Spring boot app using Thymeleaf and want to display selected "user" from Combobox1 at the "userName" text field. How i can made it?
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>Добавить цитату</title>
</head>
<body>
<form th:action="#{/addQuote}"
th:object="${personForm}" method="POST">
<p><b>Имя</b><br>
<div>
<input name = "userName" type="text" size="38" th:field="*{name}" >
<a style="position:fixed;left:0px;top:0px;margin: 0;border-width:0;z-
index:255"></a>
</div>
<textarea name="comment" cols="40" rows="6" th:field="*{text}" >
</textarea>
<p><input type="reset" value="Отменить">
<input type="submit" value="+"></p>
<select name="Combobox1" size="1" id="Combobox1"
style="position:absolute;left:17%;top:4%;width:199px;height:20px;z-
index:3;" >
<option th:each="user : ${users}"
th:value="${user}"
th:utext="${user}"/>
</select>
</form>
<div th:if="${errorMessage}" th:utext="${errorMessage}"
style="color:red;font-style:italic;">
</div>
</body>
</html>
Option 1:
Add Id in your userName input tag
<input id="userName" name = "userName" type="text" size="38" th:field="*{name}" />
Add script
<script>
function check() {
document.getElementById("userName").value=document.getElementById("Combobox1").value;
}
</script>
Call script function
<select id="Combobox1" onChange="check();">
Option2:
Another option with Jquery
$(function() {
$("#Combobox1").on("change",function() {
alert();
$("#userName").val($(this).val());
});
});
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 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.
code:
<script type="text/javascript">
function showFileName() {
var filename = document.getElementById("uploadFile");
}
</script>
OR
<script type="text/javascript">
var filename = document.getElementById("uploadFile");
</script>
OR
var filename="uploadedfilename";
<form name="AttachmentsForm" method="post" action="<%=Constants.WEB_APP_NAME%><%=Constants.SERVLET_NAME%>?para=ajaxRefTabUpload&action=add&uploadfilename="+filename+"" ENCTYPE="multipart/form-data">
<table class="innerBorderTable" width="100%">
<tr>
<td>Attach New File:</td>
<td>
<INPUT TYPE="FILE" NAME="uploadFile" width="120">
<input type="submit" class="button" value="Add Attachment">
</td>
</tr>
</table>
</form>
I tried 3 different approaches to pass it with +filename+ i am getting null with uploadfilename in action parameter
Please advise
use of scriptlets(<% %>) in JSP highly discouraged, use JSTL(<c:tags) or Expression Language(${})
to use JSTL in your jsp download jstl.x.x.jar file and add it to your buildpath.
then, add this
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
in top of jsp.
to resolve form action url you have:
<%=Constants.WEB_APP_NAME%><%=Constants.SERVLET_NAME%>
no need of any constants for that, instead use <c:url tag to resolve url like:
<c:url value="/yourServletUrl" var="postUrl"/>
<form action="${postUrl}" method="post" ...
i am getting null with uploadfilename in action parameter
because, you accessing javascript variable in html(&uploadfilename="+filename+"), instead do like:
jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>your title</title>
</head>
<body>
<c:url value="/yourServletUrl" var="postUrl"/>
<form id="AttachmentsForm"
method="post"
onSubmit="showFileName()"
action="${postUrl}para=ajaxRefTabUpload&action=add"
enctype="multipart/form-data">
<table class="innerBorderTable" width="100%">
<tr>
<td>Attach New File:</td>
<td>
<input type="file" name="uploadFile" width="120">
<input type="submit" class="button" value="Add Attachment">
</td>
</tr>
</table>
</form>
<script type="text/javascript">
function showFileName(e) {
if (e.preventDefault)
e.preventDefault();
var filename = document.getElementById("uploadFile");
alert('fileName: '+filename);
//here, attach filename to from action and continue your form submition by AJAX
// You must return false to prevent the default form behavior
return false;
}
}
</script>
</body>
</html>
Try something like:
function showFileName() {
document.forms[0].action ="<%=Constants.WEB_APP_NAME%>... //Here goes the expression you want to set the action to
}
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.