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

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>

Related

Getting error when trying to upload image into the database using jsp servlet

This is form tag
<form action="Slider" method="post" enctype="multipart/form-data">
<input type="file" name="img" size="50">
<input type = "submit" value = "Change Poster" class="btn btn-primary waves-effect">
<input type="hidden" name="id" value="1">
</form>
This is servlet code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection con=null;
PreparedStatement st=null;
InputStream inputStream = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
ReadProperty rd=new ReadProperty();
con=rd.getConnection();
String id=request.getParameter("id");
System.out.println("id is"+id);
// obtains the upload file part in this multipart request
Part filePart = request.getPart("img");
System.out.println(filePart);
if (filePart != null) {
// prints out some information for debugging
System.out.println("image name"+filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
System.out.println("input stream"+inputStream);
}
st=con.prepareStatement("update slider set img=? where id='"+id+"'");
if(inputStream!=null)
{
st.setBlob(1, inputStream);
}
int result=st.executeUpdate();
if(result>0)
{
System.out.println("file uploaded successfully...");
}
}
catch(Exception e)
{
System.out.println(e);
}
// TODO Auto-generated method stub
}

doPost() is not being called from my jsp

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

i am trying to work on this piece of code but its not working and flashing error on the line mentioned

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
/* TODO output your page here. You may use following sample code. */
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Existing</title>");
out.println("</head>");
out.println("<body>");
HttpSession session=request.getSession(true);
String id,password;
id=request.getParameter("t1");
password=request.getParameter("t2");
session.setAttribute("t1",id);
int f=0;
Class.forName("org.sqlite.JDBC");
Connection c;
c=DriverManager.getConnection("jdbc:sqlite:c:/java/project");//ERROR COMES HERE java.lang.UnsatisfiedLinkError: org.sqlite.core.NativeDB._open(Ljava/lang/String;I)V
/* PreparedStatement ps;
ps=c.prepareStatement("select id,password from id where id='tirjss' password='020'");
String id2,pswrd;
ResultSet r;
r=ps.executeQuery();
if(r.next()==true)
{*/ response.sendRedirect("existing_user.html");
out.println("</body>");
out.println("</html>");
}catch(Exception e){}
}

Tomcat error 500 on page load

I am getting the following error on Tomcat.
The code is given below
message Servlet execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher
DBChart.doGet(DBChart.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.ClassNotFoundException: net.sf.ezmorph.Morpher
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
DBChart.doGet(DBChart.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Below is my Java file
//imported all the required packages here
class DBChart extends HttpServlet
{
Connection c = null;
Statement st = null;
ResultSet rs = null;
String query = null;
JSONObject obj = null;
JSONObject resobj = null;
PreparedStatement pst = null;
DatabaseMetaData dbmd = null;
String dbURL = "jdbc:sqlserver://localhost:1433; databaseName = EMPLOYEE";
String user = "username";
String password = "mypassword";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
List<JSONObject> Details = new LinkedList<JSONObject>();
PrintWriter out = response.getWriter();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
c = DriverManager.getConnection(dbURL, user, password);
query = " select DeptName, NumberOfEmployess from Departments";
pst = c.prepareStatement(query);
rs = pst.executeQuery();
while (rs.next())
{
String dept = rs.getString(1);
int empnumber = rs.getInt(2);
obj = new JSONObject();
obj.put("DepartmentName", dept);
obj.put("EmployeesinNumbers", empnumber);
Details.add(obj);
}
resobj.put("RelativeDetails", Details);
out.write(resobj.toString());
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
}
I made sure that I have mentioned the correct name in XMl file and using the url as follows:
http://localhost:8080/DBCHART/db
Your class needs to be public:
public class DBChart extends HttpServlet

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.

Resources