HTTP状态500 –内部服务器错误-数据源不能为空

时间:2019-01-29 20:45:19

标签: java eclipse servlets

我有问题。我创建一个动态Web项目,当我尝试运行JSP文件时,屏幕上出现错误。 这是错误:

HTTP Status 500 – Internal Server Error 
Type Exception Report

Message DataSource must not be null

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

Exception
java.lang.IllegalArgumentException: DataSource must not be null
    org.springframework.util.Assert.notNull(Assert.java:112)
    org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.<init>(NamedParameterJdbcTemplate.java:91)
    pl.kryspin.weekop.dao.UserDAOImpl.<init>(UserDAOImpl.java:21)
    pl.kryspin.weekop.dao.MysqlDAOFactory.getUserDAO(MysqlDAOFactory.java:12)
    pl.kryspin.weekop.service.UserService.addUser(UserService.java:15)
    pl.kryspin.weekop.controller.RegisterController.doPost(RegisterController.java:31)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

注意在服务器日志中可以找到根本原因的完整堆栈跟踪。

Apache Tomcat / 9.0.14`

UserDAOImpl:

    package pl.kryspin.weekop.dao;

import java.util.List;
import pl.kryspin.weekop.model.User;

import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import pl.kryspin.weekop.util.ConnectionProvider;

public class UserDAOImpl implements UserDAO {

    private static final String CREATE_USER = 
    "INSERT INTO user(username, email, password, is_active) VALUES(:username, :email, :password, :active);";

    private NamedParameterJdbcTemplate template;

    public UserDAOImpl() {
        template = new NamedParameterJdbcTemplate(ConnectionProvider.getDataSource());
    }

    @Override
    public User create(User user) {
        User resultUser = new User(user);
        KeyHolder holder = new GeneratedKeyHolder();
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(user);
        int update = template.update(CREATE_USER, paramSource, holder);
        if(update > 0) {
            resultUser.setId((Long)holder.getKey());
            setPrivigiles(resultUser);
        }
        return resultUser;
    }

    private void setPrivigiles(User user) {
        final String userRoleQuery = "INSERT INTO user_role(username) VALUES(:username)";
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(user);
        template.update(userRoleQuery, paramSource);
    }

    @Override
    public User read(Long primaryKey) {
        return null;
    }

    @Override
    public boolean update(User updateObject) {
        return false;
    }

    @Override
    public boolean delete(Long key) {
        return false;
    }

    @Override
    public List<User> getAll() {
        return null;
    }

    @Override
    public User getUserByUsername(String username) {
        return null;
    }
}

ConnectionProvider:

package pl.kryspin.weekop.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConnectionProvider {

    private static DataSource dataSource;

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    public static DataSource getDataSource() {
        if (dataSource == null) {
            try {
                Context initialContext = new InitialContext();
                Context envContext = (Context) initialContext
                        .lookup("java:comp/env");
                DataSource ds = (DataSource) envContext.lookup("jdbc/weekop");
                dataSource = ds;
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }

        return dataSource;
    }
}

RegisterController:

package pl.kryspin.weekop.controller;

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;

import pl.kryspin.weekop.service.UserService;

@WebServlet("/register")
public class RegisterController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        request.getRequestDispatcher("register.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("inputUsername");
        String password = request.getParameter("inputPassword");
        String email = request.getParameter("inputEmail");
        UserService userService = new UserService();
        userService.addUser(username, email, password);
        response.sendRedirect(request.getContextPath() + "/");
    }

}

register.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <title>Weekop - rejestracja</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" type="text/css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/resources/css/styles.css" type="text/css" rel="stylesheet">
  </head>

  <body>

    <nav class = "navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <a href="#" class="navbar-brand">Weekop</a>

        <button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">
          <span class="glyphicon glyphicon-list"></span>
        </button>

        <div class="collapse navbar-collapse navHeaderCollapse">
          <ul class="nav navbar-nav navbar-right">
            <li class="active"><a href="#">Główna</a></li>
            <li><a href="#">Dodaj</a></li>
            <li><a href="#">Zaloguj się</a></li>
          </ul>
        </div>

      </div>
    </nav>

    <div class="container">
        <div class="col-sm-6 col-md-4 col-md-offset-4">
            <form class="form-signin" method="post" action="register">
                <h2 class="form-signin-heading">Zarejestruj się</h2>
                <input name="inputEmail" type="email" class="form-control" placeholder="Email" required autofocus />
                <input name="inputUsername" type="text" name="inputUsername" class="form-control" placeholder="Nazwa użytkownika" required autofocus />
                <input name="inputPassword" type="password" class="form-control" placeholder="Hasło" required />
                <button class="btn btn-lg btn-primary btn-block" type="submit" >Zarejestruj</button>
            </form>
        </div>
    </div>

    <footer class="footer">
      <div class="container">
        <p class="navbar-text">Weekop - developed by <a href="http://javastart.pl">JavaStart.pl</a></p>
      </div>
    </footer>

    <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="resources/js/bootstrap.js"></script>
  </body>
</html>

context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Context>
    <Resource 
        name="jdbc/weekop" 
        auth="Container" 
        type="javax.sql.DataSource"
        initialSize="10" 
        maxTotal="100" 
        maxIdle="30" 
        maxWaitMillis="10000" 
        username="root"
        password="admin" 
        driverClassName="com.mysql.cj.jdbc.Driver" 
        url="jdbc:mysql://localhost:3306/weekop" />

    <Realm 
        className="org.apache.catalina.realm.DataSourceRealm" 
        dataSourceName="jdbc/weekop"
        userTable="user" 
        userNameCol="username" 
        userCredCol="password" 
        userRoleTable="user_role"
        roleNameCol="role_name" 
        localDataSource="true" />
</Context>

0 个答案:

没有答案