Tag Archives: Servlet

[Solved] servlet jump to Blank Page Error: java.lang.ClassNotFoundException: com.mysql.jdbc.

The problem of page blank after servlet jump

Servlet code

report errors

ava.lang.ClassNotFoundException: com.mysql.jdbc.Driver exception

Reason: it has nothing to do with the above code,

The real reason is that the MySQL jar package was not imported into Tomcat. His grandmother found this problem for a long time and almost died

Now let’s show a wave of operation

1. Open Tomcat configuration,

2. Enter the favorite Guide Package link

Everyone’s lib directory is stored in different locations here. Anyway, you need to import the MySQL package into the Lib directory,

If you find that you don’t have this package, we’ll copy and paste it online or copy it in the Maven project

The main reason is that the MySQL package is not imported into tomcat, which leads to such an error

[Solved] Tomcat10 Error: jakarta.servlet.ServletException: Class com.kuang.servlet.HelloServlet is not a servlet

 Class com.kuang.servlet.HelloServlet is not a servlet

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

exception

jakarta.servlet.ServletException: Class com.kuang.servlet.HelloServlet is not a servlet
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:353)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:872)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1695)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)
Reason.

java.lang.ClassCastException: com.kuang.servlet.HelloServlet cannot be cast to jakarta.servlet.Servlet
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:353)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:872)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1695)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)

This is because the latest Tomcat 10 is used, and the biggest change in the latest Tomcat 10 is that Tomcat 10 m1 replaces JavaEE with Jakarta® EE

Jakarta® EE has a very, very important update over the previous JavaEE: the package name is no longer “javax.servlet”. Instead, it has been changed to “jakarta.servlet”

The first solution: downgrade Tomcat 10 to Tomcat 9

The second solution: continue to use Tomcat 10

Import the correct dependencies

<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>5.0.0</version>
    <scope>provided</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/jakarta.servlet.jsp/jakarta.servlet.jsp-api -->
<dependency>
    <groupId>jakarta.servlet.jsp</groupId>
    <artifactId>jakarta.servlet.jsp-api</artifactId>
    <version>3.0.0</version>
    <scope>provided</scope>
</dependency>

The requested resource [/servlet] in JavaWeb is not available [How to Solve]

Problem Description: after submitting the form, an error is reported, and the servlet is unavailable

Solution:

The development tool I use is idea2020. First, check whether comments are added:

2. Through consulting materials, it is said that servlets should be configured under web.xml. Here, I run JSP to get the web page source code, but I don’t know why. I haven’t configured web.xml in previous projects

3. Solution: add the following in the web app of web.xml:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

So far, the problem has been solved.

Maven does not have a servlet (an error is reported after the servlet is created)

 Maven cannot create a servlet

Solution

Scheme I

Specify the root directory in the IML of the project

 <sourceRoots>
        <root url="file://$MODULE_DIR$/src/main/java" />
  </sourceRoots>

Scheme II

Successfully solved

Error when Maven creates Servlet

Solution

Add in pom.xml (add dependencies under dependencies)

<!-- JSTL -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- Servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!--JSP -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>

Successfully resolved

 

Servlet jump mode sendredirect() and forward ()

A super detailed tutorial: springboot integrates mybatis plus>>>

In web application services, we often face the jump between different servlets. At present, we can achieve it in the following two ways:

1.RequestDispatcher.forward()

2.ServletResponse.sendReDirect()

The difference between the two is as follows

1. The redirect mode can be accessed across applications, and forward can only jump in the same application

2. Forward client accesses the server, and the server finds the corresponding URL to jump to and returns it to the client. The client’s address bar shows the original URL

The server finds the URL to jump and sends it to the client, then the client sends the request to the new URL again. Guest

The address bar of the client shows the URL of the second request

3. Data transmission: the data in the request can be accessed by forward, but not by redirect, because redirect is already a new request

Understanding of forward jump:

1. Get jump

The getrequestdispatcher method uses string parameter to describe the path of ServletContext scope. The path must be relative to the root of the ServletContext and begin with a ‘/’. This method uses the path to find the servlet, wraps it with the requestdispatcher object, and then returns the result object. If there is no servlet based on the specified path, provide a requestdispatcher to return the path value

The getnameddispatcher method uses a string parameter to represent the servlet name known to ServletContext. If the servlet is found, wrap it with the requestdispatcher object and return it. If there is no servlet associated with the specified name, the method must return null

In order to use the relative path of the current request (not the relative path of the ServletContext root) to obtain the requestdispatcher object, the ServletRequest interface provides the following methods:

getRequestDispatcher

The behavior of this method is similar to the method with the same name of ServletContext. The servlet container uses the information in the request object to convert the specified relative path into a full path. For example, for the context with the root of ‘/’, request/Garden/tools.html. The requestdispatcher obtained through servletrequest.getrequestdispatcher (“header. HTML”) is actually equivalent to calling servletcontext.getrequestdispatcher (“/ Garden/header. HTML”)

Java code

request.getRequestDispatcher(“/uu”).forward(request,response)

this.getServletContext().getRequestDispatcher(“/uu”).forward(request,response)

this.getServletContext().getNamedDispatche(“ServletName”).forward(request,response)

1.1 query string of requestdispatcher path

ServletContext and ServletRequest use the path parameter to create the method of the requestdispatcher object, allowing to add the query string after the path. For example, a developer can obtain a requestdispatcher by the following code:

String path = “/raisons.jsp?orderno=5”;

RequestDispatcher rd = context.getRequestDispatcher(path);

rd.include(request, response);

The parameters specified in the query string are used to create the requestdispatcher, which takes precedence over other parameters with the same name passed to the servlet. This parameter is associated with the requestdispatcher and is only valid in include or forward calls

2 using requestdispatcher

To use the requestdispatcher, the servlet can call the include or forward method of the requestdispatcher interface. The parameters of these methods can be the request and response parameters passed through the service method of the servlet interface, or they can be instances of the subclasses of the request and response wrapper classes introduced in specification 2.3. In the latter case, the wrapper instance must wrap the request and response objects that the container passes to the service method

The container vendor must ensure that the forwarding request to the target servlet and the original request are in the same VM and thread

3 include method

The include of the requestdispatcher interface can be called at any time. The target servlet of the include method can fully access the request object, but there are some restrictions on using the response object

It can only write information to the ServletOutputStream or writer of the response object, submit the response (output the content to the tail of the response buffer), or explicitly call the flushbuffer method of the servletresponse interface. It cannot set the header or call any method that affects the response header. Any attempt like that has to be ignored

3.1 request parameters included

In addition to the servlet obtained using the getnameddispatcher method, the servlet of include can access the path to which it was called. Set the following request properties:

javax.servlet.include.request_ uri

javax.servlet.include.context_ path

javax.servlet.include.servlet_ path

javax.servlet.include.path_ info

javax.servlet.include.query_ string

These properties of the include servlet are accessed through the getattribute method of the request object

If the included servlet is obtained through the getnameddispatcher method, these properties are not set

4. Forward method

The forward method of the requestdispatcher interface can only be called by the calling servlet when the output has not been submitted to the client. If the output data exists in the uncommitted response buffer, the content must be cleared before the service method call of the target servlet (otherwise, the output of out. Println() is in the buffer and invalid). If the response has been submitted, an IllegalStateException must be thrown. The path element of the request object exposed to the target servlet must be mapped to the path used to get the requestdispatcher

The only exception is if the requestdispatcher is obtained through the getnameddispatcher method, in which case the path element of the request object must map to the original request

Before the forward method of the requestdispatcher interface returns, the servlet container must send, submit, and close the response content

Java code

publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException,ServletException{

Stringpage=request.getParameter(“page”);// In forward, it is covered by page = 1 in the URL

response.setCharacterEncoding(“UTF-8”);

//clearcache.

response.setHeader(“Pragma”,”No-cache”);

response.setHeader(“Cache-Control”,”no-cache”);

response.setHeader(“Cache-Control”,”no-store”);

response.setDateHeader(“Expires”,0);

PrintWriterout=response.getWriter();

out.println(“< html>”);

out.println(“< head>& lt; title> china</ title>& lt;/ hea>”);

out.println(“< body>”);

out.print(“==”);

out.println(“< br/>”);// JSP page wrap

out.println(“</ body>”);

out.println(“</ html>”);

//if out. Flush or out. Close (). Indicates that the response has been submitted, an IllegalStateException is thrown. Requestdispatcher. Forward(): will not execute

//out.flush();

//out.close();

//there are three jump modes

//request.getRequestDispatcher(“/productInfo.do?page=1”).forward(request,response);

}

4.1 query string

The request forwarding mechanism is responsible for passing query strings when forwarding or including requests

5 error handling

If the target servlet of the requestdispatcher throws a runtime exception of type ServletException or IOException or a checked exception, it should be passed to the calling servlet. All other exceptions should be wrapped as ServletException exceptions, and the root of the exception is set to the original exception before passing

Understanding of relative path:

“/” in forward is relative to web application.
from http://localhost : forward in 8080/test/GW/page.jsp
& lt; jsp:forward page= “OtherPage.jsp”/> After the JSP page is parsed, it is converted to pagecontext. Forward (“otherpage. JSP”)
“/ otherpage. JSP” submit to http://localhost : 8080/test/otherpage. JSP
“otherpage. JSP” submitted to http://localhost :8080/Test/gw/OtherPage.jsp

< form action=”/ddd”> And response. Sendredirect (“/ DDD”); Relative to the server root path.
suppose that the forwarding code is contained in the registered servlet – URL is/GGG/TT; JSP is/GGG/TT. Jsp:
absolute path: response.sendredirect(“ http://www.brainysoftware.com “) send http://www.brainysoftware.com
Root path: response. Sendredirect (“/ OOo”) sent to http://localhost : 8080/OOo
relative path: response.sendredirect (“OOo”) to http://localhost :8080/Test/ggg/ooo,