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?
Related
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);
}
}
I want to sent parameter from JSP to HTTP Servlet. but it doesn't work:(
I would like create a button to sent information to disable/enable user.
I'm still new to JSP and HTTP.
I hope can some one help me.
I hope it's enough to Overview
here my code:
admin.jsp
<%#page import="model.*"%>
<%#page import="java.util.*"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
List<Category> categories = (List<Category>) request.getAttribute("categories");
List<User> users = (List<User>) request.getAttribute("users");
User credentials = (User) request.getSession().getAttribute("credentials");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<jsp:include page="header.jsp"></jsp:include>
<jsp:include page="/WEB-INF/navbar.jsp"></jsp:include>
<h1 style="color:green;">Admin Control Page</h1>
<h2>categories</h2>
<% for (Category category : categories) { %>
<%=category.getName()%><br/>
<% } %>
<form method="post" action="<%=request.getContextPath()%>/admin" accept-charset="iso-8859-1">
<br/>
add new category: <input name="categoryName" />
<input type="hidden" name="event" value="createCategory" />
<input type="submit" />
</form>
<h2>users</h2>
<% for (User user : users){
if(user.getRole().getId()!= 1){
out.println("<a href='"+request.getContextPath()+"/user/"+user.getUsername()+"'><b>"+user.getUsername()+"</b></a>");
int id = user.getId();
%>
<%if(user.isEnabled()){ %>
//My Problem is here
<form action="/admin" method="POST">
<input value="<%user.getId();%>">
<input type="submit" value="Submit" />
</form>
<%}else if(!user.isEnabled()){
%>
// TODO Button
<%}%>
<p><hr>
<%
}
}
%>
</body>
</html>
AdminController.java
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.DatabaseManager;
import model.Category;
import model.User;
#WebServlet("/admin/*")
public class AdminController extends HttpServlet {
private DatabaseManager db = DatabaseManager.getInstance();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// check admin, if not "error"
User user = (User) req.getSession().getAttribute("credentials");
if (user == null || !user.getRole().getName().equals("admin")) {
resp.sendError(403);
return;
}
// load page
req.setAttribute("categories", db.getCategoryDAO().findAll());
req.setAttribute("users", db.getUserDAO().findAll());
req.getRequestDispatcher("/WEB-INF/admin.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// event
String event = req.getParameter("event");
// create new category
if (event.equals("createCategory")) {
String categoryName = req.getParameter("categoryName").trim();
try {
Category cat = new Category();
cat.setName(categoryName);
db.getCategoryDAO().create(cat);
} catch (IllegalArgumentException e) {
// error
req.setAttribute("msg", e.getMessage());
doGet(req, resp);
return;
}
// Create successful
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
String idTemp = req.getParameter("id");
try{
int id = Integer.parseInt(idTemp);
User user = db.getUserDAO().findById(id);
user.setEnabled(false);
} catch(IllegalArgumentException e){
e.getMessage();
return;
}
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
}
Change
#WebServlet("/admin/*")
To
#WebServlet("/admin")
And you can use either:
action="<%=request.getContextPath()%>/admin" or action="admin".
And if you are still having error then mention the error name :)
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>
I'm using Spring MVC 3 with Hibernate. And I'm stuck with displaying the image. I am perfectly able to upload the image but I am unable to display it after the successful upload. Please suggest me where I had stepped wrong .below is the code i am trying.
This is my controller:
private String uploadFolderPath;
ServletConfig config;
public String getUploadFolderPath() {
return uploadFolderPath;
}
public void setUploadFolderPath(String uploadFolderPath) {
this.uploadFolderPath = uploadFolderPath;
}
#RequestMapping(value = "/uploadfile",method = RequestMethod.GET)
public String getUploadForm(Model model) {
model.addAttribute(new UploadItem());
return "/uploadfile";
}
#RequestMapping(value = "/uploadfile",method = RequestMethod.POST)
public String create(UploadItem uploadItem, HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors,
HttpSession session) {
try {
MultipartFile filea = uploadItem.getFileData();
InputStream inputStream = null;
OutputStream outputStream = null;
if (filea.getSize() > 0) {
inputStream = filea.getInputStream();
// File realUpload = new File("C:/");
outputStream = new FileOutputStream("C:\\images\\"
+ filea.getOriginalFilename());
System.out.println("====22=========");
System.out.println(filea.getOriginalFilename());
System.out.println("=============");
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
System.out.println("===ddd=======");
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
session.setAttribute("uploadFile", "C:\\images\\"
+ filea.getOriginalFilename());
}
} catch (Exception e) {
e.printStackTrace();
}
return "uploadfileindex";
}
#RequestMapping(value = "/uploadfileindex",method = RequestMethod.GET)
public String showRegistration(Model model) {
return "uploadfileindex";
}
// Process the form.
#RequestMapping(value = "/uploadfileindex",method = RequestMethod.POST)
public String processRegistration(BindingResult result) {
return "uploadfileindex";
uploadfile jsp
<%#page contentType="text/html;charset=UTF-8"%>
<%#page pageEncoding="UTF-8"%>
<%# page session="false"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<META http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Upload Example</title>
<script language="JavaScript">
function Validate()
{
var image =document.getElementById("image").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg");
document.getElementById("image").focus();
return false;
}
}
return true;
}
</script>
</head>
<body>
<form:form modelAttribute="uploadItem" name="frm" method="post"
enctype="multipart/form-data" onSubmit="return Validate();">
<fieldset><legend>Upload File</legend>
<table>
<tr>
<td><form:label for="fileData" path="fileData">File</form:label><br />
</td>
<td><form:input path="fileData" id="image" type="file" /></td>
</tr>
<tr>
<td><br />
</td>
<td><input type="submit" value="Upload" /></td>
</tr>
</table>
</fieldset>
</form:form>
</body>
</html>
uploadfileindex.jsp
<%#page contentType="text/html;charset=UTF-8"%>
<%#page pageEncoding="UTF-8"%>
<%# page session="true"%>
<%#taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<META http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Welcome</title>
</head>
<body>
<h2>Upload Example</h2>
<%
if (session.getAttribute("uploadFile") != null
&& !(session.getAttribute("uploadFile")).equals("")) {
%>
<h3>Uploaded File</h3>
<br>
<img src="<%=session.getAttribute("uploadFile")%>" alt="Upload Image" />
<%
session.removeAttribute("uploadFile");
}
%>
</body>
</html>
As you are saying that you have that image on your hard drive but you are not able to display it over the web page. So what you need to do is, place your image in the installation directory that is from where the MVC is installed. Like is we use an WAMP server, we store image in wamp\www\yourprojectfolder\image.jpg. Like this you'll be fetching your image directly through the web page.
#Controller
#RequestMapping(value="/imageServer")
public class ImageServer {
#RequestMapping(value="/{imageUrl:.+}")
public void getImageByUrl(#PathVariable String imageUrl,
HttpServletResponse response) throws IOException
{
String filesFolder = "C:/images";
File finalImage = new File(filesFolder+"/"+imageUrl);
FileInputStream fileStream=new FileInputStream(finalImage);
try {
response.getOutputStream().write(IOUtils.toByteArray(fileStream));
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
And on your JSP Page, go for :
<img src"${pageContext.request.contextPath}/imageServer/image.jpg">
So you can see C:/images/image.jpg in your webo page.
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);
}