由一年前的笔试引发滴感悟 (宠物与主人 demo)

时间:2020-12-27 22:21:48

我好像很久都没有认认真真写过blog了,最近很闲,特别闲,到那种地步呢?两个月多没什么大事做,这期间我一直再看框架方面的知识,对很多东西都有了新的认识,O(∩_∩)O~~开心。

无意间,想起了多年前(其实也就是一年前(*^__^*)……)我去一家公司面试,一进去给台电脑笔试,用ssh写一个demo,把数据库里面的信息显示在页面上,对于刚毕业的我来说,算是个难点,ssh?前台后台结合?配置文件?怎么跟数据库连接?这一步步都是问题,因为我还没有到水到渠成的时候,一同面试的还有两个前辈,工作一两年了,我尽所能的写出我知道的东西。。

三个小时之后,我们都离开了办公室,所谓筋疲力尽,当时正值中午12点。又饿又累,虽然没做出来,但是确实努力了,我问了问一同面试的两个男生,他们最后做出来了吗?。。。。没有。。。哦,忘了说,我们用来开发的那台电脑,都是干净的什么都没装,开发工具,jdk什么的都没装,要自己安装,配置然后在开发。

写出来的东西尽显的平淡无味,切身体会过,再次回想起来心还是会波动。

我今天也用了一点时间,写了一个小demo,很简单,没什么功能就是把数据库里面的数据显示在页面上,用spring+hibernate +jsp

没用到什么技术,用spring ioc完成bean的配置

使用spring mvc构建表现层  用hibernate数据库操作组件实现数据库数据操作的具体实例,能实现我最基本的功能显示数据就可以了。

写这个blog的目的是为了纪念一年前的那次笔试。无他。

 项目截图:

由一年前的笔试引发滴感悟 (宠物与主人 demo)


附加一个:


由一年前的笔试引发滴感悟 (宠物与主人 demo)


新建两张表 vet 和master 宠物和主人的表
create table master(
 id int primary key identity(1,1),
 name varchar(30) not null,
 age int not null,
 email varchar(30) not null,
 career varchar(30) not null
)

insert into master values('舒婷',23,'wst1@163.com','java程序員')
insert into master values('ken',33,'ken@163.com','老闆')
insert into master values('herry',43,'herry@163.com','CEO')
insert into master values('baby',53,'baby@163.com','經歷')

create table vet(
 id int primary key identity(1,1),
 name varchar(30) not null,
 age int not null,
 masterid int Default (0),
 species varchar(30) not null
)

insert into vet values('tally',1,0,'cat')
insert into vet(name,age,species) values('jlly',1,'dog')--插入有默認值的數據時,省略有默認值的字段
insert into vet(name,age,masterid,species) values('fmmay',1,1,'dog')-- 加上有默認值的字段,并輸入對應的值.
select * from vet

配置文件
Web.xml 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <servlet>
		<servlet-name>test</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
				/WEB-INF/applicationConfig/app-config.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

    <servlet-mapping>
		<servlet-name>test</servlet-name>
		<url-pattern>*.action</url-pattern>
   </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>


<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- Scans the classpath of this application for @Components to deploy as beans -->
	<!-- 規約所有進行掃描的類,以完成Bean創建和自動依賴注入功能  -->
	<!-- 完全取消bean配置的做法就是使用component 但是要指明使用注解的java类 -->
	<context:component-scan base-package="www.com.spring.*" />  
	<!-- <context:annotation-config /> -->
	<!-- Configures the @Controller programming model -->
	<mvc:annotation-driven /> <!-- 使用<mvc:resources/>元素,把mapping的URI注册到SimpleUrlHandlerMapping的urlMap中, -->
	<!-- misc -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
	    <property name="suffix" value=".action"/>
	</bean>
	
	<!-- Configures Hibernate - Database Config -->
	<import resource="db-config.xml" />
</beans>

<?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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"><value>com.microsoft.sqlserver.jdbc.SQLServerDriver</value></property>
        <property name="url"><value>jdbc:sqlserver://10.1.100.217:8080;DatabaseName=smartclient</value></property>
        <property name="username"><value>000</value></property>
        <property name="password"><value>12345678</value></property>
   </bean>
   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource"><ref local="dataSource"/></property>
        <property name="packagesToScan" value="www.com.spring.*" />
        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
			<!--  <prop key="hibernate.hbm2ddl.auto">update</prop>-->
			<prop key="hibernate.format_sql">true</prop>
        </props>
        </property>
   </bean>	 
	<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
	<!-- 定义一个事物管理器  -->
	<tx:annotation-driven/>
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory"><ref local="sessionFactory"/></property>
        <qualifier value="petclinic"/><!-- 限定词 -->
    </bean>
</beans>


下面是vet实体类:
package www.com.spring.module;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "vet")
public class Vet {
	 private int id;
	 private String name;
	 private int age;
	 private int masterid;
	 private String species;
	 
	 @Id
	 @GeneratedValue
	 @Column(name = "id")
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Column(name = "name")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name = "age")
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Column(name = "masterid")
	public int getMasterid() {
		return masterid;
	}
	public void setMasterid(int masterid) {
		this.masterid = masterid;
	}
	@Column(name = "species")
	public String getSpecies() {
		return species;
	}
	public void setSpecies(String species) {
		this.species = species;
	}
}

Dao层:
package www.com.spring.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import www.com.spring.module.Vet;

@Repository
public class VetDao {
	private HibernateTemplate hibernateTemplate;
	@SuppressWarnings("unused")
	@Autowired
	private void setHibernateTemplate (SessionFactory sessionFactory){
		this.hibernateTemplate =new HibernateTemplate(sessionFactory);
	}
	
	public List<Vet> getAllVets(){
		String hql = "from Vet";
		List<Vet> list = this.hibernateTemplate.find(hql);
		return list;
	}
}

业务层service

package www.com.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import www.com.spring.dao.VetDao;
import www.com.spring.module.Vet;
@Service
public class VetService {
	private VetDao vetDao ;
	@Autowired
	public void setVetDao(VetDao vetDao) {
		this.vetDao = vetDao;
	}
	
	@Transactional("petclinic")
	public List<Vet> getAllVets(){
		return this.vetDao.getAllVets();
	}
}

Web层

package www.com.spring.web;

import java.io.IOException;
import java.util.List;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import www.com.spring.module.Vet;
import www.com.spring.service.VetService;

@Controller
public class VetWeb {
	private VetService vetService;
	@Autowired
	public void setVetService(VetService vetService) {
		this.vetService = vetService;
	}
	
	@RequestMapping(value = "petclinic/getAllVet.action")
	public void getAllVets(HttpServletRequest request,HttpServletResponse response){
		List<Vet> list = this.vetService.getAllVets();
		request.setAttribute("data", list);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("/vet.jsp");
	  try {
		dispatcher.forward(request, response);
	} catch (ServletException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	}
}


前台vet.jsp 代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>宠物信息页面</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  <body>
  <script type="text/javascript" src="js/showPic.js"></script>
  <jsp:include page="head.jsp"></jsp:include>
   <table border="1">
  	<tr><td>宠物编号</td><td>宠物名称</td><td>宠物年龄</td><td>是否被领养</td><td>物种分类</td></tr>
	  <c:forEach var="vet" items="${data}">
	    <tr>
	      <td>${vet.id}</td><td><a href="${vet.name}.jsp" >${vet.name}</a></td>
	      <td>${vet.age}</td><td>${vet.masterid}</td><td>${vet.species}</td>
	    </tr>
	  </c:forEach>
	</table>
  </body>
</html>