SSH(Spring_SpringMVC_Hibernate)

Users实体类

package com.tao.pojo;

public class Users {

    private int id;
    private String name;
    private String pass;
    
    public Users() {
        super();
    }
    public Users(String name, String pass) {
        super();
        this.name = name;
        this.pass = pass;
    }
    public Users(int id, String name, String pass) {
        super();
        this.id = id;
        this.name = name;
        this.pass = pass;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    @Override
    public String toString() {
        return "Users [id=" + id + ", name=" + name + ", pass=" + pass + "]";
    }    
    
}

Users.hbm.xml映射文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-1-31 10:52:02 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.tao.pojo.Users" table="USERS">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="pass" type="java.lang.String">
            <column name="pass" />
        </property>
    </class>
</hibernate-mapping>

BaseDAO方法

package com.tao.dao;

import java.io.Serializable;
import java.util.List;

public interface BaseDAO<T> {
    
    public List<T> findAll();
    
    public T findById(Serializable id);
    
    public T update(T t);
    
    public T save(T t);

    public T deleteById(Serializable t);
    
    
}


UsersDAO方法

package com.tao.dao;

import com.tao.pojo.Users;

public interface UsersDAO extends BaseDAO<Users>{

    
}

UsersDAOImpl实现类

package com.tao.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.tao.dao.UsersDAO;
import com.tao.pojo.Users;

@Repository
public class UserDAOImpl implements UsersDAO{

    @Value("#{hibernateTemplate}")
    private HibernateTemplate hibernateTemplate;
    
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    @Override
    public List<Users> findAll() {
        // TODO Auto-generated method stub
        
        List<Users> list = (List<Users>) hibernateTemplate.find("from Users");
        return list;
    }

    @Override
    public Users findById(Serializable id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Users update(Users t) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Users save(Users t) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Users deleteById(Serializable t) {
        // TODO Auto-generated method stub
        return null;
    }

}

UsesrService方法

package com.tao.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import com.tao.dao.UsersDAO;
import com.tao.pojo.Users;

@Service
public class UsersService {
    @Autowired
    private UsersDAO UsersDAO;
     
    public void setUsersDAO(UsersDAO usersDAO) {
        UsersDAO = usersDAO;
    }


    public List<Users> findAll(){
        return UsersDAO.findAll();
    }

}

application-context.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <context:component-scan base-package="com.tao.dao.impl"></context:component-scan>
    <context:component-scan base-package="com.tao.service"></context:component-scan>
    
<!-- 配置数据源 -->
    <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test0126?characterEncoding=utf-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        
    </bean>
    <!--整合部分  -->
    <bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" id="localSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>    
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>
        </property>
        
        <!--映射文件  -->        
        <property name="mappingDirectoryLocations">
            <list>
                <value>classpath:com/tao/pojo</value>
            </list>
        </property>
    </bean>

    <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
        <property name="sessionFactory" ref="localSessionFactoryBean"></property>
    </bean>
</beans>


test测试
package com.tao.test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.tao.pojo.Users;
import com.tao.service.UsersService;

public class TestMain {

    @Test
    public void testALl() {

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
        UsersService us = context.getBean("usersService",UsersService.class);
        List<Users> list = us.findAll();
        for (Users users : list) {
            System.out.println(users);
        }                
    }
}

test测试程序代码完毕。写到这儿测试一下,

测试如果报下面这个错;(No bean named 'usersService'
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'usersService' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:685)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1205)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
    at com.tao.test.TestMain.testALl(TestMain.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

在application_context.xml配置文件写入下面代码(自动扫描组件):写在最开始
   <context:component-scan base-package="com.tao.dao.impl"></context:component-scan>
    <context:component-scan base-package="com.tao.service"></context:component-scan>
没有错就继续,jsp页面
先写一个spring_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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <!--自动扫描  -->
    <context:component-scan base-package="com.tao.controller"></context:component-scan>

</beans>

写一个UserController类

package com.tao.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tao.pojo.Users;
import com.tao.service.UsersService;

@Controller
@RequestMapping("/user/")
public class UserController {
    @Autowired
    private UsersService usersService;
    public void setUsersService(UsersService usersService) {
        this.usersService = usersService;
    }

    @RequestMapping("/findAll")    //访问路径
    public String findAll(HttpServletRequest request) {
        System.out.println("all");
        List<Users> list = usersService.findAll();
        request.setAttribute("list", list);
        //转向页面
        return "/main2.jsp";
    }
}

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>Insert title here</title>
</head>
<body>
<a href="user/findAll">查询所有</a>
</body>
</html>

main2.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>main2</title>
</head>
<body>
主页面
    
    <c:forEach items="${list }" var="us">
        ${us.id },${us.name},${us.pass}<br>
    </c:forEach>
</body>
</html>

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>Project0126_001_SSH</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 加载 application-context.xml 文件 -->
      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      
  <!-- application的初始化参数 -->
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:application-context.xml</param-value>
      </context-param>
      
  <!--加载 spring_mvc.xml文件 -->
  <servlet>
      <servlet-name>mvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!--配置配置文件的路径 -->
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring_mvc.xml</param-value>
      </init-param>
  </servlet>
 
  <!--mvc映射  -->
  <servlet-mapping>
      <servlet-name>mvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

从index.jsp页面开始运行

执行“查询所有”【fingAll方法】报404找不到时(查看web.xml文件,看)
HTTP Status 404 – Not Found
Type Status Report
Message /Project0126_001_SSH/user/findAll
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/9.0.0.M26
解决方法:
在web.xml文件写上
<!--mvc 映射  -->
  <servlet-mapping>
      <servlet-name>mvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>


报找不到main.jsp这个页面
HTTP Status 404 – Not Found
Type Status Report
Message /Project0126_001_SSH/user/main.jsp
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/9.0.0.M26

解决方法:
在UserController,文件中找到转向 main.jsp 的 return,在其前面加一个斜杠,将 “main.jsp” 变成 “/main.jsp”


 

posted @ 2018-01-31 19:26  理想的诱惑  阅读(114)  评论(0编辑  收藏  举报