Java redirect error

Redirect error stream java In java the three main Streams stdin (standard input) , stdout (standard output) and stderr (standard output error) are handled by default by System.in, Sytem.out and System.err respectively. Sometimes we may need to change the output according to our needs, this can be done in many ways such us using […]

Содержание

  1. Redirect error stream java
  2. Redirecting streams to file from console in Unix
  3. Redirecting Output Streams to Files
  4. Redirecting Output Error Stream to the Standard Out Stream.
  5. Redirecting Output Streams to Files and Printing the result in the console.
  6. Redirecting Output Streams in Log4J
  7. How To Write Console Output To Text File In Java
  8. 1. Redirect Java System Output Stream Methods.
  9. 2. Redirect Java Out Error Stream Examples.
  10. 3. Write Console Output To Text File In Java Examples.
  11. 4. Why My Java Code Can Not Write Console Output To A Local Log Text File.
  12. 4.1 Question.
  13. 4.2 Answer1.
  14. 1 thought on “How To Write Console Output To Text File In Java”
  15. Leave a Comment Cancel Reply
  16. Redirect error stream java
  17. Redirecting streams to file from console in Unix
  18. Redirecting Output Streams to Files
  19. Redirecting Output Error Stream to the Standard Out Stream.
  20. Redirecting Output Streams to Files and Printing the result in the console.
  21. Redirecting Output Streams in Log4J
  22. Java.lang.ProcessBuilder.redirectErrorStream() Method
  23. Complete Java Programming Fundamentals With Sample Projects
  24. Get your Java dream job! Beginners interview preparation
  25. Core Java bootcamp program with Hands on practice
  26. Description
  27. Declaration
  28. Parameters
  29. Return Value
  30. Exception
  31. Example
  32. Redirect error stream java

Redirect error stream java

In java the three main Streams stdin (standard input) , stdout (standard output) and stderr (standard output error) are handled by default by System.in, Sytem.out and System.err respectively. Sometimes we may need to change the output according to our needs, this can be done in many ways such us using the OS to tell what stream we need to use or using java to set what streams we want to be used.

In these examples is shown how to deal with these streams in different sceenarios.

Redirecting streams to file from console in Unix

java MyExample > output.log 2>error.log

Redirecting Output Streams to Files

This example redirects both output streams to 2 different files. It produces an ArithmeticException dividing by 0 and the error trace will be stored in the stderr.log. The results won’t be shown in the console.

Redirecting Output Error Stream to the Standard Out Stream.

Redirecting Output Streams to Files and Printing the result in the console.

In this example a «proxy» class I used, so that every time the print or println methods are called its output will be printed by the console and also stored the specified files.

* This example appends traces to the existing file change new FileOutputStream(FilePath,true) for new FileOutputStream(FilePath) to create a new file each time.

Redirecting Output Streams in Log4J

This example prints all the traces ment for the standard outputs to the LOG4J files, so you can make sure that all traces are there.

Источник

How To Write Console Output To Text File In Java

The java.lang.System‘s out and err objects are used to write text data to the standard output stream and standard error stream. The default output stream is the command-line console. But the java.lang.System class also provides a method for you to redirect the standard output stream to other destinations such as file stream. With this, you can log text data to a log file in your java program.

1. Redirect Java System Output Stream Methods.

  1. The java.lang.System class provides the below methods to set standard output stream to custom stream.
  2. setOut(PrintStream ps): Set standard data output to a specified print stream such as a file stream.
  3. setErr(PrintStream ps): Set standard error output to a specified print stream such as a file stream.
  4. setIn(InputStream is): Set standard input stream to a custom input stream.

2. Redirect Java Out Error Stream Examples.

  1. Below are the steps of redirecting the output stream to the file stream.
  2. Create a file output print stream.
  3. Call System.setOut method to set above PrintStream as the new standard output stream.
  4. Call System.out.println to write text data to the file.

3. Write Console Output To Text File In Java Examples.

  1. Below is the full example source code.
  2. After executing the above code, you can see two files out.txt and err.txt are generated under the current java class execution folder.
  3. Below is another method to write user input in the command line console to a text file in java.

4. Why My Java Code Can Not Write Console Output To A Local Log Text File.

4.1 Question.

  1. I am new to java programming. And my java program generates a lot of log output text on the console screen using the method system.out.println() (2022/05/24).
  2. I want to save the above log text output to a log file instead of printing them on the console.
  3. Below is an example java source code, but it does not work as expected when I run it. Can anyone give me some suggestions? Thanks a lot.

4.2 Answer1.

  1. If you want to print the system standard output from the default console screen to a special file, you should change your java source code as below.
  2. The code System.setOut(pw) is very important, it will direct all your system.out.printiln() method printed text to the PrintWriter object. Then all those texts will be written to the PrintWriter wrapped text file.
  3. The above code will print text to the custom text file, but it will truncate the file when you print new text to the file.
  4. If you want to append the new text to the existing text file, you can set the append parameter to true to achieve this like the below source code.

1 thought on “How To Write Console Output To Text File In Java”

I have an existing java class which contains a lot of System.out.println() method to print text to the standard output console. But when the java class execute, I need the log text write to a file instead of writing to java standard output console. And I searched out this article. But it is difficult to update my old java class because there are too many System.out.println() lines, so I google out below method can also achieve this. In a terminal and run the command java Yout-Class-Name >> out.txt. Then it will print all the output text generated by the System.out.println() method to the text file.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Redirect error stream java

In java the three main Streams stdin (standard input) , stdout (standard output) and stderr (standard output error) are handled by default by System.in, Sytem.out and System.err respectively. Sometimes we may need to change the output according to our needs, this can be done in many ways such us using the OS to tell what stream we need to use or using java to set what streams we want to be used.

In these examples is shown how to deal with these streams in different sceenarios.

Redirecting streams to file from console in Unix

java MyExample > output.log 2>error.log

Redirecting Output Streams to Files

This example redirects both output streams to 2 different files. It produces an ArithmeticException dividing by 0 and the error trace will be stored in the stderr.log. The results won’t be shown in the console.

Redirecting Output Error Stream to the Standard Out Stream.

Redirecting Output Streams to Files and Printing the result in the console.

In this example a «proxy» class I used, so that every time the print or println methods are called its output will be printed by the console and also stored the specified files.

* This example appends traces to the existing file change new FileOutputStream(FilePath,true) for new FileOutputStream(FilePath) to create a new file each time.

Redirecting Output Streams in Log4J

This example prints all the traces ment for the standard outputs to the LOG4J files, so you can make sure that all traces are there.

Источник

Java.lang.ProcessBuilder.redirectErrorStream() Method

Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

Core Java bootcamp program with Hands on practice

99 Lectures 17 hours

Description

The java.lang.ProcessBuilder.redirectErrorStream() method tells whether this process builder merges standard error and standard output. If this property is true, then any error output generated by subprocesses subsequently started by this object’s start() method will be merged with the standard output, so that both can be read using the Process.getInputStream() method. This makes it easier to correlate error messages with the corresponding output. The initial value is false.

Declaration

Following is the declaration for java.lang.ProcessBuilder.redirectErrorStream() method

Parameters

Return Value

This method returns this process builder’s redirectErrorStream property

Exception

Example

The following example shows the usage of lang.ProcessBuilder.redirectErrorStream() method.

Let us compile and run the above program, this will produce the following result −

Источник

Redirect error stream java

Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.

The startPipeline method can be invoked to create a pipeline of new processes that send the output of each process directly to the next process. Each process has the attributes of its respective ProcessBuilder.

Each process builder manages these process attributes:

  • a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. For example, it is common for each conceptual argument to be an element in this list, but there are operating systems where programs are expected to tokenize command line strings themselves — on such a system a Java implementation might require commands to contain exactly two elements.
  • an environment, which is a system-dependent mapping from variables to values. The initial value is a copy of the environment of the current process (see System.getenv() ).
  • a working directory. The default value is the current working directory of the current process, usually the directory named by the system property user.dir .
  • a source of standard input. By default, the subprocess reads input from a pipe. Java code can access this pipe via the output stream returned by Process.getOutputStream() . However, standard input may be redirected to another source using redirectInput . In this case, Process.getOutputStream() will return a null output stream, for which:
    • the write methods always throw IOException
    • the close method does nothing
  • a destination for standard output and standard error. By default, the subprocess writes standard output and standard error to pipes. Java code can access these pipes via the input streams returned by Process.getOutputStream() and Process.getErrorStream() . However, standard output and standard error may be redirected to other destinations using redirectOutput and redirectError . In this case, Process.getInputStream() and/or Process.getErrorStream() will return a null input stream, for which:
    • the read methods always return -1
    • the available method always returns 0
    • the close method does nothing
  • a redirectErrorStream property. Initially, this property is false , meaning that the standard output and error output of a subprocess are sent to two separate streams, which can be accessed using the Process.getInputStream() and Process.getErrorStream() methods.

    If the value is set to true , then:

    • standard error is merged with the standard output and always sent to the same destination (this makes it easier to correlate error messages with the corresponding output)
    • the common destination of standard error and standard output can be redirected using redirectOutput
    • any redirection set by the redirectError method is ignored when creating a subprocess
    • the stream returned from Process.getErrorStream() will always be a null input stream

    Modifying a process builder’s attributes will affect processes subsequently started by that object’s start() method, but will never affect previously started processes or the Java process itself.

    Most error checking is performed by the start() method. It is possible to modify the state of an object so that start() will fail. For example, setting the command attribute to an empty list will not throw an exception unless start() is invoked.

    Note that this class is not synchronized. If multiple threads access a ProcessBuilder instance concurrently, and at least one of the threads modifies one of the attributes structurally, it must be synchronized externally.

    Starting a new process which uses the default working directory and environment is easy:

    Here is an example that starts a process with a modified working directory and environment, and redirects standard output and error to be appended to a log file:

    To start a process with an explicit set of environment variables, first call Map.clear() before adding environment variables.

    Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

    Источник

The most common and recommended scenario (for the server side validation in Java serlvets/JSP world) is setting some error message as a request attribute (in the request scope) and then outputting this message in a JSP using Expression Language (see the example below). When the error message is not set — nothing will be shown.

But when storing an error message in a request, you should forward a request to the initial page. Setting a request attribute is not suitable when redirecting, because if you use a redirect it will be a totally NEW request and request attributes are reset between requests.

If you want to redirect a request to the referring page (the one from which you submitted data) then you can store an error message in a session (in the session scope), i.e. set a session attribute. But in this case, you also need to remove that attribute from the session when the submitted request is correct, because otherwise an error message will be available as long as the session lives.

As for the context attribute it is meant to be available to the whole web application (application scope) and for ALL users, plus it lives as long as the web application lives, which is hardly useful in your case. If you set an error message as an application attribute it will be visible to ALL users, not only to the one that submitted the wrong data.


OK, here is a primitive example.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
    version="3.0">

    <display-name>Test application</display-name>

    <servlet>
        <servlet-name>Order Servlet</servlet-name>
        <servlet-class>com.example.TestOrderServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Order Servlet</servlet-name>
        <url-pattern>/MakeOrder.do</url-pattern>
    </servlet-mapping>

</web-app>

order.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <h1>Test page</h1>
    <form action="MakeOrder.do" method="post">
        <div style="color: #FF0000;">${errorMessage}</div>
        <p>Enter amount: <input type="text" name="itemAmount" /></p>
        <input type="submit" value="Submit Data" />
    </form>
</body>
</html>

Option №1: setting an error message as a request attribute

package com.example;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.io.IOException;

public class TestOrderServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
        int amount = 0;
        try {
            amount = Integer.parseInt(request.getParameter("itemAmount"));
        } catch (NumberFormatException e) {
            // do something or whatever
        }

        if ((amount > 0) && (amount < 100)) {   // an amount is OK
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {                                // invalid amount
            // Set some error message as a request attribute.
            if (amount <= 0) {
                request.setAttribute("errorMessage", "Please submit an amount of at least 1");
            } 
            if (amount > 100){
                request.setAttribute("errorMessage", "Amount of items ordered is too big. No more than 100 is currently available.");
            }
            // get back to order.jsp page using forward
            request.getRequestDispatcher("/order.jsp").forward(request, response);
        }
    }
}

Option №2: setting an error message as a session attribute

TestOrderServlet.java

package com.example;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.io.IOException;

public class TestOrderServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
        int amount = 0;
        try {
            amount = Integer.parseInt(request.getParameter("itemAmount"));
        } catch (NumberFormatException e) {
            // do something or whatever
        }

        if ((amount > 0) && (amount < 100)) {   // an amount is OK
            // If the session does not have an object bound with the specified name, the removeAttribute() method does nothing.
            request.getSession().removeAttribute("errorMessage");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {                                // invalid amount
            // Set some error message as a Session attribute.
            if (amount <= 0) {
                request.getSession().setAttribute("errorMessage", "Please submit an amount of at least 1");
            } 
            if (amount > 100){
                request.getSession().setAttribute("errorMessage", "Amount of items ordered is too big. No more than 100 is currently available.");
            }
            // get back to the referer page using redirect
            response.sendRedirect(request.getHeader("Referer"));
        }
    }
}

Related reading:

  • How to choose the right bean
    scope?
  • java.lang.IllegalStateException: Cannot forward after response has
    been committed

Содержание

  • 1 Redirecting Standard Output, and Error
  • 2 Redirect standard error
  • 3 Redirect standard output
  • 4 Redirect standard output to a file
  • 5 Replace standard output and error with a print stream, output to both the console and to a file.
  • 6 Standard Err and Output Windows

Redirecting Standard Output, and Error

   <source lang="java">

import java.io.FileOutputStream;
import java.io.PrintStream;
public class Main {

 public static void main(String[] argv) throws Exception {
   System.setOut(new LogStream(System.out, new PrintStream(new FileOutputStream("out.log"))));
   System.setErr(new LogStream(System.err, new PrintStream(new FileOutputStream("err.log"))));
   
   System.out.println("output");
   System.err.println("error");
 }

}
class LogStream extends PrintStream {

 PrintStream out;
 public LogStream(PrintStream out1, PrintStream out2) {
   super(out1);
   this.out = out2;
 }
 public void write(byte buf[], int off, int len) {
   try {
     super.write(buf, off, len);
     out.write(buf, off, len);
   } catch (Exception e) {
   }
 }
 public void flush() {
   super.flush();
   out.flush();
 }

}

 </source>
   
  
 
  

Redirect standard error

   <source lang="java">

import java.io.FileOutputStream;
import java.io.PrintStream;
public class Main {

 public static void main(String[] args) throws Exception {
   System.setErr(new PrintStream(new FileOutputStream("system_err.txt")));
   String nullString = null;
   nullString = nullString.toUpperCase();
 }

}

 </source>
   
  
 
  

Redirect standard output

   <source lang="java">

import java.io.FileOutputStream;
import java.io.PrintStream;
public class Main {

 public static void main(String[] args) throws Exception {
   System.setOut(new PrintStream(new FileOutputStream("system_out.txt")));
   System.out.println("sent to the file system_out.txt");
 }

}

 </source>
   
  
 
  

Redirect standard output to a file

   <source lang="java">

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Main {

 public static void main(String[] argv) throws Exception {
   System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.dat"))));
 }

}

 </source>
   
  
 
  

Replace standard output and error with a print stream, output to both the console and to a file.

   <source lang="java">

import java.io.FileOutputStream;
import java.io.PrintStream;
public class Main {

 public static void main(String[] argv) throws Exception {
   System.setOut(new LogStream(System.out, new PrintStream(new FileOutputStream("out.log"))));
   System.setErr(new LogStream(System.err, new PrintStream(new FileOutputStream("err.log"))));
   
   System.out.println("output");
   System.err.println("error");
 }

}
class LogStream extends PrintStream {

 PrintStream out;
 public LogStream(PrintStream out1, PrintStream out2) {
   super(out1);
   this.out = out2;
 }
 public void write(byte buf[], int off, int len) {
   try {
     super.write(buf, off, len);
     out.write(buf, off, len);
   } catch (Exception e) {
   }
 }
 public void flush() {
   super.flush();
   out.flush();
 }

}

 </source>
   
  
 
  

Standard Err and Output Windows

   <source lang="java">

import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
public class StdErrOutWindows {

 JTextArea outArea = new JTextArea(20, 50), errArea = new JTextArea(20, 50);;
 public StdErrOutWindows() {
   JScrollPane pain = new JScrollPane(outArea);
   JFrame outFrame = new JFrame("out");
   outFrame.getContentPane().add(pain);
   outFrame.setVisible(true);
   
   pain = new JScrollPane(errArea);
   JFrame errFrame = new JFrame("err");
   errFrame.getContentPane().add(pain);
   errFrame.setLocation(errFrame.getLocation().x + 20, errFrame.getLocation().y + 20);
   errFrame.setVisible(true);
   System.setOut(new PrintStream(new JTextAreaOutputStream(outArea)));
   System.setErr(new PrintStream(new JTextAreaOutputStream(errArea)));
 }
 public static void main(String[] args) {
   new StdErrOutWindows();
   System.out.println("test to out");
   try {
     throw new Exception("Test exception");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 public class JTextAreaOutputStream extends OutputStream {
   JTextArea ta;
   public JTextAreaOutputStream(JTextArea t) {
     super();
     ta = t;
   }
   public void write(int i) {
     ta.append(Character.toString((char)i));
   }
   public void write(char[] buf, int off, int len) {
     String s = new String(buf, off, len);
     ta.append(s);
   }
 }

}

 </source>
   
  
 
  1. June 15th, 2009, 02:29 AM


    #1

    leenabora is offline


    Junior Member


    Default Redirect error and output stream using java program

    I’m facing following problem:

    1. I have a Java program which calls other java program.

    2. I call the other java program by:

    —> I run the batch file.
    Process proc =Runtime.getRuntime().exec(batchFile);
    —> This batch file calls the java program.

    Now In my main application that is main java program I’m capturing error and output stream of DOS command
    line so that it will be displayed by my swing application.

    proc.getInputStream() and proc.getErrorStream().

    But I’m not able to capture the error stream

    If I don’t capture the streams and run command window it will display error as
    well as o/p on command window.

    I’m not getting what is going wrong over here.

    Thanks in advance.

    Lee


  2. Default Related threads:


  3. June 15th, 2009, 04:15 AM


    #2

    Default Re: Redirect error and output stream using java program

    try using redirectErrorStream(true); so that you can read it using getInputStream()

    Chris


  4. June 15th, 2009, 04:54 AM


    #3

    leenabora is offline


    Junior Member


    Default Re: Redirect error and output stream using java program

    Hi,

    Thanks for the reply.

    I cannot do this for following two reasons:
    1. I want to capture error streams and o/p streams differently as they are treated differently by my swing application.

    2. It is not that I’m not able to catch the error stream completely.
    The java class which I’m calling through the batch file has the main() method. If I throw some exception in that class and I catch it. It will be redirected to the Error stream.

    But If it is being thrown from some other class then it cannot be captured by error stream.

    Initially I thought it is due to the fact that may be log4j is redirecting it to some other place. But thats not true if I run this through command line I can view all error and o/p msg.

    Lee


  5. June 15th, 2009, 07:42 AM


    #4

    leenabora is offline


    Junior Member


    Default Re: Redirect error and output stream using java program

    I’m facing following problem:

    1. I have a Java program which calls other java program.

    2. I call the other java program by:

    —> I run the batch file.
    Process proc =Runtime.getRuntime().exec(batchFile);
    —> This batch file calls the java program.

    Now In my main application that is main java program I’m capturing error and output stream of DOS command
    line so that it will be displayed by my swing application.

    proc.getInputStream() and proc.getErrorStream().

    But I’m not able to capture the error stream

    If I don’t capture the streams and run command window it will display error as
    well as o/p on command window.

    I’m not getting what is going wrong over here.

    Idont want to use try redirectErrorStream(true); or following two reasons:
    1. I want to capture error streams and o/p streams differently as they are treated differently by my swing application.

    2. It is not that I’m not able to catch the error stream completely.
    The java class which I’m calling through the batch file has the main() method. If I throw some exception in that class and I catch it. It will be redirected to the Error stream.

    But If it is being thrown from some other class then it cannot be captured by error stream.

    Initially I thought it is due to the fact that may be log4j is redirecting it to some other place. But thats not true if I run this through command line I can view all error and o/p msg.

    Lee


  6. June 15th, 2009, 11:24 PM


    #5

    leenabora is offline


    Junior Member


    Default Re: Redirect error and output stream using java program

    Hi,

    This is solved. We need to read input and error stream in two different threads to avoid the blocking.


  7. June 16th, 2009, 04:12 AM


    #6

    Thumbs up Re: Redirect error and output stream using java program

    Quote Originally Posted by leenabora
    View Post

    Hi,

    This is solved. We need to read input and error stream in two different threads to avoid the blocking.

    I’m glad you resolved your problem leenabora.

    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.


During configure spring security with my project i find java.lang.IllegalArgumentException error and also fine its solution by me: my SpringSecurityWebConfig as bellow and when i run my project at initial level error was generating which mentioned in trance.

SpringSecurityWebConfig

package com.springdemo.configs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by JavaDeveloperZone on 18-03-2017.
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityWebConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("javadeveloperzone").password("javadeveloperzone").roles("USER");
        auth.inMemoryAuthentication().withUser("javadeveloperzone1").password("javadeveloperzone1").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("javadeveloperzone2").password("javadeveloperzone2").roles("CLIENT");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("login").defaultSuccessUrl("/admin/home")
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest().authenticated();
        /*http.csrf().disable();*/
        http.logout().logoutSuccessUrl("/logoutSuccess").permitAll();
    }
}

Trace:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: 'login?error' is not a valid redirect URL
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
  at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
  at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
  at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
  at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5014)
  at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5524)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
  at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
  at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
  at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
  at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1760)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.lang.reflect.Method.invoke(Unknown Source)
  at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
  at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(Unknown Source)
  at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(Unknown Source)
  at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:618)
  at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:565)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.lang.reflect.Method.invoke(Unknown Source)
  at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
  at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(Unknown Source)
  at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(Unknown Source)
  at javax.management.remote.rmi.RMIConnectionImpl.doOperation(Unknown Source)
  at javax.management.remote.rmi.RMIConnectionImpl.access$300(Unknown Source)
  at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(Unknown Source)
  at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(Unknown Source)
  at javax.management.remote.rmi.RMIConnectionImpl.invoke(Unknown Source)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.lang.reflect.Method.invoke(Unknown Source)
  at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
  at sun.rmi.transport.Transport$1.run(Unknown Source)
  at sun.rmi.transport.Transport$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.Transport.serviceCall(Unknown Source)
  at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
  at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: 'login?error' is not a valid redirect URL
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  ... 61 more
Caused by: java.lang.IllegalArgumentException: 'login?error' is not a valid redirect URL
  at org.springframework.util.Assert.isTrue(Assert.java:68)
  at org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.setDefaultFailureUrl(SimpleUrlAuthenticationFailureHandler.java:125)
  at org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.<init>(SimpleUrlAuthenticationFailureHandler.java:60)
  at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.failureUrl(AbstractAuthenticationFilterConfigurer.java:206)
  at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.updateAuthenticationDefaults(AbstractAuthenticationFilterConfigurer.java:368)
  at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.loginPage(AbstractAuthenticationFilterConfigurer.java:308)
  at org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer.loginPage(FormLoginConfigurer.java:183)
  at com.springdemo.configs.SpringSecurityWebConfig.configure(SpringSecurityWebConfig.java:29)
  at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:224)
  at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:315)
  at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:86)
  at com.springdemo.configs.SpringSecurityWebConfig$$EnhancerBySpringCGLIB$$aa5da7d1.init(<generated>)
  at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
  at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
  at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
  at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
  at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$ff0c06c4.CGLIB$springSecurityFilterChain$0(<generated>)
  at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$ff0c06c4$$FastClassBySpringCGLIB$$9d8da255.invoke(<generated>)
  at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
  at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
  at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$ff0c06c4.springSecurityFilterChain(<generated>)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.lang.reflect.Method.invoke(Unknown Source)
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
  ... 62 more

 Solution:

Replace

loginPage("login") 
With
loginPage("/login")

Complete code as under:

package com.springdemo.configs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by JavaDeveloperZone on 18-03-2017.
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityWebConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("javadeveloperzone").password("javadeveloperzone").roles("USER");
        auth.inMemoryAuthentication().withUser("javadeveloperzone1").password("javadeveloperzone1").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("javadeveloperzone2").password("javadeveloperzone2").roles("CLIENT");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("/login").defaultSuccessUrl("/admin/home")
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest().authenticated();
        /*http.csrf().disable();*/
        http.logout().logoutSuccessUrl("/logoutSuccess").permitAll();
    }
}

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Related Articles

java 9 get list of all modules

Java 9 Stack Walking Api

Понравилась статья? Поделить с друзьями:
  • Java nio file nosuchfileexception как исправить
  • Java nio file accessdeniedexception как исправить
  • Java nio channels closedchannelexception майнкрафт как исправить
  • Java net sockettimeoutexception read timed out ошибка
  • Java net socketexception unrecognized windows sockets error 0 cannot bind