I am dispatching a request to html resource in Webcontent folder in servlet. But its not dispatching it. Even its not giving any exception. AboutUs is an html page placed in WebContent folder of project. The IDE i am using is eclipse. I am very new to web development. any help will be appreciated.
Thanks in advance.
Servlet Code:
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name="";
String pass="";
name=request.getParameter("param1");
pass=request.getParameter("param2");
System.out.println("Name :" +name+"PAss :"+pass);
if (name!=null && pass!=null){
List<User> please = DataAccessUtil.getByEmail(name, pass);
if (please!=null)
{
int count = please.size();
System.out.println("Record Found : " + count);
if(!(count==0))
{
Iterator<User> iterator = please.iterator();
while(iterator.hasNext())
{
User object = (User) iterator.next();
String email = object.getEmail();
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);
session.setAttribute("email", email);
}
RequestDispatcher r= request.getRequestDispatcher("/AboutUs.html");
r.forward(request, response);
log("please");
}
else{
RequestDispatcher rd= request.getRequestDispatcher("/DR.html");
rd.forward(request, response);
log("please2");
}
}
}
else{
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Related
#WebServlet("/")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDAO userDAO;
public void init() {
userDAO = new UserDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getServletPath();
try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertUser(request, response);
break;
case "/delete":
deleteUser(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateUser(request, response);
break;
default:
listUser(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
private void listUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
List<User> listUser = userDAO.selectAllUsers();
request.setAttribute("listUser", listUser);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-list.jsp");
dispatcher.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
dispatcher.forward(request, response);
}
private void showEditForm(HttpServletRequest request, HttpServletResponse response)
throws SQLException, ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User existingUser = userDAO.selectUser(id);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
request.setAttribute("user", existingUser);
dispatcher.forward(request, response);
}
private void insertUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");
User newUser = new User(name, email, country);
userDAO.insertUser(newUser);
response.sendRedirect("list");
}
private void updateUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");
User book = new User(id, name, email, country);
userDAO.updateUser(book);
response.sendRedirect("list");
}
private void deleteUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDAO.deleteUser(id);
response.sendRedirect("list");
}
}
This is my servlet and I believe I am having a problem with my goPost & my doGet.
Currently, my index page is the user-list.JSP, and when I click on any of the buttons on the page to turn it into "/new" etc.
I am not able to switch to the "user-form.JSP".
I have been staring at this thing for a while and am unsure what to move on from here. I will continue to look into this problem, hopefully, I can find something wrong with the Request Dispatcher, but I am not sure.
I am getting:
HTML status report 404 - Not Found
The image contains two methods and i want to pass an id from Country table to Province table
public class DataGeneraterServlet extends HttpServlet {
#EJB
DataGenerator gen;
EntityManager em;
private static final Logger log = Logger.getLogger(MainUtil.class.getSimpleName());
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Running Data Generator Servlet");
try
{
Country c = new Country();
Province p = new Province();
gen.addCountry();
gen.addProvince(c);
gen.addCity(p);
}
catch(Exception e)
{
log.log(Level.OFF,"Couldnt Add to database",e);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Country c = new Country(); //created a new country object but not have an id
Province p = new Province();
gen.addCountry(); //if this method returns a country object it will have an id.
gen.addProvince(c);
gen.addCity(p);
So
Country c = gen.addCountry();
Province p = gen.addProvince(c);
gen.addCity(p);
will give your expected result.
PS: You have to also refactor your EJB methods to return persisted values.
I have implemented drag & drop file uploading in jsp and servlet, but I have a problem. Here is a part of my upload.jsp code:
function dropUpload(event) {
var files = event.dataTransfer.files;
upload(files);
}
function upload(files) {
var formData = new FormData();
for (var i in files) {
formData.append('file[]', files[i]);
}
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.open("POST", "UploadServlet");
xhr.send(formData);
}
I use the getParts() method in my UploadServlet.java code to get the files that the user uploads, like below:
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("login.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String savePath = "D:\\TEST";
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
response.getWriter().println(request.getParts().size());
for (Part part : request.getParts()) {
if(part.getContentType() == null) {
continue;
}
response.getWriter().println("Part name: " + part.getName());
response.getWriter().println("Size: " + part.getSize());
response.getWriter().println("Content Type: " + part.getContentType());
String fileName = extractFileName(part, response);
response.getWriter().println(fileName);
part.write(savePath + File.separator + fileName);
response.getWriter().println("already upload file:" + fileName);
response.getWriter().println("=============================================");
}
}
private String extractFileName(Part part,HttpServletResponse response) throws IOException {
String contentDisp = part.getHeader("content-disposition");
//response.getWriter().println(contentDisp);
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
But I can't understand that if I upload 2 files with upload.jsp,
the value of getParts().size() is 4; it means that I always have 2 more files than exactly what I upload, and the 2 external files name and contentType will be null, and it will cause an error in part.write().
My solution is use the if statement
if(part.getContentType() == null) {
continue; }
to ignore the null file.
Can somebody tell me why this happens?
public class CompanyServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static org.apache.log4j.Logger log = Logger.getLogger(Company.class);
/**
* This string holds the filename of the file.
*/
String fileName = null;
Details detailsById = null;
Page page = null;
String date = null;
HttpServletRequest request = null;
/**
* This holds the bytes of the file to be written .
*/
Workbook wb = null;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
The class CompanyServlet is a singleton, so the member field request is shared between users. The result is that one user could see another user's data. How to avoid this problem.
Don't keep state in servlets, keep them in the session if you need to store them somewhere.
I have my servlet:
public class Authentification extends HttpServlet {
public int id1;
private static final long serialVersionUID = 1L;
public HttpSession session;
Authentification_link auth=new Authentification_link();
public Integer IdUser;
public Authentification() {
super();
}
public void init() {
Codb co= new Codb();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int IdUser = Integer.valueOf(request.getParameter("id"));
session.setAttribute("ide", IdUser);
try {
if(auth.authen(IdUser)){
session.setAttribute("id", IdUser);
request.getRequestDispatcher("acceuil.jsp").forward(request, response);
System.out.println("found");}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("not found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doInteret (HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
IdUser = (Integer) session.getAttribute("IdUser");
Interets inte= new Interets (IdUser);
}
}
The user login to through an id, the authentification works fine, but now I want to get the same user's id so I can include it in this java classe when the user click on a link. For that I added the method doInteret in the servlet and the class Interet.java is like this:
public class Interets {
static Statement St ;
public ResultSet rs;
public Interets(Integer IdUser) throws SQLException, ServletException, IOException{
String res=" ";
try{
ResultSet result = St.executeQuery("SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar="+IdUser+"");
ResultSetMetaData resultMeta = (ResultSetMetaData) result.getMetaData();
while(result.next()){
String Newligne=System.getProperty("line.separator");
for(int i = 1; i <= resultMeta.getColumnCount(); i++){
res=res+Newligne+result.getObject(i).toString();
System.out.println(res);
}
}
}
catch (Exception e) {
System.out.println("Error in Select ");
}
}
}
but I am getting this error:
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoSuchMethodError: pack1.Interets.AfficheInteret()Ljava/lang/String;
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:412)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
try changing your query and print it may be your query is not working
SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar='"+IdUser+"'");