Servlet is not printing anything with PrintWriter object - java

This is my JSP code, i am using get method to send data to go to servlet , servlet name is googleser.
<body>
<div class="formdiv">
<h1 align="center">Shikhar Google</h1>
<form action="googleser" method="get" align="center">
<input type="text" name="search1" class="search1"><br>
<input type="submit" class="submitbtn">
</form>
</div>
</body>
This is my servlet code . I tired printing every option related with printwriter method , but none of these worked.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class googleser extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3307/shikhar","root","");
Statement st = con.createStatement();
ResultSet rs= st.executeQuery("select * from student");
PrintWriter out=response.getWriter();
while(rs.next())
{
out.print(rs.getString(2));
}
String a= request.getParameter("search1");
out.print("<h1>Shikhar</h1>");
out.print("sddsdssdsd");
}
catch(Exception ex)
{
// System.out.print("yes yes yes");
}
}
}

please call the flush method after writing content into the response.
out.flush();

Related

404 Http Status by servlet

I have created a post yesterday regarding this, but someone decided to close it. I have tried solutions from the post, it didn't work. If answer from the post could solve my issues, I won't be asking the same question again. Tried Put servlet class in a package, Set servlet URL in url-pattern, Use domain-relative URL to reference servlet from HTML. The thing is my registration.jsp is almost the same as my login.jsp same for the servlets as well, I dont get why it doesnt work for registration when it works for the login servlet. I also have clean and restarted my server multiples times. Didnt install tomcat into the computer just import it thru zip files into eclipse.
HTTP Status 404 return by Servlet
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Login Servlet
package net.login.controller;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import net.login.dao.UserDAO;
import net.login.model.Users;
#WebServlet("/login")
public class UserLoginServlet extends HttpServlet{
public #interface WebServlet {
}
private static final long serialVersionUID = 1L;
public UserLoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDAO userDao = new UserDAO();
try {
Users user = userDao.checkLogin(username, password);
String destPage = "login.jsp";
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
destPage = "home.jsp";
} else {
String message = "Invalid username/password";
request.setAttribute("message", message);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
} catch (SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}
register.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.0/dist/jquery.validate.min.js"></script>
<link href=”bootstrap/css/bootstrap.min.css” rel=”stylesheet” type=”text/css” />
<script type=”text/javascript” src=”bootstrap/js/bootstrap.min.js”></script>
</head>
<body>
<div style='text-align=center' class="container">
<h1>New User Registration</h1>
<form action='register' method='POST' role='form'>
<div class='registerform'>
<label for='username'> Username: </label>
<input type="text" placeholder='Username' class='form-control' name='username'>
</div>
<div class='registerform'>
<label for='password'> Password: </label>
<input type="password" class='form-control' placeholder='Password' name='password'>
</div>
<br><br>
<button type="submit" class="btn btn-default"> Register </button>
</form>
</div>
</body>
</html>
UserRegisterServlet
package net.login.controller;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.login.dao.UserDAO;
import net.login.model.Users;
#WebServlet("/register")
public class UserRegisterServlet extends HttpServlet{
public #interface WebServlet{
}
private static final long serialVersionUID = 1L;
public UserRegisterServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// String pathInfo = request.getPathInfo();
// String[] pathParts = pathInfo.split("/");
// String part1 = pathParts[1];
// String part2 = pathParts[2];
//
// System.out.println(part1 + part2); //doesnt work for now since cant find /register
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDAO userDAO = new UserDAO();
try {
userDAO.createUsers(username, password);
String destPage = "register.jsp";
System.out.println("Success");
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
}catch(SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}

why i can't load data from database to jsp file? [duplicate]

This question already has an answer here:
Submitting form to Servlet which interacts with database results in blank page
(1 answer)
Closed 2 years ago.
Hello i am learning java servlet and i am coding a web ecommerce and i want to load data product form databse to jsp file i got some issues.My list product can't show on the jsp file.Pls help me
this is my class HomeController
package com.WebBanHang.controller;
import java.io.IOException;
import java.util.ArrayList;
import com.WebBanHang.model.Product;
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 com.WebBanHang.dao.Dao;
#WebServlet("/home")
public class HomeController extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//b1: get data from dao
Dao dao = new Dao();
ArrayList<Product> list = dao.getAllProduct();
//b2: set data to jsp
request.setAttribute("listP", list);
request.getRequestDispatcher("/view/Home.jsp").forward(request, response);
}
}
this is my class Dao to get product from database
package com.WebBanHang.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.WebBanHang.model.Product;
public class Dao {
public Dao() {
super();
// TODO Auto-generated constructor stub
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public ArrayList<Product> getAllProduct(){
ArrayList<Product> list = new ArrayList<>();
String query = "select * from tblProduct";
try {
conn = new DbConnection().getConnection();
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()) {
list.add(new Product(rs.getString(1),
rs.getString(2),
rs.getDouble(3),
rs.getString(4),
rs.getString(5)));
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
and this is my jsp file
<c:forEach items="${listP}" var="o">
<div class="row wow fadeIn">
<!--Fourth column-->
<div class="col-lg-3 col-md-6 mb-4">
<!--Card-->
<div class="card">
<!--Card image-->
<div class="view overlay">
<img src="${o.image}" class="card-img-top" alt="">
<a>
<div class="mask rgba-white-slight"></div>
</a>
</div>
<!--Card image-->
<!--Card content-->
<div class="card-body text-center">
<!--Category & Title-->
<a href="" class="grey-text">
<h5>${o.name}</h5>
</a>
<h5>
<strong>
${o.description}
</strong>
</h5>
<h4 class="font-weight-bold blue-text">
<strong>${o.price}</strong>
</h4>
</div>
<!--Card content-->
</div>
<!--Card-->
</div>
<!--Fourth column-->
</div>
<!--Grid row-->
</c:forEach>
When i run class HomeController my jsp file not show my list product
Help me pls.Thank you
when reading requests attributes you need to use the object requestScope.
Example:
<c:forEach items="${requestScope.listP}" var="o">

error in session build in a servlet

There is a problem in the session.
In create.html when i click on createdepartment the createdepartment.jsp page opens i copy its url1 after i submit the data , i again copy the url2 and then i logout after logging out when i paste url2 in the browser it gives message that Please login first and opens login.html but when i paste url1 in the browser it opens it but it shouldn't. Why is this happening?
I have given the code please could someone correct it?
LoginServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
boolean status=false;
try{
Connection con=ConnectionProvider.getCon();
String sql="select * from roles where name='" + name + "' and pass='" + password + "'";
PreparedStatement stmt =con.prepareStatement(sql);
String role="admin";
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
status=true;
role=rs.getString("role");
}
if(status){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
if(role!=null && role.equals("admin") ){
request.getRequestDispatcher("create.html").include(request, response);
}
else {
request.getRequestDispatcher("create1.html").include(request, response);
}
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
}catch( SQLException | ServletException | IOException e){}
}
}
}
create.html
Logout
Create Department
Create Users
<hr/>
department.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Create Department</h1>
<br>
<form action="DepartmentServlet">
<table border="1">
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
DepartmentServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DepartmentServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){}
if(status){
out.print("Values have been inserted,"+name);
request.getSession();}
else
{
out.print("failed");
}
request.getRequestDispatcher("department.jsp").include(request, response);
}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}
}
Logout.Servlet
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.print("You are successfully logged out!");
}
}
}
http://mytechsoft.jimdo.com/exclusive-projects
above link is for your problem, refer first 2 photos in it
LogoutServlet.java code might has problem.
You haven't mentioned its code.
Logout procedure includes 2 important things..
Remove all attributes attached to that session object
Make session object null (by making session.invalidate(); )
doing this makes session eligible for Garbage Collection, and reference of object (object stored in heap memory) is deleted (reference is stored in stack ).
In your case, I guess (because LogoutServlet.java is not there), most likely the reason for error is that
"You might be creating a new session Object and then you are copying the reference of old session object, now you would be deleting this new session by "session.invalidate();".
The above process deletes new reference but old one is still there because it's copy available in new object is deleted not the original one.
For More Specific and correct answer, please attach your LogoutServlet.java source code too.
Your logout servlet should have request.getSession(false)..This will not return new session if one already exists..Also clear your browser cache before running it.
HttpSession session=request.getSession(false);
session.invalidate();

How to receive a file type parameter from html/jsp into a servlet

I want to take image as input into my web page. I have written following code in my jsp for this :-
<form action="Upload" method="get" enctype="multipart/form-data">
Image<input type="file" name="image" accept="image/jpg" id="image">
<input type="submit" value="submit">
</form>
but I do not know how to receive the "image" parameter in a servlet that is whether it should be a input stream or file, I have no idea. Please tell me the correct code for it.
Use Apache Commons File.
The form method must be method="POST".
Then in your web.xml you need to map the request to your servlet:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.stackoverflow.MyServletClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/Upload</url-pattern>
</servlet-mapping>
Then you write a class that extends HttpServlet and implement to doPost() method.
well, just go here: http://www.codejava.net/java-ee/servlet/apache-commons-fileupload-example-with-servlet-and-jsp
After painstaking efforts and google search I found a solution to my problem. A page from Stackoverflow helped very much. First I changed the get method of my form to post like this
<form action="Upload" method="post" enctype="multipart/form-data">
Image<input type="file" name="image" id="image" accept="image/jpg">
<input type="submit" value="submit">
</form>
Then I wrote the following servlet code. We accept the <input type="file">data as Part data in servlet. Then we convert it to input stream. The input stream then can be saved in database. Here is my Servlet:-
package controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import model.ConnectionManager;
#MultipartConfig(location="/tmp", fileSizeThreshold=1048576, maxFileSize=20848820, maxRequestSize=418018841)
public class Upload extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part filePart=request.getPart("image");`// Retrieves <input type="file" name="image">`
String filePath = filePart.getSubmittedFileName();//Retrieves complete file name with path and directories
Path p = Paths.get(filePath); //creates a Path object
String fileName = p.getFileName().toString();//Retrieves file name from Path object
InputStream fileContent = filePart.getInputStream();//converts Part data to input stream
Connection conn=ConnectionManager.getConnection();
int len=(int) filePart.getSize();
String query = ("insert into IMAGETABLE(ID,NAME,LENGTH,IMAGE) VALUES(?,?,?,?)");
try {
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1, 5);
pstmt.setString(2, fileName);
pstmt.setInt(3, len);
pstmt.setBinaryStream(4, fileContent, len);
success=pstmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("Error : "+ex.getMessage());
}finally{
try{
if(fileContent!=null)fileContent.close();
if(conn!=null)conn.close();
}catch(IOException | SQLException ex){
System.out.println("Error : "+ex.getMessage());
}
}
}
}
After execution, it does the job successfully. We accept the image from user and save it in database. Hope this solution will help all :)

Tomcat error HTTP Status 405 - HTTP method GET is not supported by this URL

This is my jsp page
<html>
<head>
<link rel = "stylesheet" href="main.css"/>
<title>Login Page</title> </head>
<body>
<div class ="RegWrap">
<div class ="Set">
<form name="actionForm" action="Connecter" method ="Get">
<table>
<tr><td>Enter your Username: </td>
<td><input type="text" name="userName"/></td></tr>
<tr><td>Enter your Password: </td>
<td><input type="password" name="password"/></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"> </td></tr>
</table>
</form>
</div>
</div>
</body>
</html>
This is my Connecter class :
import java.io.IOException;
import java.io.PrintWriter;
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 Connecter extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("password");
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("welcom");
rd.forward(request,response);`
}
else {
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("Sign up.jsp");
rd.include(request,response);
}
out.close();
}`
This is my Welcome page
import java.io.IOException;`
import java.io.PrintWriter;`
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;`
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class welcom extends HttpServlet {
public class WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}
}
}
This is my Dao page
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class LoginDao {
public static boolean validate(String userName,String password){
boolean status=false;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306 /autolube","root","mehar");
PreparedStatement ps=con.prepareStatement
("select * from person where userName=?and password=?");
ps.setString(1,userName);
ps.setString(2,password);`ResultSet rs=ps.executeQuery();
status=rs.next();`}catch(Exception e){System.out.println(e);
}
return status;
}
}
In your servlet add the below line. As I commented I think its a problem with web.xml. If you are using servlet 3.0 you can use the below ammotation or map in web.xml.
#WebServlet("/Connecter")
public class Connecter extends HttpServlet
if url-pattern is /Connector then add /Connector in your form tag of index.html.

Categories

Resources