Spring MVC数据库展示

标签 spring spring-mvc jdbc jstl datasource

我创建了一个 mySQL 表:student.studentInfo,其中:-

Int id autofill PK, 
 String name, 
int age,  
String email.

用户填写 StudentRegForm,姓名、年龄和电子邮件的值显示在 RegisteredStudent jsp 上。

我想在jsp页面上显示mySQL表的内容[数据元素]。

我的StudentDaoImpl:

public class StudentDaoImpl implements StudentDao {
    DataSource datasource;
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource datasource) {
        this.datasource = datasource;
        this.jdbcTemplate = new JdbcTemplate(datasource);
    }


    @Override
    public List<Student> getStudentList() {
        List<Student> studentList = new ArrayList<Student>();
        String sql = "select * from student.studentInfo";
        JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
        studentList = jdbcTemplate.query(sql, new StudentMapper());
        return studentList;
    }   
}

上面的StudentMapper方法是:

public class StudentMapper implements RowMapper<Student>{

    @Override
    public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
        Student student = new Student();
        student.setId( rs.getInt("id"));
        student.setName(rs.getString("name"));
        student.setAge(rs.getInt("age"));
        student.setEmail(rs.getString("email"));

        return student;
    }
}

在 MvcConfiguration 上设置 View 解析器,并将 DataSource 属性声明为 @Bean:

@Configuration
@ComponentScan(basePackages = "com.anand")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations(
                "/resources/");
    }

    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/student");
        dataSource.setUsername("root");
        dataSource.setPassword("root");

        return dataSource;
    }
}

学生填写此 Studentform.jsp:

<form   action="StudentAddSuccess.htm" method=post>
${formHeading}
<p>
id <input type="text" name="id" />
</p>
<p>
Name <input type="text" name="name"/>
</p>
<p>
Age <input type="text" name="age" />
</p>
<p>
Email <input type="text" name="email" />
</p>

<p>
<input type="submit" name="submit" value="save">
</p>

</form>

Controller 类是:

@Controller
public class StudentController {    
    @Autowired
    StudentDao stdDao;  
    @RequestMapping(value = "/studentForm.htm", method = RequestMethod.GET)
    public ModelAndView sendStudentForm() {
        ModelAndView mav = new ModelAndView("studentForm");
        mav.addObject("formHeading", "Student Registration Form");
        mav.setViewName("studentForm");
        System.out.println("student Form");
        return mav;
    }
//**********************************************************
    @RequestMapping(value = "RegdSuccess", method = RequestMethod.POST)
    public ModelAndView addStudent(@ModelAttribute("student1") Student student1) {
        ModelAndView mav = new ModelAndView();
        //mav.addObject("studentId", "id is:-" + student1.getId());
        mav.addObject("studentName", " name is:- " + student1.getName());
        mav.addObject("studentAge", " age is:-" + student1.getAge());
        mav.addObject("studentEmail", "student email is:-" + student1.getEmail());
        // mav.addObject("student", "student list is"+ student1);
        System.out.println(" hello  from RegdSuccess");
        mav.setViewName("RegdSuccess");
        return mav;
    }
//********************************************************************  


@RequestMapping( value = "RegdStudent", method = RequestMethod.GET)
        public ModelAndView showStudent(@ModelAttribute("std")Student std) throws IOException{
            ModelAndView mav = new ModelAndView();
            List<Student> listStudent= stdDao.getStudentList(); 
            mav.addObject("msg", "hello from Regd jsp");
            //mav.addObject("listStudent", listStudent);
            mav.addObject("msg",""+listStudent);

            System.out.println(" hello  from Regd Students controller"+std.getName());
            mav.setViewName("RegdStudent");

        return mav;
    }

StudentDao 是:

public interface StudentDao {   
    // create
    public void createStudent(Student student);

    // read
    public Student getStudent(Integer id);

    // Update
    public void updateStudent(Student student);

    // delete
    public void deleteStudent(Integer id);

    // List
    public List<Student> getStudentList();

    // save
    public void save(Student student);

}

StudentImplDao 是:

public class StudentDaoImpl implements StudentDao {
    StudentDaoImpl StudentDao;  
    DataSource datasource;
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource datasource) {
        this.datasource = datasource;
        this.jdbcTemplate = new JdbcTemplate(datasource);
    }

    public void doExecute() {
        String sql = "SELECT * FROM STUDENT.StudentInfo";
        SqlRowSet srs = jdbcTemplate.queryForRowSet(sql);
        int rowCount = 0;
        while (srs.next()) {
            System.out.println(srs.getString("id") + "-"
                    + srs.getString("name") + "-" + srs.getString("age") + "-"
                    + srs.getString("email"));

        }
        rowCount++;
        System.out.println("Number of records" + rowCount);
    }

    // -------------List----------------------------------------
    @Override
    public List<Student> getStudentList() {

        List<Student> studentList = new ArrayList<Student>();
        String sql = "select * from student.studentInfo";
        JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
        studentList = jdbcTemplate.query(sql, new StudentMapper());
        return studentList;

    }
 // other remaining methods of StudentDao go here for the implementations
    //………………………………
}

我可以在 Studentform.jsp 上输入姓名、年龄、电子邮件,这些输入会显示在 RegdSuccess.jsp 上,但我的 RegdStudent.jsp 页面没有按照我的意愿显示数据库中的列表记录。 RegdStudent.jsp 是:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>

<head>
<title>Regd. Students</title>
</head>
<body>
    hello from Regd Students jsp 
    <form:form>
    <table>

        <c:forEach items="${msg}" var="employee">
            <tr>
                <td><c:out value="${employee.id}" /></td>
                <td><c:out value="${employee.name}" /></td>
                <td><c:out value="${employee.age}" /></td>
                <td><c:out value="${employee.email}" /></td>
            </tr>
        </c:forEach>

    </table>
    </form:form>
</body>
</html>

我想让这个 JSP Age 显示 mysql 数据库中的所有记录。

最佳答案

通过做

mav.addObject("msg",""+listStudent);

您将 listStudent 列表强制转换为字符串,从而无法在 JSP 中对其进行迭代。如果您将该行更改为:

mav.addObject("msg", listStudent);

${msg} 对象将是一个可迭代列表。

<小时/>

自从您转储所有层的代码以来,您似乎不知道应用程序中哪些有效,哪些无效。您应该熟悉 IDE 的调试器,并学会遵循请求的路径来查看发生了什么。缩小问题范围可以大大减少查找和修复错误所需的时间。

关于Spring MVC数据库展示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25333516/

相关文章:

java - @Autowired 请求处理失败;嵌套异常是 java.lang.NullPointerException

java - 由 : java. lang.ClassNotFoundException : org. elasticsearch.transport.Netty3Plugin 引起

java - spring boot mongodb审计报错

spring - 无法从 messages.properties 文件读取验证消息

javascript - 当我从&lt;input type = "file">中选择文件时,如何获取文件名?

java - 发送两个不同类的对象到jsp并显示信息

java - 用java加密数据库用户名和密码?

Java/ Spring MVC : provide request context to child threads

mysql - Spring Boot + MySQL + Docker Compose - 无法让 Spring Boot 连接到 MySQL

java - 设置 arquillian.xml 和 glassfish-resource.xml