Spring自动装配报空指针异常

这几天在学Spring的自动装配,自己动手做一个小项目,但是被一个空指针异常卡住了。

启动的时候弹出index.jsp,这是一个登陆页面:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>消费管理系统--首页</title>
<style type="text/css">
    #surebtn{
        align:center;
    }
</style>
<script type="text/javascript">

</script>
</head>
<body>
    <h1>用户登录</h1>
    <div>
        <form action="UserServlet">
            用户名:<input id="username" type="text" name="nickname"/><br/>
            密码:<input id="password" type="password" name="password"><br/>
            <input type="hidden" name="action" value="login">
            <input id="surebtn" type="submit" value="登录"><button onclick="#" id="regbtn">注册</button>
        </form>
    </div>
</body>
</html>

跳转到UserServlet:

package com.ffy.servlet;

import java.io.IOException;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ffy.bean.User;
import com.ffy.service.UserService;
public class UserServlet extends HttpServlet{
    @Autowired
    private UserService userService;
    private static WebApplicationContext context;
    private String action=null;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        context=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        userService=context.getBean(UserService.class);
        if(req.getParameter("action")!=null){
            action=req.getParameter("action");
            if("login".equals(action)){
                if(login(req,resp)!=null){
                    User user=login(req,resp);
                    req.getRequestDispatcher("/list.jsp?userId="+user.getId()).forward(req, resp);
                }else{
                    req.getRequestDispatcher("loginError.jsp").forward(req, resp);
                }
            }
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    private User login(HttpServletRequest req,HttpServletResponse resp){
        User user=new User();
        user.setNickName(req.getParameter("nickname"));
        user.setPassword(req.getParameter("password"));
        User returnu=userService.login(user);
        if(returnu!=null){
            return returnu;
        }
        return null;
    }
}

若用户名和密码都正确,跳转到list.jsp,一个账单列表:

<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="javax.enterprise.context.spi.Context"%>
<%@page import="org.springframework.beans.factory.annotation.Autowired"%>
<%@page import="com.ffy.bean.Record"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.List" %>
<%@ page import="com.ffy.service.UserService" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<%


**UserService service=new UserService();**

    list=service.listRecordByUserId(Integer.parseInt(request.getParameter("userId")));
%>
<title>账单</title>
</head>
<body>
    <h1>账单</h1>
    <hr>
    <table>
        <tr>
            <td>编号</td>
            <td>金额</td>
            <td>类型</td>
            <td>日期</td>
            <td>描述</td>
        </tr>
        <%
            for(Record r:list){
        %>
            <tr>
                <td><%=r.getId() %></td>
                <td><%=r.getPrice() %></td>
                <td><%=r.getType().getName() %></td>
                <td><%=r.getDate() %></td>
                <td><%=r.getDescription() %></td>
            </tr>
        <%
            }
        %>
    </table>
</body>
</html>

注意加粗的那句话,这个list.jsp会调用UserService的listRecordByUserId(int userId)方法,具体如下:

package com.ffy.service;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffy.bean.Record;
import com.ffy.bean.User;

@Service
@Transactional
public class UserService {
    @Autowired
    private HibernateManage hibernateManage;

    public HibernateManage getHibernateManage() {
        return hibernateManage;
    }
    public void setHibernateManage(HibernateManage hibernateManage) {
        this.hibernateManage = hibernateManage;
    }
    public User login(User user){
        System.out.println("login........");
        Session session=hibernateManage.getSession();
        Query<User>query=session.createQuery("from User where nickname=:nickname and password=:password",User.class);
        query.setParameter("nickname",user.getNickName());
        query.setParameter("password", user.getPassword());
        if(query.getResultList().size()>0){
            return query.getResultList().get(0);
        }
        return null;
    }
    public List<Record> listRecordByUserId(int userId){
        if(hibernateManage==null){
            System.out.println("null-----------------------");
        }
        **Session session=hibernateManage.getSession();**
        Query<Record> q=session.createQuery("from Record r,User u where r.id=r.user.id",Record.class);
        List<Record> list=q.getResultList();
        return list;
    }
}

这个时候加粗的那句话就报空指针了,这是因为我在list.jsp直接new了一个UserService,直接new的话那这个UserService的实例service就不归spring管了,spring是不会自动装配UserService里面hibernateManage,所以报了空指针异常。只要将list.jsp里的UserService service=new UserService();改成ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
UserService service=context.getBean(UserService.class);就可以了。

<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="javax.enterprise.context.spi.Context"%>
<%@page import="org.springframework.beans.factory.annotation.Autowired"%>
<%@page import="com.ffy.bean.Record"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.List" %>
<%@ page import="com.ffy.service.UserService" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<%
    ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
    UserService service=context.getBean(UserService.class);
    List<Record> list=service.listRecordByUserId(Integer.parseInt(request.getParameter("userId")));
%>
<title>账单</title>
</head>
<body>
    <h1>账单</h1>
    <hr>
    <table>
        <tr>
            <td>编号</td>
            <td>金额</td>
            <td>类型</td>
            <td>日期</td>
            <td>描述</td>
        </tr>
        <%
            for(Record r:list){
        %>
            <tr>
                <td><%=r.getId() %></td>
                <td><%=r.getPrice() %></td>
                <td><%=r.getType().getName() %></td>
                <td><%=r.getDate() %></td>
                <td><%=r.getDescription() %></td>
            </tr>
        <%
            }
        %>
    </table>
</body>
</html>

唉,因为这个查了好久,对于大牛来说这种问题太low了,但是对于我这种还没毕业的小白来说实在是一个挺难的问题了,在这里记录一下。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值