Tag Archives: servlet

[Solved] it only responds to error and does not enter success after AJAX is successfully processed

1. Problem description

Front end request code

$.ajax({
    url: 'getOne', 	
    data: {		
        name: 'zhangsan',
        pwd: '123'
    },
    type: 'get',		
    dataType: 'json',	
    success: function (res) { 
        alert("成功" + res)
    },
    error: function (xhr, errorMessage, e) { 
        alert("失败" + errorMessage);
    }
})

Backend servlet code

@WebServlet(name = "getOne", urlPatterns = "/getOne")
public class GetOne extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      	// Set encoding
       response.setContentType("application/json;charset=utf-8");
       // Processing business logic
        
         // Responding to the request, there may be IO exceptions in the way of using the stream, so the exception is caught
        PrintWriter out = response.getWriter();
        try {
            out.write("ajax request successful");
            out.close
        } catch (Exception exception) {
            out.write(exception);
        }
        out.close();
    }
}

Then it is found that after each processing, it will only respond to the abnormal error function and cannot enter success


2. Problem solving

The code above looks OK at first glance. I thought so at first. However, after some analysis, it is found that the format of the return value type at the back end is incorrect

What do you mean?

I set the JSON format in the back-end response

response.setContentType("application/json;charset=utf-8");

However, I output the ordinary string with the stream when responding, not the JSON format string

out.write("ajax request successful");

How to solve it?

Method 1: change the string format to JSON format
back end output: out.Write ("{'data':'ajax request succeeded '}")
front end: alert ("success" + res.data) method 2: change the type of request and processing to text
back end: response.setcontenttype ("application/JSON; charset = UTF-8")
front end: datatype: 'text'

[Solved] SpringMVC Run Error: SEVERE-Servlet.service() for servlet jsp threw exception

Today, I was learning spring MVC. Everything was difficult at the beginning. I didn’t expect it to be so difficult. The most basic Hello World was trapped for half an hour. The main problem was that Tomcat 10 version didn’t adapt to and Maven relied on. The error was: servlet. Service () for servlet JSP thread exception Java. Lang. NullPointerException , and the following is the specific solution

Read the original text

At the beginning of writing dependency, I found that groupid in the book was javax , and I had suffered such a loss before. In order to adapt it to my Tomcat 10, I changed it to Jakarta . As a result, when writing controller , the method can only recognize javax , and I can’t change the source code again, There is no way to replace dependence with this

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
</dependency>

Not surprisingly, when the Tomcat server is executed, it always reports an error saying that org.springframework.web.servlet.dispatcherservlet in the configuration file is not a servlet, so there is no way but to change the method

I thought Maven could play Tomcat plug-in and paste the dependent code immediately

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
        </plugin>
    </plugins>
</build>

Continue to run and report an error: servlet. Service () for servlet JSP thread exception Java. Lang. NullPointerException , go to stackoverflow and say that the range must be set to provided , and then run to display it. Later, switch back to normal tomcat operation with a try state, but the result is still not good

PS: finally switched back to Tomcat version 9.052

[Solved] Java.lang.IllegalStateException: getReader() has already been called for this request

For the project, it is necessary to obtain the data in the request body in the interceptor for data verification, because the @ requestbody annotation is used in the self-defined controller, resulting in an error in the project. The content of the error is: Java. Lang. IllegalStateException: getreader() has already been called for this request

After consulting the data, it is found that the getReader and getinputstream in the request are obtained by stream. After reading once, they can’t be used again. The solution is:

Step 1: define a filter in which a self-defined request is passed in. The self-defined request inherits the wrapper class httpservletrequestwrapper and rewrites the getinputstream and getReader methods
the filter code is as follows:

package com.chinastock.filter;

import com.chinastock.util.CustomHttpServletRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author zhoule
 * @description: handle request
 */
public class IMTAFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if(servletRequest instanceof HttpServletRequest) {
            requestWrapper = new CustomHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        }
        if(requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }
}

The custom request code is as follows:

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author zhoule
 * @description: Custom request wrapper for processing messages in the request body
 */
public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private byte[] body;

    public CustomHttpServletRequestWrapper(HttpServletRequest request) throws IOException
    {
        super(request);

        BufferedReader reader = request.getReader();
        try (StringWriter writer = new StringWriter()) {
            int read;
            char[] buf = new char[1024 * 8];
            while ((read = reader.read(buf)) != -1) {
                writer.write(buf, 0, read);
            }
            this.body = writer.getBuffer().toString().getBytes();
        }
    }

    public String getBody(){
        return new String(body, StandardCharsets.UTF_8);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException
    {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream()
        {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            public int read() throws IOException
            {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException
    {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}

The second step is to write the interceptor of the project. Some codes of the interceptor are as follows:

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CustomHttpServletRequestWrapper wrapper = (CustomHttpServletRequestWrapper) request;
        String body = wrapper.getBody();
        System.out.println(body);
        return true;
    }

maven_ Unable to create servlet file under Java Web project

Add the following code in pom.xml:

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
   <scope>provided</scope>
</dependency>
 
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
</dependency>

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

Error message: java.lang.illegalstateexception: cannot call sendredirect() after the response has been committed java.lang.illegalstateexception


Error message parsing: redirection cannot be called after response

Basic overview of Servlet

    determine whether it is necessary to use redirection. If necessary, use redirection. Otherwise, continue the work of servlet

    Cause of error:

      when using retargeting, our page has jumped, and the retargeted code will not be able to perform work. In order to make the jump page unaffected, we add a return after retargeting (most likely) the doget() and dopost() methods in servlet are incomplete. For example, write a doget() method less and delete the super. Doget() and super. Dopost() in the doget() and dopost() methods after rewriting; Here, we can use a request method to receive parameters. For example, the client uses the post or get request to send parameters, and we receive and respond consistently using the get method. At this time, we can add the code dopost (request, response) in the dopost () method check whether the program logic causes multiple jumps

      Note: when we write the redirection path. Redirection supports both the project resources and the resources in the server to use redirection, so the general redirection path is /project resource name/page or servlet to be redirected to or write the relative path directly

The solution to the problem that the method of interacting with database in the servlet class is invalid after the servlet submits 404, 500 refresh and becomes 404, and after connecting to the data pool

About 404

When checking the path and web inf carefully, take a look at the default path of Tomcat and change it to

About 505 in refresh to 404

There may be a problem with the jar package. It is recommended to check it carefully and try importing it again

Method failure
was found         The connection pool needs to use streams to accept configuration files. I wrote classloder.getsystemclassloder, which is wrong. It should be written as jdbcutils. Class. Getclassloder
instead           Classloader.getsystemclassloader is a system class loader (or application class loader), but in Tomcat’s class loader architecture, or ordinary web projects (JavaEE projects, not ordinary Java projects), we write our own business program code and resource files (configuration files are also counted, the code is the code in the SRC directory), When you deploy to the server, you will go to/WEB-INF/classes and/web-infb (you can go and have a look). The contents in these two directories are not loaded by the system class loader, but a webappclassloader (which can be printed)   System.out.println(JdbcUtils.class.getClassLoader());), So you can’t

use that  

Continuous Error 404 in servlet operation [How to Solve]

When writing the project, the servlet has been unable to work normally. After consulting the data for many times, we found the following possibilities.

First, automatic editing is not turned on

In the top project option, check build automatically from the drop-down list

Second: the version of the top header in web.xml is too low

The author uses @ webservlet (urlpatterns =/xxservlet) mode, which does not need to configure servlet file in web.xml, but only version 3.0 or above supports this mode. Therefore, in web.xml, there must be version = 3.1.

You can directly copy the following code to use.

<?xml version="1.0" encoding="UTF-8"?>
<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" version="3.1">
  <display-name>Project Name</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Third: Tomcat configuration problems

Remove Tomcat from the server and install Tomcat again according to the process.

1. Delete Tomcat

2. Select preference in the top window option. In the pop-up box, select server — runtime environment — and select the original Tomcat — remove

3. Then click Add to configure the Tomcat you downloaded.

I hope eclipse will work properly.

Solve the problem of forward parameter req and resp parameter error

1. Right click the stand-alone project and select Open Cloud settings, as shown in the figure:

2. Then click libraries on the left, and then click + on the right, as shown in the figure:

3. Then select the path Tomcat/lib/servlet-api.jar, as shown in the figure:

After completion, there will be no mistakes in testing context. Getrequestdispatcher (“/ GP”). Forward (req, resp)!!

Servlet error: no interface expected here

No interface expected here error was encountered when implementing the code. Idea was not compiled. No interface expected here means there is no interface.

resolvent

After a look around, we found that servlet is an interface, not a class. Httpservlet is an abstract class, so when we change it to servlet, we need to change extensions to implements.

Change extend to implements

 

 

 

Problems of accessing servlet display 404 on MyEclipse

Sometimes, when accessing a servlet in MyEclipse, a 404 page will appear. I won’t go into this if the web.xml is not configured properly or the URL is wrong, but I will talk about the situation where everything seems to be correct but I still can’t access it.
All you need to do is find the container where the servlet is running, in this case Tomcat, close it first, then locate the corresponding project in Tomcat, click ReDeploy, and then start Tomcat.

Possible causes and solutions of 404 problems in accessing servlet pages

Today I finished a function Want to direct input in the address bar servletA class and parameters to test the servlet code
an error 404. But I tested a new servletB class and it worked exactly the same way.
I was puzzled because both classes were servlets I created directly from Eclipse, and the web.xml was configured automatically. Even if the configuration is wrong it should be both wrong. Want to for a long time, suddenly think of you just created ServletA class, put the wrong to service pack, dragged her into the servlet found directly after the bag, but the web. The XML configuration path has been in the service package
as shown in figure
and the actual class names should be com. Student. Servlet. DeleteStudentServlet
for simple reason is:
I just begin to create the servlet misplacing to service the bag (actually should put the servlet bag), but to create the eclipse will help me get web. The XML class name is automatically configured (the name of the class is the route of the distribution of com. Student. Service. DeleteStudentServlet) and I treat the servlet to tow the servlet packages, web, XML is not modified, lead to the web. The path name of the class error in the XML. So when he visited the Servlet can’t find the correct path, to be an error 404.
so the Servlet error 404, must be sure to check the path name is correct, also want to check the web, XML configuration information is incorrect.
Summary: Make sure to go to web.xml to change the configuration if the package you created the Servlet contains changes.