URL Redirect in Servlet after form - java

In my Java web app I have a unique Front Controller which maps all the requests, and various controllers that execute the logic and return a string representing the next page the user is forwarded to.
This works, but when I submit a form with post method, the form action gets appended to the URL in the address bar. For example, if the login method in LoginController returns false (so that nextPage="/index.jsp"), it correctly redirects to that page, but in the address bar I'll have /MyAPP/app/home.jsp anyway. Is there a way to avoid this?
I took a look to the Post/Redirect/Get pattern, but I'd like to figure out how can I implement this without aggressively changing the structure.
#WebServlet("/app/*")
public class FrontController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<String, Controller> controllers = new HashMap<String, Controller>();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String pathInfo = req.getPathInfo();
String controllerName = pathInfo.substring(pathInfo.lastIndexOf('/'));
Controller c = controllers.get(controllerName);
String resource = c.action(req, resp);
req.getRequestDispatcher(resource).forward(req, resp);
}
#Override
public void init() throws ServletException {
super.init();
controllers.put("/index.jsp", new IndexController());
controllers.put("/home.jsp", new LoginController());
}
}
public class LoginController implements Controller {
private static final String USERNAME_PARAM = "username";
private static final String PASSWORD_PARAM = "password";
private static final String USERBEAN_ATTR = "userBean";
public String action(HttpServletRequest request, HttpServletResponse response) {
String username = request.getParameter(USERNAME_PARAM);
String password = request.getParameter(PASSWORD_PARAM);
boolean result = false;
UserBean userBean = (UserBean)request.getSession().getAttribute(USERBEAN_ATTR);
userBean.setUsername(username);
userBean.setPassword(password);
if (!username.isEmpty() && !password.isEmpty())
result = userBean.doLogin();
String nextPage = result ? "/home.jsp" : "/index.jsp";
if (!result)
request.setAttribute("error", "Login Error");
return nextPage;
}
}
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Welcome!</title>
</head>
<body>
<h1>Welcome</h1>
<form
action="${pageContext.request.contextPath}/app/home.jsp"
method="post">
Username: <input type="text" name="username"> <br>
Password: <input type="text" name="password"> <br> <input
type="submit" value="Log In" />
</form>
<p>${error}</p>
</body>
</html>

Related

Submitting a post method doesn't redirect to target page using Servlets

I have followed many tutorials.
the login page (index.jsp) opens, but when I submit it doesn't redirect (go to welcome page (welcome.jsp)) and gives error 404
im new to using servlets as you can see, any help will be appreciated
login class
#WebServlet(name = "login" ,urlPatterns = "/login")
public class Login extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("index.jsp");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String password = req.getParameter("password");
if (name.equalsIgnoreCase("ahmad") && password.equalsIgnoreCase("ahmad")) {
resp.sendRedirect("welcome.jsp");
} else {
resp.sendRedirect("index.jsp");
}
}
}
index.jsp
<html>
<head>
<title>login</title>
</head>
<body>
<form action = "/login" method = "post">
Name : <input name = "name" type = "text" />
Password : <input name = "password" type = "password" />
<input type = "submit" />
</form>
</body>
</html>
welcome.jsp
<html>
<head>
<title>welcome</title>
</head>
<body>
<p><font color="red">welcome</font></p>
</body>
</html>
Error Description:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

How to retrieve request attributes from a servlet?

I'm creating a basic website where you can add products to a database. The problem is when completing the form for adding a product in the JSP file. I'm able to submit the form but no response is retrieved from the servlet. Once the form is submitted the form is empty again. This happens repeatedly unless I force a FormatNumberException to occur. I've been searching but I couldn't find a solution yet.
Thanks in advance for your help.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Ingrese un producto
<hr>
<% if(request.getAttribute("mensaje")!= null){
out.print(request.getAttribute("mensaje"));
}
%>
<form action="IngresarServlet" method="POST">
Descripción: <input type="text" name="descr"/><br>
Precio: <input type="text" name="precio"/><br>
<input type="submit" value="enviar">
</form>
</body>
#WebServlet(name = "IngresarServlet", urlPatterns = {"/IngresarServlet"})
public class IngresarServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String descripcion = request.getParameter("descr");
Double precio = Double.valueOf(request.getParameter("precio"));
Producto p = new Producto(descripcion, precio);
ProductoDAO dao = new ProductoDAO();
try {
dao.insertar(p);
request.setAttribute("mensaje", "El producto se ha insertado correctamente.");
} catch (Exception ex) {
request.setAttribute("mensaje", ex.getMessage());
}
request.getRequestDispatcher("Ingresar.jsp").forward(request, response);
}
}

Are the request and response in filters the same as in servlets?

I am facing this error which throws
"Warning: StandardWrapperValve[AddServlet]: Servlet.service() for servlet > AddServlet threw exception
java.lang.NullPointerException"
I am not sure if it is caused by the ServletRequest's session not being the same as HttpServletRequest's session which causes the null exception when "results is being retrieved".
Is there any suggestion to fix this?
I am thinking of adding the numbers and checking if the result is more than 10 using the filter
The following is the code I have written and run:
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="AddServlet" method="post">
Enter 1st number: <input type="text" name="num1"><br>
Enter 2nd number: <input type="text" name="num2"><br>
<input type="submit">
</form>
</body>
</html>
AddServlet.java
#WebServlet(urlPatterns = {"/AddServlet"})
public class AddServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//retrieve from HTML
int i = Integer.parseInt(request.getParameter("num1"));
int j = Integer.parseInt(request.getParameter("num2"));
int k = i+j;
System.out.println(k);
HttpSession session = request.getSession();
session.setAttribute("result", k);
out.print(k);
}
}
ResultsFilter.java
#WebFilter(filterName = "ResultsFilter", urlPatterns = {"/AddServlet"})
public class ResultsFilter implements Filter {
public ResultsFilter() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
int ans = (int) session.getAttribute("result"); <-- error from here
System.out.println(ans);
if (ans <= 10) {
PrintWriter out = response.getWriter();
out.print("Result must be more than 10!");
} else {
chain.doFilter(request, response);
}
}
}

"Action" doesn't change in servlet even when changed in jsp

I have taken form information and populated an arraylist with each form object. Now I want to display each form object onto a new jsp called displayEvent.jsp. However, on displayEvent.jsp, I set the pointer to my servlet and method get as well as change "action" to "display", but my servlet doesnt seem to recognize that the action has changed.
displayEvent.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<c:import url="/includes/header.html" />
<c:import url="/includes/navigation.html" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" href="styles/main.css" type="text/css"/>
</head>
<body>
<div class="float-box1">
<h1>Nice Strike!</h1>
<img src="https://usatftw.files.wordpress.com/2018/04/epa_italy_soccer_serie_a.jpg?w=1000&h=600&crop=1" alt="Bicycle Kick" height="500" width="500">
</div>
<div class="float-box">
<h2>Reserved Field Times</h2>
<c:forEach var="event" items="${eventList.events}">
<tr align="center">
<td>${event.eventTitle}</td>
<td>${event.description}</td>
<td>${event.fieldNumber}</td>
<td>${event.date}</td>
<td>${event.startTime}</td>
<td>${event.stAMPM}</td>
<td>${event.endTime}</td>
<td>${event.etAMPM}</td>
</tr>
</c:forEach>
<form action="AddEventServlet" method="get">
<input type="hidden" name="action" value="display">
</form>
</div>
<div style="clear: both;"></div>
</body>
<footer>
<p1><c:import url="/includes/footer.jsp" /></p1>
</footer>
</html>
AddEventServlet.java:
public class AddEventServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String url = "/index.jsp";
HttpSession session = request.getSession();
EventList eventList = new EventList();
request.setAttribute("eventList", eventList);
// get current action
String action = request.getParameter("action");
System.out.println(action);
if (action == null) {
action = "home"; // default action
}
if (action.equals("add")) {
// get parameters from the request
String eventTitle = request.getParameter("Event Title");
String description = request.getParameter("Description");
String fieldNumber = request.getParameter("Field Number");
String date = request.getParameter("Date");
String startTime = request.getParameter("Start Time");
String stAMPM = request.getParameter("stAMPM");
String endTime = request.getParameter("End Time");
String etAMPM = request.getParameter("etAMPM");
System.out.println("hello world");
System.out.println(eventTitle);
System.out.println(description);
System.out.println(fieldNumber);
System.out.println(date);
System.out.println(startTime);
System.out.println(stAMPM);
System.out.println(endTime);
System.out.println(etAMPM);
// use regular Java class
Event event = new Event(eventTitle, description, fieldNumber, date, startTime, stAMPM, endTime, etAMPM);
eventList.addEvent(event);
System.out.println(event.toString());
// store the Event object in request and set URL
request.setAttribute("event", event);
url = "/enterEvent.jsp";
request.setAttribute("successfulEntry", "Successfully entered event!");
request.getRequestDispatcher(url)
.forward(request, response);
}
if (action.equals("home")) {
url = "/index.jsp"; // the "index" page
request.getRequestDispatcher(url)
.forward(request, response);
} else if (action.equals("display")) {
System.out.println("hello reeeee");
String eventTitle = request.getParameter("eventTitle");
String description = request.getParameter("description");
String fieldNumber = request.getParameter("fieldNumber");
String date = request.getParameter("date");
String startTime = request.getParameter("startTime");
String stAMPM = request.getParameter("stAMPM");
String endTime = request.getParameter("endTime");
String etAMPM = request.getParameter("etAMPM");
request.getAttribute("eventList");
if (eventList == null) {
eventList = new EventList();
}
request.setAttribute("eventList", eventList);
url = "/displayEvent.jsp";
System.out.print(eventList);
request.getRequestDispatcher(url)
.forward(request, response);
}
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
<servlet>
<servlet-name>AddEventServlet </servlet-name>
<servlet-class>AddEventServlet </servlet-class>
</servlet>
Have you set mapping attribute on web.xml?

Hang Man Game in MVC with JSP

I want to create Hang man game, but I need to save the session and the username, but I have problems for pass the username. I wrote the JSP, servlet and Javabean, but after the login my user, in the next view I only have Welcome + NULL. Help me please. thanks for the help.
I don't know how Can I pass the name to the next view.
enter code here
this is the JavaBean(Userdata.java):
public class Userdata {
String userName;
public Userdata() {
}
public Userdata(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
This is the servlet, in this code I need to use a session, but I want to that, in all the time that the user is logging, cans see his/her name
loginServlet.java
public class loginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata = new Userdata(usuari);
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", username);
RequestDispatcher view = request.getRequestDispatcher("juego.jsp");
view.forward(request, resp);
}
}
Finally the Views in JSP, The first view is the login
Nom de jugador:
Contrasenya:
And this is the response of servlet -> juego.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Penjat</title>
</head>
<h2>Benvingut</h2>
<%=request.getAttribute("usuari")%>
<div align="center">
<h1>Joc del Penjat</h1>
</div>
<div align="center">
<!--Delaració d'imatges-->
<img src="Imatges/p_JEE_3.png">
</div>
<div align="center">
<!--Declaració de les lletres-->
Lletra:
<input type="text" name="lletra" size="1" maxlength="1">
<br/>
<p>
<input type="hidden" name="id" value=""/>
<input type="hidden" name="vegades_jugades" value=""/>
<input type="hidden" name="pistes" value=""/>
<input type="submit" name="boto_jugar" value="Jugar">
</p>
</div>
First you have to put username in request, in your servlet use request.setAttribute in the following manner
request.setAttribute("username", value);
where value happens to be the object you want to read later.
Use it later in a different servlet/jsp using request.getAttribute as
String value = (String)request.getAttribute("username")
or
<%= request.getAttribute("username")>
Thanks for your help, now I understand, I modificated and now I can get the username.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata usuari = new Userdata();
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", usuari);
RequestDispatcher view = request.getRequestDispatcher("juegoOriginal.jsp");
view.forward(request, resp);
}

Categories

Resources