0

Please before setting it to duplicate read it first!

It's not a duplicate of: HTTP Status 404 - The requested resource (/) is not available I already tried it and all other topics about this in this site and none of the helped.

I am developing a small project with Spring MVC and Tomcat, so far I've created login and main page, which is redirected after logging in. These are my files related to the issue, if there is something missing or needed, please, just let me know.

The issue is, it shows perfectly index.jsp (login page) but if I introduce credentials it shows the error HTTP-404: Requested resource is not available, I cannot find where the issue is. It should go to main.jsp if the login is correct, if not, it should go back to index.jsp and show an error message. I do not get any error in the console either. Thanks in advance.

web.xml

   <?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" id="WebApp_ID" 
        version="3.1">
     <display-name>WebProject</display-name>
     <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
      <servlet-name>SpringDispatcherServlet</servlet-name>
       <servlet-
      class>org.springframework.web.servlet.DispatcherServlet</servlet- 
    class>
   <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/config-mvc.xml</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
   <servlet-name>SpringDispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
    </servlet-mapping>
   <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:configApplication.xml</param-value>
   </context-param>
  </web-app>

index.jsp

 <!doctype html>
 <html>
 <head>
<meta charset="utf-8" />
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>TPV Cocoa</title>
<style>
    .formulario{
        margin: 0 auto;
        float: none;
    }
</style>
</head>
<body>
<div class="container-fluid">
<h1 class="text-center">Inicia sesión en TPV Cocoa</h1>
<form action="login.do" method="post">
<div class="row">
    <div class="col-lg-4 col-lg-offset-4 col-sm-4 col-sm-offset-4">  
        <div class="formulario form-group">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon 
 glyphicon-user"></i></span>
                <input id="user" type="text" class="form-control" 
 name="user" placeholder="Usuario" value=""> 
            </div>
            <br>
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon 
  glyphicon-lock"></i></span>
                <input id="password" type="password" class="form-control" 
  name="password" placeholder="Password" value=""> 
            </div>
            <div>
                <c:out value="${requestScope.error}"/>
            </div>
            <br>
            <input type="submit" class="btn btn-default" value="Iniciar 
     sesión"/>
        </div>
    </div>
</div>
 </form>
   <div id="avisos" style="color:red"><?php echo $avisos ?></div>
 </div>
 <script>document.getElementById('usuario').focus();</script>   
  </body>
   </html>

config-mvc.xml

     <?xml version="1.0" encoding="UTF-8"?>
     <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="viewResolver" 
 class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
          <property name="prefix">
              <value>/WEB-INF/</value>
           </property>
          <property name="suffix">
             <value>.jsp</value>
          </property>
    </bean>
    </beans>

UserController(Controller used for the login)

@Controller
@ComponentScan("cocoa.tpv.controllers")
public class UserController {

@Autowired
UserFacade userService;


@RequestMapping("login.do")
public ModelAndView loginUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException{
    HttpSession session=request.getSession();

    ModelAndView modelAndView=new ModelAndView();
    User user=new User();

    String userName=request.getParameter("user");
    String userPassword=request.getParameter("password");

    try{
        user.setName(userName);
        user.setPassword(userPassword);

        User usuarioLogged=userService.getUser(user);

        if(usuarioLogged == null){
            modelAndView.setViewName("index.jsp");
        }else{
            modelAndView.setViewName("main.jsp");
            modelAndView.addObject("usuarioLogged", usuarioLogged);
        }

    }catch(MainException excepcion){
        modelAndView.setViewName("index.jsp");
        modelAndView.addObject("error", excepcion.getMessage());
    }

    return modelAndView;

}
}

My project is structured like this:

introducir la descripción de la imagen aquí

EDIT 1:

I add a video so you all can see what my site actually does and the issue.

https://i.gyazo.com/e5aac4b7c067247f2424d4a8cc6eb123.mp

EDIT 2:

I am adding Server logs from the moment I tried to log in:

localhost_access_log2017-07-14.txt

This is what I get when I make the first login:

  127.0.0.1 - - [14/Jul/2017:17:32:30 +0200] "GET / HTTP/1.1" 200 11452

And this is what I get after I try to log in again:

   0:0:0:0:0:0:0:1 - - [14/Jul/2017:17:34:05 +0200] "GET /TPV/index.jsp 
   HTTP/1.1" 200 1938

   0:0:0:0:0:0:0:1 - - [14/Jul/2017:17:34:10 +0200] "POST /TPV/login.do 
   HTTP/1.1" 404 1002
NeoChiri
  • 296
  • 4
  • 18
  • 1
    You shouldn't put `@ComponentScan` on your controller. This goes in your `Configuration` – Rana_S Jul 13 '17 at 19:15
  • `@Autowired UserFacade userService;` you have not defined this bean in your config file for example ` ` – Akshay jain Jul 13 '17 at 19:23
  • @RossiRobinsion I actually tried by doing it in the configuration and it wasn't working properly, to scan all packages but I found that annotation and it worked perfectly. – NeoChiri Jul 13 '17 at 19:30
  • @Akshayjain As far as I know and tested, I don't need to declare the bean in a XML if I use Autowired annotation, I didn't need to in a past project I made. – NeoChiri Jul 13 '17 at 19:31
  • To enable autowiring you have to define `` in config file [https://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/] – Akshay jain Jul 13 '17 at 19:40
  • @Akshayjain I just did but it didn't solve the issue – NeoChiri Jul 13 '17 at 19:44
  • try once by defining both these in your config-mvc.xml ` ` according this link _https://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/_ – Akshay jain Jul 13 '17 at 19:59
  • Now I got this exception: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException – NeoChiri Jul 13 '17 at 20:17

2 Answers2

0

Try this:

<servlet-mapping>
<servlet-name>SpringDispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern> //Change the url pattern attribute in your web.xml to this
</servlet-mapping>

The code editor on the site messes up the format but change the contents of your url-pattern to: /*

Jamal H
  • 934
  • 7
  • 23
0

add this to your action in the form declaration:

<form action="${pageContext.request.contextPath}/login.do" method="POST">

i have modified your code, please try now

    @RequestMapping("login.do", method=RequestMethod.POST)
public ModelAndView loginUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException{
    HttpSession session=request.getSession();

    ModelAndView modelAndView=new ModelAndView();
    User user=new User();

    String userName=request.getParameter("user");
    String userPassword=request.getParameter("password");

    try{
        user.setName(userName);
        user.setPassword(userPassword);

        User usuarioLogged=userService.getUser(user);

        if(usuarioLogged == null){
            modelAndView.setViewName("redirect:index");
        }else{
            modelAndView.setViewName("redirect:main");
            modelAndView.addObject("usuarioLogged", usuarioLogged);
        }

    }catch(MainException excepcion){
        modelAndView.setViewName("redirect:index");
        modelAndView.addObject("error", excepcion.getMessage());
    }

    return modelAndView;

}

´

[EDIT]: i missed to remove the extensions Hope this helps!

[EDIT 2]:

Look to this controller please, maybe you can use it as reference

@Controller
@RequestMapping("/singup")
public class SingupController {

    SingupValidations userValidations;
    private JdbcTemplate jdbcTemplate;

    public SingupController(){
        this.userValidations = new SingupValidations();
        DBConnections DBConnection = new DBConnections();
        this.jdbcTemplate = new JdbcTemplate(DBConnection.connect());

    }

    @RequestMapping(method=RequestMethod.GET)
    public ModelAndView singup(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("singup");
        mav.addObject("users", new User());
        return mav;
    }

    @RequestMapping(method=RequestMethod.POST)
    public ModelAndView singup(@ModelAttribute("users") User u, BindingResult result){

        this.userValidations.validate(u, result);
        if(result.hasErrors()){
            ModelAndView mav = new ModelAndView();
            mav.setViewName("singup");
            mav.addObject("users", new User());
            return mav;

        }else{
            this.jdbcTemplate.update("insert into Users (nombre, correo, telefono, password) values (?,?,?,?)", u.getUsername(), u.getCorreo(), u.getTelefono(), u.getPassword());
            ModelAndView mav = new ModelAndView();
            mav.setViewName("redirect:index");
            return mav;

        }

    }
Ivan Lynch
  • 563
  • 5
  • 23
  • I'm kind of new with ModelAndView, and in my controller I set the View according to what happens (wrong/correct login) and then I return the object, not just return and creating the object at the same time so I'm not sure how I can adjust your solution. – NeoChiri Jul 13 '17 at 19:41
  • Good morning!, can you post your server log when you try to login? – Ivan Lynch Jul 14 '17 at 15:10
  • See my last EDIT please – NeoChiri Jul 14 '17 at 16:40
  • You don't have a POST method declared, please try with separated methods i will edit my post and i show you any controller to get reference – Ivan Lynch Jul 14 '17 at 16:52
  • I will try with that, I'll get back to you as soon as I have some results, in the mean time I have a couple of questions, why do I need POST and GET method? what's the difference between the functionatily of each one? I am asking this because in a past project I made, I didn't need this. – NeoChiri Jul 14 '17 at 17:22
  • The difference between those method is the action for example, your are using request mapping to call i.e: "/action" how the server knows why you are trying to do?, if you need data or you need to add new data. If in your last project you didn't declare the methods maybe in another place of your project this methods was handled automatically. – Ivan Lynch Jul 14 '17 at 17:34