0
点赞
收藏
分享

微信扫一扫

Spring教程____SpringMVC入门小列子(主流模式,精简模式)

非凡兔 2023-09-13 阅读 4


//添加spring的依赖和先关的jar包


//整合结构图

Spring教程____SpringMVC入门小列子(主流模式,精简模式)_spring

Spring教程____SpringMVC入门小列子(主流模式,精简模式)_xml_02

//配置spring的applicationContext.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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
		
<!-- springconfigStart -->
	
	<!-- 加载多个资源配置文件    -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>  	
	
	<!-- 配置dbcp数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
	
	<!-- 配置MVC的伞要素 1使用注解配置bean 2使用扫描方式加载bean 3使用注解映射的mvc请求   -->
	<context:annotation-config />
	<context:component-scan base-package="com.frame"></context:component-scan>
	<!-- 通过注解,把URL映射到Controller上  -->
	<mvc:annotation-driven />
	  
	<!-- 定义jdbcTemplate模板 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- 配置事物管理和使用主耳机式事物 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager" />
	
<!-- springconfigEnd -->
</beans>

//配置jdbc配置文件

################Oracle_JDBC################
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:orcl  
jdbc.username=oracle  
jdbc.password=123456

//配置springmvc-servlet,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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	<!-- 默认的视图解析器 -->
	<bean id="defaultViewResolver" 	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" 	value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/project/" />
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

//配置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">
<!-- 配置页面index页面 -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
<!-- 配置监听器初始化加载Spring的配置   -->  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
<!-- 配置Stringmvc的servlet -->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
</web-app>

//配置baseController

package com.frame.base.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * @author Administrator
 * father controller
 */
public class BaseController {
	//father log
	protected final Logger logger = Logger.getLogger(this.getClass());
	//request 
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	//get reqyest
	@ModelAttribute
	protected void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.session = request.getSession();
	}

	protected  void writeRespData(String data) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=utf-8");
			response.getWriter().write(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}

//创建basedao和basedaoimpl

package com.frame.base.dao;

import java.util.List;

public interface BaseDao {
	
	public int insert(String sql,Object[] args); 
	
	public <T> T findObject(String sql,Object[] args,Class<T>clazz);
	
	public int update(String sql,Object[] args);
	
	public int delete(String sql,Object[] args);
	
	public <E> List<E> findList(String sql,Object[] args,Class<E>clazz);
	
}

package com.frame.base.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

public class BaseDaoImpl implements BaseDao{

	@Autowired
	private JdbcTemplate template;
	
	//日志记录
	protected final Logger logger = Logger.getLogger(this.getClass());	
	
	@Override
	public int insert(String sql, Object[] args) {
		return template.update(sql, args);
	}

	@Override
	public <T> T findObject(String sql, Object[] args, Class<T> clazz) {
		RowMapper<T> rm = ParameterizedBeanPropertyRowMapper.newInstance(clazz);
		return template.queryForObject(sql, args, rm);
	}

	@Override
	public int update(String sql, Object[] args) {
		return template.update(sql, args);
	}

	@Override
	public int delete(String sql, Object[] args) {
		return template.update(sql, args);
	}

	@Override
	public <E> List<E> findList(String sql, Object[] args, Class<E> clazz) {
		RowMapper<E> rm = ParameterizedBeanPropertyRowMapper.newInstance(clazz);
		return template.query(sql, args, rm);
	}


}

//创建student实体类

package com.frame.student.bean;

public class Student {

	// PO
	private String stuid;
	private String stuname;
	private String stutime;

	// Encap
	public String getStuid() {
		return stuid;
	}

	public void setStuid(String stuid) {
		this.stuid = stuid;
	}

	public String getStuname() {
		return stuname;
	}

	public void setStuname(String stuname) {
		this.stuname = stuname;
	}

	public String getStutime() {
		return stutime;
	}

	public void setStutime(String stutime) {
		this.stutime = stutime;
	}

	@Override
	public String toString() {
		return "Student [stuid=" + stuid + ", stuname=" + stuname
				+ ", stutime=" + stutime + "]";
	}

}

//创建studnetdao和studentDaoImpl

package com.frame.student.dao;

import com.frame.base.dao.BaseDao;

public interface StudentDao extends BaseDao{

	
}

package com.frame.student.dao;

import org.springframework.stereotype.Repository;
import com.frame.base.dao.BaseDaoImpl;

@Repository 
public class StudentDaoImpl extends BaseDaoImpl implements StudentDao{


}

//StudentService和实现类


package com.frame.student.service;

import java.util.List;

import com.frame.student.bean.Student;

public interface StudentService {
	
	public int insert(Student entity); 
	
	public Student findObject(Student entity);
	
	public int update(Student entity);
	
	public int delete(Student entity);
	
	public List<Student> findList(Student entity);
	
}

package com.frame.student.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.frame.student.bean.Student;
import com.frame.student.dao.StudentDao;

@Service
public class StudentServiceImpl implements StudentService{

	@Autowired
 	private StudentDao dao;
	
	@Override
	public int insert(Student entity) {
		 StringBuffer sb=new  StringBuffer();  
		 sb.append("insert into STUDENT(stuid,stuname,stutime) values(?,?,?) ");  
	     Object [] args={entity.getStuid(),entity.getStuname(),entity.getStutime()};
		return dao.insert(sb.toString(), args);
	}
	
	@Override
	public Student findObject(Student entity) {
		 StringBuffer sb=new  StringBuffer();  
	        sb.append("select * from  STUDENT where  stuid=? and stuname=?  ");  
	        Object [] args={entity.getStuid(),entity.getStuname()};  
		return dao.findObject(sb.toString(), args, Student.class);
	}

	@Override
	public int update(Student entity) {
		 StringBuffer sb=new  StringBuffer();  
	     sb.append("update STUDENT set stuname=? , stutime=? where stuid=? ");  
	     Object [] args={entity.getStuname(),entity.getStutime(),entity.getStuid()};  
		return dao.update(sb.toString(), args);
	}

	@Override
	public int delete(Student entity) {
		 StringBuffer sb=new  StringBuffer();  
	     sb.append("delete from STUDENT where  stuid=? ");  
	     Object [] args={entity.getStuid()};  
		return dao.delete(sb.toString(), args);
	}

	@Override
	public List<Student> findList(Student entity) {
		 StringBuffer sb=new  StringBuffer();  
	     sb.append("select * from STUDENT where 1=1");  
	     Object [] args={};  
	     return dao.findList(sb.toString(), args, Student.class);
	}

}

//studnet控制层

package com.frame.student.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.frame.base.controller.BaseController;
import com.frame.student.bean.Student;
import com.frame.student.service.StudentService;

@Controller
@Scope("prototype")
@RequestMapping("/student")
public class StudentController extends BaseController{

	//装配service层
	@Autowired
	private StudentService service;
	
	@RequestMapping("/findStudent.do")
	public String findStudent(){
		//获取请求参数
		String stuid=request.getParameter("stuid");
		String stuname=request.getParameter("stuname");
		Student entity=new Student(); 
		entity.setStuid(stuid);
		entity.setStuname(stuname);
		Student resultStudent=service.findObject(entity);
		if(resultStudent!=null){
			return "/main/main";
		}else{
			return "/error/error";
		}
	}
	
	@RequestMapping("/findStudentList.do")
	public String findStudentList(ModelMap map){
		//获取请求参数
		Student entity=new Student(); 
		List<Student> studentList = service.findList(entity);
		map.addAttribute("studentList", studentList); 
		
		return "student/studentList";
	}
	
	@RequestMapping("/insertStudent.do")
	public String insertStudent(ModelMap map){
		//获取请求0参数
		String stuid=request.getParameter("stuid");
		String stuname=request.getParameter("stuname");
		String stutime=request.getParameter("stutime");
		Student entity=new Student(); 
				entity.setStuid(stuid);
				entity.setStuname(stuname);
				entity.setStutime(stutime);
		service.delete(entity);
		return "student/insertStudent";
	}
	@RequestMapping("/deleteStudent.do")
	public void deleteStudent(ModelMap map){
		//获取请求0参数
		String stuid=request.getParameter("stuid");
		Student entity=new Student(); 
		entity.setStuid(stuid);
		service.delete(entity);
	}
	
	
	
	
}

//index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'index.jsp' starting page</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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body style="text-align: center;">
    	<form action="<%=basePath%>student/findStudent.do">
    		编号:<input name="stuid" type="text" >
    		<br/>
    		姓名:<input name="stuname" type="text" >
    		<br/>
    		<input name="submit" type="submit"  value="Sign Up" />
    	</form>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'main.jsp' starting page</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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  	<H2>登陆成功</H2>
	<div>
		<ul>
			<li>
				<a href="<%=basePath%>/student/findStudentList.do">查询用户列表</a>
			</li>
			<li>
				<a href="<%=basePath%>/student/insertStudent.do">增加用户</a>
			</li>
		</ul>
	</div>
  </body>
</html>

//发布项目运行

Spring教程____SpringMVC入门小列子(主流模式,精简模式)_spring_03

Spring教程____SpringMVC入门小列子(主流模式,精简模式)_xml_04


Spring教程____SpringMVC入门小列子(主流模式,精简模式)_bc_05

//源码 http://pan.baidu.com/s/1boUkkHp



举报

相关推荐

0 条评论