I am learning Java CRUD Operation . I am trying to insert ,update and delete records from sql database.The insert and displaying all records methods is working but the problem is when I click edit and delete links ,its throw http 404 not found exception
Here is my HTML code display all the records .
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Posts</title>
</head>
<body>
<div style="width: 1200px; margin-left: auto; margin-right: auto;">
<table cellpadding="10">
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Detail</th>
<th>Category</th>
<th>Date</th>
<th>Image</th>
<th></th>
</tr>
<c:forEach items="${AllPost}" var="p">
<tr>
<td>${p.id}</td>
<td>${p.title}...</td>
<td>${p.description}...</td>
<td>${p.detail}...</td>
<td>${p.category}</td>
<td>${p.date}...</td>
<td>${p.image}...</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Here is the HTML for EidtPost.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit</title>
</head>
<body>
<h1>Edit News</h1>
<div style="width: 900px; margin-left: auto; margin-right: auto">
<c:forEach items="${getNewsById}" var="p">
<form action="JSP/ManagerEditPost.jsp" method="post">
<input type="hidden" name="id" value="${p.id}">
Title:<br>
<input type="text" value="${p.title}" name="title" style="width: 200px"><br>
Description:<br>
<input type="text" value="${p.description}" name="description" style="width: 200px"><br>
Detail:<br>
<textarea name="detail" style="width: 400px; height: 200px">${p.detail}</textarea><br>
Category:
<select name="category">
<option value="${p.category}">${p.category}</option>
<option value="World">World</option>
<option value="Tech">Tech</option>
<option value="Sport">Sport</option>
</select><br>
Image:<br>
<input type="text" value="${p.image}" name="image" style="width: 200px"><br>
<input type="submit" value="Submit">
</form>
</c:forEach>
</div>
</body>
</html>
Here is the Data Access code for CRUD operation.
public void edit(int id, String title, String description, String detail, String category, String image){
try {
String sql = "update News SET title = ?, description = ?, detail = ?, category = ?, image = ?" + " where id = ?";
PreparedStatement ps= DBUtils.getPreparedStatement(sql);
ps.setString(1, title);
ps.setString(2, description);
ps.setString(3, detail);
ps.setString(4, category);
ps.setString(5, image);
ps.setInt(6, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Here is the servlet code .
#WebServlet(name = "EditPost", urlPatterns = {"/EditPost"})
public class EditPost extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
{
String idTemp = request.getParameter("id");
int id = Integer.parseInt(idTemp);
request.setAttribute("getNewsById", DataAccess.getNewById(id));
RequestDispatcher rd = request.getRequestDispatcher("CRUD/EditPost.jsp");
try {
rd.forward(request, response);
} catch (ServletException | IOException ex) {
Logger.getLogger(EditPost.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>EditPost</servlet-name>
<servlet-class>servlet.EditPost</servlet-class>
</servlet>
<servlet>
<servlet-name>DeletePost</servlet-name>
<servlet-class>servlet.DeletePost</servlet-class>
</servlet>
<servlet>
<servlet-name>AllPost</servlet-name>
<servlet-class>servlet.AllPost</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>EditPost</servlet-name>
<url-pattern>/EditPost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeletePost</servlet-name>
<url-pattern>/DeletePost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AllPost</servlet-name>
<url-pattern>/AllPost</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Here is the screen shot of the error when i click the edit and delete link .
The following shows the minimum necessary to create the desired functionality. Obviously everything about the true implementation needs to be added.
Ultimately, the path in the .jsp needs to match to the #WebServlet path. Though the specific forwarding depends a bit on absolute vs. relative URLs.
This works in tomcat 9.0, but is likely applicable to other such servers such as glassfish, etc.
web.xml
This provides the basic information.
<web-app>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
welcome.jsp
This is just an example .jsp that provides an href.
<%# 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>
</head>
<body>
<h1>Hello World!</h1>
<!-- note this can also be ./EditPost -->
<!-- also note that not passing any query here -->
Edit Post
</body>
</html>
EditPost.java
This is a quick example of an annotated servlet.
#WebServlet("/EditPost")
public class EditPost extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public EditPost() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Related
I have to load some values from servlet to jsp page
My "order_processing.jsp" JSP Page code is given below
<%#page import="test.abc.io.User_Objects"%>
<%# page import="java.util.Date" %>
<%# 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>Order Processing</title>
</head>
<body>
<form name="OrderProcessing" action="order_processing" method="post" onsubmit="return validateForm();">
<table align="center">
<tr align="center">
<td colspan="2">
<img src="images/otn_logo.jpg"/>
</td>
</tr>
<tr>
<td>First Name :</td>
<td><input type="text" id="txtFirstname" name="txtFirstname" value="${reqObj.firstname}" /></td>
</tr>
<tr>
<td>Last Name :</td>
<td><input type="text" id="txtLastname" name="txtLastname" value="${reqObj.lastname}" /></td>
</tr>
<tr>
<td>Communication Email :</td>
<td><input type="text" id="txtCommunicationEmail" name="txtCommunicationEmail" value="${reqObj.commEmail}" />
<label style="color: red;">*</label></td>
</tr>
<tr align="left">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
My User_Objects code
public class User_Objects {
public String firstname;
public String lastname;
public String commEmail;
}
My "OrderProcessing" code
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OrderProcessing extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
User_Objects fillObj = new User_Objects();
fillObj.firstname = "Test";
fillObj.lastname = "User1";
fillObj.commEmail = "tuser01#xyz.com";
request.setAttribute("reqObj", fillObj);
RequestDispatcher view = request.getRequestDispatcher("/order_processing.jsp");
view.forward(request, response);
} catch (Exception e) {
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("into OrderProcessing java");
}
}
My web.xml code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>OrderProcessing</display-name>
<welcome-file-list>
<welcome-file>order_processing.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>order_processing</servlet-name>
<servlet-class>test.abc.io.OrderProcessing</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>order_processing</servlet-name>
<url-pattern>/order_processing</url-pattern>
</servlet-mapping>
</web-app>
When i debug this project and click on Submit button its gives the following error:
SEVERE: Servlet.service() for servlet jsp threw exception
javax.el.PropertyNotFoundException: Property 'firstname' not found on type test.abc.io.User_Objects
and I also want to do some task on "order_processing.jsp" page load.
but when i run this project, my order_processing.jsp page display successfully but on that case my doGet method of OrderProcessing.java did not call.
I am using JAVA with Eclipse Mars.
The object "User_Objects" is no java bean:
firstname, lastName and commEMail are fields and not properties.
Try to add a getter / setter for firstName, lastName and commEMail
I have two pages jsp pages First one is AppLogin.jsp and other one is Login.jsp
I want that when i click on Submit button of AppLogin.jsp page, i want redirect to Login.jsp page with password value
and check this value on page load of Login.jsp page.
For this i did following code
but the below code did not work.
I don't want to use Session and append value on url.
AppLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>App Login</title>
</head>
<body>
<form action="loginServlet" method="post">
<table>
<tr>
<td>Application Name</td>
<td><input type="text" value="" name="txtApplication" /></td>
</tr>
<tr>
<td>Username</td>
<td><input type="text" value="" name="txtUsername" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" value="" name="txtPassword" /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, ClientProtocolException {
try {
String password = req.getParameter("txtPassword");
req.setAttribute("crendential",password);
RequestDispatcher rd = req.getRequestDispatcher("Login.jsp");
rd.forward(req,res);
}
catch (Exception e) {
System.out.println("LoginServletException>>>>>>>>>>" + e);
}
}
}
Login.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>Login</title>
</head>
<body>
<form action="saveServlet" method="post">
<table>
<tr>
<td>Application :</td>
<td><input type="text" value="" name="txtApplication" /></td>
</tr>
<tr>
<td>Username :</td>
<td><input type="text" value="" name="txtUsername" /></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="text" value="" name="txtPassword" /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
public class SaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException {
try {
String crendential = (String) req.getAttribute("crendential");
System.out.println("crendential>>>>>>>>>>" + crendential);
}
catch (Exception e) {
System.out.println("LoginServletException>>>>>>>>>>" + e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String crendential = (String) req.getAttribute("crendential");
System.out.println("crendential>>>>>>>>>>" + crendential);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>xyz</display-name>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>xyz.io.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>save</servlet-name>
<servlet-class>xyz.io.SaveServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>save</servlet-name>
<url-pattern>/Login.jsp</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>AppLogin.jsp</welcome-file>
</welcome-file-list>
</web-app>
I am using Java with Eclipse Mars.
Login.jsp has a request attribute "credentials." To pass this value to the saveServlet there would be two possibilities:
Store the credentials instead as session attribute
Pass the credentials on in Login.jsp, say as hidden form input field.
<input type="hidden" name="credentials" value="${credentials}">
Correction:
I did miss the somewhat hard to digest web.xml with its servlet mappings.
In general how it often is done
A servlet mapping:
xyz.io.DisplayLoginServlet
/login
xyz.io.ProcessLoginServlet
/authorize
DisplayLoginServlet
doGet
prepares the form data (request attributes)
forwards to some displayLogin.jsp
doPost
validates the form, possibly redisplays the form with error messages (doGet)
otherwise when successfully done,
set session attributes
and redirect to the home page.
displayLogin.jsp
(posts to the same servlet)
And so on.
The mapped servlet URLs do not relate to JSPs.
The servlet is the entry point, the controller. It prepares the data model, puts them in the request attributes, and forwards to some JSP, the view. The servlet can on successfull login use an other JSP for instance.
Here we redirect after a successfull post. That is the brower is told to get the redirected page as answer. The effect is that the user cannot reload the page and effectively re-post the HTML form.
I think making a clean distinction will already help.
I am developing a Spring application that will do a basic CRUD operation.The login and after login the population of information is working properly.But when i trying to forward to a page from the main page i.e from where all the information is coming.The URL that is coming is strange and i can not find a reason behind that.i am posting my full code here...
web.xml
<display-name>SpringWebCrudExample</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="com.gamma.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
login.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>
Login Page
<form:form action="forms/doLogin" commandName="loginForm">
<table>
<tr>
<td>UserName:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:input path="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
mainpage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
main page is here all details will be shown here...
<c:url var="addUrl" value="/add" />
<table style="border: 1px solid; width: 500px; text-align:center">
<thead style="background:#fcf">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Address</th>
<th colspan="3"></th>
</tr>
</thead>
<td>Add</td>
<tbody>
<c:forEach items="${mainpage}" var="student">
<tr>
<td><c:out value="${student.fname}" /></td>
<td><c:out value="${student.lname}" /></td>
<td><c:out value="${student.address}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
AppController
#Controller
public class AppController {
public static DbImpl dbImpl;
#RequestMapping(value = "/start", method = RequestMethod.GET)
public static ModelAndView getAllinfo() {
ModelAndView mav = new ModelAndView("/mainpage");
System.out.println("mainpage is here");
List<StudentVO> allInfo = dbImpl.populateInfo();
System.out.println("The List is " + allInfo.size());
mav.addObject("mainpage", allInfo);
return mav;
}
#RequestMapping(value = "/doLogin", method = RequestMethod.GET)
public String ShowForm(Map model) {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
return "login";
}
#RequestMapping(value = "/doLogin", method = RequestMethod.POST)
public ModelAndView ProcessForm(#Valid LoginForm loginForm,
BindingResult result, Map model) {
String userName = "Jeet";
String passWord = "gamma";
if (result.hasErrors()) {
return new ModelAndView("login", "loginDetails", loginForm);
}
loginForm = (LoginForm) model.get("loginForm");
if (!loginForm.getUsername().equals(userName)
|| !loginForm.getPassword().equals(passWord)) {
return new ModelAndView("login", "loginDetails", loginForm);
}
model.put("loginForm", loginForm);
System.out.println("----->" + loginForm.getUsername());
RedirectView redirectView = new RedirectView("start", true);
return new ModelAndView(redirectView);
}
#RequestMapping(value="/add",method=RequestMethod.GET)
public String aMethod2insert(Map model){
StudentVO studentVO=new StudentVO();
model.put("studentVO", studentVO);
return "insertpage";
}
Now the problem is that when i am doing the login it is working fine and it is generating the URL SpringWebCrudExample/forms/start and coming to this page (the picture i attached here).Now i have added a link call add in this page from which i will go to a page where i will insert some vlaues, but the problem is here when i click on this URL it is giving SpringWebCrudExample/add this URL.As the result the page is not coming.
It has nothing to do with spring but with basic URL generation.
When you are prefixing a href with a / it means that this is an absolute URL and it will be navigated from the root of your application. If you leave it out it will be relative to the current URL.
Now lets take an application deployed at /app which has a servlet mapped at /servlet. If you are in a page at /app/servlet/page and you have a href like /foo it will result in the actual location of /app/foo. Leaving the / would lead to /app/servlet/foo.
For more information see Absolute vs relative URLs
I'm currently working on a school project. We have to do a small market website in Java.
I've a small problem. I have an Index.jsp where i want to include a servlet (RandomArticle.jsp). This servlet have a .jsp and a .java and just shuffle a collection and return names.
When I display index.jsp, the html of RandomArticle.jsp is well displayed (so the include is correct) but the returned name are "null".
Here is some code:
Index.jsp (in WebContent of eclipse)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Market</title>
</head>
<body>
<header>
<h1>market 2013</h1>
<h2>Bievenue </h2>
</header>
<nav>
<% String include = "/WEB-INF/RandomArticle.jsp"; %>
<jsp:include page='<%=include%>' />
</nav>
</body>
</html>
RandomArticle.jsp (in WEB-INF):
<h1>Liste des produits EpiMarket</h1>
<%
String productName1 = (String) request.getAttribute("productName1");
String productName2 = (String) request.getAttribute("productName2");
String productName3 = (String) request.getAttribute("productName3");
%>
<p>Acheter <% out.println(productName1); %></p>
<p>Acheter <% out.println(productName2); %></p>
<p>Acheter <% out.println(productName3); %></p>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Market</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>fr.market.servlets.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RandomArticle</servlet-name>
<servlet-class>fr.market.servlets.RandomArticle</servlet-class>
</servlet>
</web-app>
and RandomARticle.java
public class RandomArticle extends HttpServlet {
private ArrayList<Object> allProducts;
public String getProductName(int index){
return (((AbstractProduct) allProducts.get(index)).getName());
}
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
ADAO<AbstractProduct> dao = new DAOProduit();
allProducts = ((DAOProduit) dao).getAll();
Collections.shuffle(allProducts);
request.setAttribute("productName1", getProductName(0));
request.setAttribute("productName2", getProductName(1));
request.setAttribute("productName3", getProductName(2));
this.getServletContext().getRequestDispatcher( "/WEB-INF/RandomArticle.jsp" ).forward( request, response );
}
}
I think that the .java is never called, but I don't understand why.
Thanks for your time.
Gilles
I have a simple JSP project, which has 3 classes, controllers and DAO's
I can Login but when I click on my buttons, I just can't get the Parameters from the form.
Lemme show the code, and maybe You'll figure it out:
package school.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import school.dao.StudentDAO;
import school.model.Student;
public class StudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String UPDATE = "/student.jsp";
private static String VIEW_COURSES = "CourseController";
private static String VIEW_GRADES = "GradeController";
private StudentDAO dao;
public StudentController() {
dao = new StudentDAO();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String forward = "";
String action = request.getParameter("name");
if (action.equalsIgnoreCase("update")) {
forward = UPDATE;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewgrades")) {
forward = VIEW_GRADES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewcourses")) {
forward = VIEW_COURSES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
And here's the WEB.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>School_JSP</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>CourseController</display-name>
<servlet-name>CourseController</servlet-name>
<servlet-class>school.controller.CourseController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>StudentController</display-name>
<servlet-name>StudentController</servlet-name>
<servlet-class>school.controller.StudentController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>school.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentController</servlet-name>
<url-pattern>/StudentController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CourseController</servlet-name>
<url-pattern>/CourseController</url-pattern>
</servlet-mapping>
</web-app>
And the mainPage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Main Page</title>
</head>
<body>
<h3>
Welcome,
<c:out value="${student.firstName}" />
</br>
<h1>My Personal Information</h1>
<center>
<form method="POST" action='StudentController' name="viewgrades">
<input type="submit" value="View My Grades" />
</form>
<form method="POST" action='StudentController' name="viewcourses">
<input type="submit" id="hidden" value="View My Courses" />
</form>
<form method="POST" action='StudentController' name="update">
<input type="submit" id="hidden" value="Update Personal Information" />
</form>
</center>
</h3>
</body>
</html>
You're confusing attributes and parameters.
Parameters are String values sent by the browser. They're accessed using the getParameterXxx() family of methods.
Attributes are data that you can add to a request (or session, or servlet context), or any type, in order to get them backlater. You typically add an attribute to the request in a servlet (for example, the information about the logged in user) in order to get back this attribute in the JSP and display the information.
In your code, the only place where you get a parameter is commented out. And you're trying to get a parameter named "hidden", although none of the form has an input field with than name. It's the name attribute of an input field that is submitted by the browser, and not its id attribute.
Also, you should use GET rather than POST for actions which consist in getting or reading things.
The reason you don't get any values is that the attribute "name" in the form, indeed is just the name of the form and isn't sent at all.
To actually send data, you need to provide some in the innerHTML of the form. Like this (not the best solution, but should you get running):
<form method="GET" action="StudentController" name="formName">
<input type="hidden" name="viewgrades" value="show" />
<input type="submit" value="View My Grades" />
</form>
After this you can read the sent data "viewgrades=show" (parameter=value) in your Java-class.
Also, btw, you shouldn't use "h3" as a paragraph ("p") or section. It is intended to be a headline.