doPost() is not being called from my jsp - servlets

when i click on submit button ....servlet is not being called..
it shows the same index.jsp page...
where is the error I am unable to find..Please help me out
//here my jsp
Name
Gender
Male
Female
Email
Password
Contact
//here is my web.xml
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>servlet.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
//here my Register.java
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.print("something");
try {
processRequest(request, response);
UserModal user=new UserModal();
user.setName(request.getParameter("uname"));
user.setGender(request.getParameter("usex"));
user.setEmail(request.getParameter("uemail"));
user.setPassword(request.getParameter("upass"));
user.setContact(request.getParameter("ucontact"));
boolean result=new UserService().registerUser(user);
if(result){
response.sendRedirect("welcome.jsp");
}
else{
response.sendRedirect("index.jasp?msg=fail");
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex);
}
}

Please refer following link with some jsp-servlet example. You can get more idea about servlet doPost() calling.
Crunchify.com
met.guc.edu.eg
docs.oracle.com

Related

Running methods depending JSP link using switch statements on Servlets [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?
(7 answers)
Closed 1 year ago.
Hi there I am fairly new to building web pages using JSP and servlets and I'm trying to use switch statements to run functions depending on the link/button the user clicks but every code I've tried fails to run the function or redirect to new page, any help would be appreciated i tried using html tag and request.getContextPath but no avail... it returns 404 error or returns a blank page
Here is my servlet code
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public StudentServlet() {
this.studentDao = new StudentDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sPath = request.getServletPath();
//switch statement to call appropriate method
switch (sPath) {
case "/new":
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/insert":
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/delete":
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/update":
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/edit":
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
default:
try {
listAllStudents(request, response);
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
}
}
// functions to fetch data from studentDao and display data on appropriate jsp
private void listAllStudents(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
List<Student> allStudents = studentDao.selectAllStudents();
request.setAttribute("listStudents", allStudents);
RequestDispatcher dispatch = request.getRequestDispatcher("student-list.jsp"); //home page week04/StudentServlet | list all objects from table
dispatch.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
dispatch.forward(request, response);
}
private void insertStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
String name = request.getParameter("name");
String email = request.getParameter("email");
Student newStudent = new Student(name, email);
studentDao.insertStudent(newStudent); //student object inserted to table
response.sendRedirect("listStudents"); //redirect to home page
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
studentDao.deleteStudent(id); //student object deleted
response.sendRedirect("listStudents");
}
private void updateStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
Student updateStudent = new Student(id, name, email);
studentDao.updateStudent(updateStudent); //student object updated
response.sendRedirect("listStudents");
}
private void editStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Student currentStudent = studentDao.selectStudent(id);
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
request.setAttribute("student", currentStudent); //student object updated
dispatch.forward(request, response);
}
}
and here is my jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*" import="week04.model.Student"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-... " crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand">XYZ University</a>
</nav>
<div class="container">
<div class="container-fluid p-4">
<a href="/new" class="btn btn-success" action="/new">Add
Student</a>
</div>
<br>
<!--Assigning ArrayList object containing student data to the local object -->
<% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"); %>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<%
if(request.getAttribute("listStudents") != null) {
Iterator<Student> iterator = studentList.iterator();
while(iterator.hasNext()) {
Student studentDetails = iterator.next();
%>
<tr><td><%=studentDetails.getId()%></td>
<td><%=studentDetails.getName()%></td>
<td><%=studentDetails.getEmail()%></td>
<td>Update
Delete</td>
</tr>
<%
}
}
%>
</tbody>
</table>
</div>
</div>
</body>
</html>
and here is my xml file
<?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/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://java.sun.com/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee" id="WebApp_ID" version="2.4">
<servlet>
<description></description>
<display-name>StudentServlet</display-name>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>week04.web.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/StudentServlet</url-pattern>
</servlet-mapping>
</web-app>
Any help on what i'm doing wrong would be appreciated.
You need to tell the servlet in the web.xml that it processes the specified URLs.
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/StudentServlet</url-pattern>
<url-pattern>/new</url-pattern>
</servlet-mapping>
Additionally, href must be specified correctly.
<div class="container-fluid p-4">
Add Student
</div>

StopWatch#stop(), throwing NPE

while working on interceptor with SpringMVC I'm getting NPE. I am using log4j.properties and here is the following code of interceptor
ThreadLocal<StopWatch> stopWatchLocal = new ThreadLocal<>();
Logger logger = Logger.getLogger(this.getClass());
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
Exception exception) throws Exception {
StopWatch stopWatch = stopWatchLocal.get();
stopWatch.stop();//Line 24
logger.info("Total time taken for processing: " + stopWatch.getTotalTimeMillis() + " ms");
stopWatchLocal.set(null);
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
ModelAndView modelAndView) throws Exception {
logger.info("Request processing ended on " + getCurrentTime());
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
StopWatch stopWatch = new StopWatch(object.toString());
stopWatch.start(object.toString());
stopWatchLocal.set(stopWatch);
logger.info("Accessing URL path: " + getURLPath(request));
logger.info("Request processing started on: " + getCurrentTime());
return true;
}
private String getCurrentTime() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy 'at' hh:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return formatter.format(calendar.getTime());
}
private String getURLPath(HttpServletRequest request) {
String currentPath = request.getRequestURI();
String queryString = request.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
return currentPath + queryString;
}
this is the log
j
ava.lang.NullPointerException
at com.webstore.interceptor.PerformanceMontiorInterceptor.afterCompletion(PerformanceMontiorInterceptor.java:24)
at org.springframework.web.servlet.HandlerExecutionChain.triggerAfterCompletion(HandlerExecutionChain.java:167)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1023)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
interceptor in dispatcherServlet
<mvc:interceptors>
<bean class="com.package.InterceptorClass"></bean>
</mvc:interceptors>
Am I doing something wrong ?
Please Help, is my configuration is broken because I'm not able to get the answer why I am getting NPE

GWT RequestBuilder file download

I implemented servlet, that creates XLS file. I am making a request from UI (GWT, RequestBuilder). I get the response, but is it possible to get ready file (with auto "save as" dialog box)?
Should I somehow set headers or something?
Here is my code:
Request implementation
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + "downloadLimitsFile");
try {
rb.setHeader("Content-type", "text/html");
Request response = rb.sendRequest("", new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("fail");
}
public void onResponseReceived(Request request, Response response) {
Window.alert("file downloaded " + response.getText());
}
});
} catch (RequestException e) {
Window.alert("Failed to send the request: " + e.getMessage());
}
My servlet implementation
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Content-Disposition", "attachment; filename=File.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
try {
workbook = fileExporter.prepareExcellFile();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
response.setStatus(HttpServletResponse.SC_OK);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
response.flushBuffer();
}
It was working fine (auto file download) when I was using eg. Anchor with servlet URL, but I have to use RequestBuilder now to make a request.
Can someone help?
I am afraid it is not possible, at least you can use a third party library.
Adding the header "Content-Disposition" won't work.

Upload file to my application on host by using servlet

I have a serlvet to upload file ... It work on my server, i upload to "http://localhost:8084/TestAmazon" and it work ... but we deploy my web application to host and upload file it not work ... please help me
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String relativeWebPath = "/image";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
if (ServletFileUpload.isMultipartContent(request)) {
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(absoluteFilePath + File.separator + name));
}
}
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception e) {
request.setAttribute("message", "File Upload Failed due to " + e);
}
} else {
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("result.jsp").forward(request, response);
}
i got an error:
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoSuchMethodError: org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload.parseRequest(Ljavax/servlet/http/HttpServletRequest;)Ljava/util/List;
sample.ProcessServlet.doPost(ProcessServlet.java:73)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

Trying to read tiff file using jai_imageio

I'm having some issue trying to create a subimage through a doGet method. I'm using jai_imageio, the same method "getInvoiceNumberTif()" works fine when using the main method.But when I try to call the method from servlet I get an exception.
Heres the GET:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Hello Servlet Get </h1>");
out.println("</body>");
out.println("</html>");
FileHandler fh = new FileHandler();
fh.getInvoiceNumberTif();
}
Here is the method:
public void getInvoiceNumberTif() throws IOException{
File file = new File("C:\\Users\\gideon\\Desktop\\tmp\\invoice.tif");
BufferedImage img = ImageIO.read(file);
BufferedImage subImage = img.getSubimage(1600, 355, 220, 50);
OutputStream out = new FileOutputStream(new File("C:\\Users\\gideon\\Desktop\\tmp\\img_invoice_nr.tif"));
ImageIO.write(subImage, "tif", out);
out.flush();
out.close();
}
the exception:
java.lang.NullPointerException
at se.visma.servlet.FileHandler.getInvoiceNumberTif(FileHandler.java:145)
at se.visma.servlet.InvoiceServlet.doGet(InvoiceServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)

Resources