In Myeclipse I created a web project called web1,and added a servlet called servlet1,the web.xml is as followed:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
but when I typed the address:http://localhost:8080/web/test in the browser,it didn't work.I tried many times but have no answer.what's the problem?thanks a lot!
Here is the code:
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 servlet1 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6214906967399177511L;
/**
* Constructor of the object.
*/
public servlet1() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* #throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
Well as usual, you forgot to say super.init(config);
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
You're servlet never got initialized, because you overrode method, and forgot to call parents' init.
That's why, if you do not know the internals, do NOT override anything, except if you're sure what are you doing.
Related
This question already has answers here:
Should I override service() or doPost()?
(5 answers)
Overriding HttpServlet service method
(2 answers)
Closed 12 months ago.
I am fresher in java web application development .
I tried just running the servlet file(not even through html file just servlet file) .
Service method is executing and displaying the statement (I commented in order to execute the get method print statement)
but doGet and doPost is not been called.
Will anyone can help me
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Myservlet
*/
#WebServlet("/Myservlet")
public class Myservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Myservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
/*PrintWriter out = response.getWriter();
out.print("In service method");*/
//response.getWriter().println("Hello Server service method");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
response.getWriter().println("Hello Server, Get method");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
response.getWriter().println("Hello Server, Post method");
}
}
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
Exact error: The requested resource [/Register/] is not available. Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I am using tomcat and Eclipse.
Here is the code:
RegisterDao.java
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegisterDao {
private String dbUrl = "jdbc:mysql://localhost:3306/explorecalifornia";
private String dbUname = "dbuser";
private String dbPassword = "dbpassword";
private String dbDriver = "com.mysql.cj.jdbc.Driver";
public void loadDriver(String dbDriver)
{
try {
Class.forName(dbDriver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection()
{
Connection con = null;
try {
con = DriverManager.getConnection(dbUrl, dbUname, dbPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public String insert(Member member)
{
loadDriver(dbDriver);
Connection con = getConnection();
String result = "Data entered successfully";
String sql = "insert into member values(?,?,?,?)";
PreparedStatement ps;
try {
ps = con.prepareStatement(sql);
ps.setString(1, member.getUname());
ps.setString(2, member.getPassword());
ps.setString(3, member.getEmail());
ps.setString(4, member.getPhone());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "Data not entered";
}
return result;
}
}
Register.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
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 {
String uname = request.getParameter("uname");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
Member member = new Member(uname, password, email, phone);
RegisterDao rDao = new RegisterDao();
String result = rDao.insert(member);
response.getWriter().print(result);
}
}
web.xml
<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>Registration</display-name>
<welcome-file-list>
<welcome-file>memberRegistration.jsp</welcome-file>
</welcome-file-list>
</web-app>
and memberRegistration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="memberRegistration" method="post">
<table>
<tr><td>User Name: </td><td><input type="text" name="uname"></td></tr>
<tr><td>Password: </td><td><input type="password" name="password"></td></tr>
<tr><td>Email: </td><td><input type="text" name="email"></td></tr>
<tr><td>phone: </td><td><input type="text" name="phone"></td></tr>
<tr><td></td><td><input type="submit" value="register"></td></tr>
</table>
</form>
</body>
</html>
Need to place the servlet class in a java package. You should always put publicly reusable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself.
Am trying to access the url from JBOss server.. i have an error
javax.servlet.ServletException: Error instantiating servlet class com.tg.simReplacementApi.ReplaceSim
org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
java.lang.Thread.run(Thread.java:701)
root cause
java.lang.ClassNotFoundException: com.tg.simReplacementApi.ReplaceSim from [Module "deployment.ReplacementSim.war:main" from Service Module Loader]
org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
org.jboss.as.web.deployment.WebInjectionContainer.newInstance(WebInjectionContainer.java:72)
org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
java.lang.Thread.run(Thread.java:701)
and my web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Web Application</display-name>
<servlet>
<servlet-name>ReplaceSim</servlet-name>
<display-name>ReplaceSim</display-name>
<description></description>
<servlet-class>com.tg.simReplacementApi.ReplaceSim</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReplaceSim</servlet-name>
<url-pattern>/ReplaceSim</url-pattern>
</servlet-mapping>
</web-app>
and servlet is ReplaceSim.java
package com.tg.simReplacementApi;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ReplaceSim
*/
public class ReplaceSim extends HttpServlet {
private static final long serialVersionUID = 1L;
public ReplaceSim(){
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
Member member = new Member();
member.setPhoneNo(request.getParameter("phone"));
member.setSimSerial(request.getParameter("simSerial"));
WebServiceCaller call = new WebServiceCaller();
String resp = call.getReplacementSim(member);
System.out.println(resp);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
and successfully deployed into jboss7.1.1 server. When accessing the url this error is occurring. in localhost the application is working fine.
can anybody know why it causing error.. thanks in advance
Could anyone please help me?
Locally, on my mahcine I am running Tomcat 8.
I have used Eclipse to create a very very very simple Java Servlet by reading some online tutorials, Here's the code:
package com.theopentutorials.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloWorldServlet
*/
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloWorldServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I am successfully running this servlet on my machine and can access it fine from other machines in the same domain.
My web browser simply displays the string "Hello World" as expected.
So, now I'd like to push it to CloudFoundry.
So I use eclipse to export as a WAR file. Fine.
Next to CloudFoundry and I execute the following:
cf push Karry -p FirstServlet.war
All works fine. I see CloudFoundry installing java buildpacks etc. Finally it says App Started OK.
So now I browse to the url provided and I get:
What have I done wrong?
Thanks,
Mitch.
Did you try the /HelloWorldServlet endpoint? This is where I would look for this servlet, as defined in the code in
#WebServlet("/HelloWorldServlet")
I have springmvc and angularjs app up and running.
In Springmvc i have a bean named userSessionBean.
Now i am adding an interceptor to spring mvc and in its pre handel method i am trying to access userSessionBean.
My question is "Can i inject userSessionBean inside interceptor "
/**
*
*/
package com.loginLite.remote.authentication.interceptors;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.remote.authentication.model.UserSessionBean;
/**
* #author jamju02
*
*/
public class AuthenticationInteceptor implements HandlerInterceptor {
#Autowired
private UserSessionBean userSessionBean = null;
/**
* #return the userSessionBean
*/
public UserSessionBean getUserSessionBean() {
return userSessionBean;
}
/**
* #param userSessionBean the userSessionBean to set
*/
public void setUserSessionBean(UserSessionBean userSessionBean) {
userSessionBean = userSessionBean;
}
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre-handle");
return true;
}
#Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
Random rnd = new Random();
int tokenNumber = 100000 + rnd.nextInt(900000);
userSessionBean.setAuthTokenNumber(String.valueOf(tokenNumber));
response.addHeader("AUTH_TOKEN",userSessionBean.getAuthTokenNumber());
System.out.println("Post-handle");
}
#Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("After completion handle");
}
}
My dispatcher servlet
<mvc:interceptors>
<bean class="com.paychex.loginLite.remote.authentication.interceptors.AuthenticationInteceptor">
<property name="userSessionBean" ref="userSessionBean"></property>
</bean>
</mvc:interceptors>
<bean id="userSessionBean"
class="com.paychex.loginLite.remote.authentication.model.UserSessionBean"
scope="session">
<aop:scoped-proxy />
</bean>
I was finally able to solve the issue which i was troubling me.
The mistake was, i was implementing the interface "HandlerInterceptor" for my interceptor class, as soon as i removed the interface and extended class "HandlerInterceptorAdapter" dependency injection started working fine.