SpringMVC(21):使用springmvc+spring+jdbc 优化订单管理系统的示例(ID查看供应商信息明细-REST的功能实现)

2018年1月28日

【0】功能:

     实现REST风格的URL,提供查看该ID对应的供应商信息明细的的功能;登陆进入系统页面后,在“查看供应商一栏”输入需要查看的供应商ID,点击提交,然后进入供应商明细的页面;


【1】文件框架与jar包


图1


图2


【2】View层:

1. 在sys.jsp加入添加代码:

	<h4>------------------点击下面的链接进行查询供应商信息明细(REST):---------</h4>
	<br>
		<form action="${pageContext.request.contextPath }/usera/view"
			method="post">
			Pro_Id:<input type="text" value="" name="viewId">		
			<input type="submit" value="submit">
		</form>
	<br>	

效果:


图3


2. 新建 /jsp/providerviewId.jsp(url提交页面):

<%@ 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>
	<h4>这是providerviewId页面!</h4>>
	<a href="${pageContext.request.contextPath }/usera/view/${provider1.id}"  type="button">ID_Check_provider</a>
</body>
</html>

效果:


图4


3. 新建 /jsp/providerview.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>
	<h5>providerview页面</h5>
	provider2:${provider2.id},${provider2.proCode}
	,${provider2.proName}
	,${provider2.proDesc},${provider2.proContact}
	,${provider2.proPhone},${provider2.proFax}
	,${provider2.proAddress},${provider2.pic_BusinessLic}
	,${provider2.pic_OrgCodeCer},${provider2.createBy}
	<br>
	provider1:${provider1.id},${provider1.proCode}
	,${provider1.proName}
	,${provider1.proDesc},${provider1.proContact}
	,${provider1.proPhone},${provider1.proFax}
	,${provider1.proAddress},${provider1.pic_BusinessLic}
	,${provider1.pic_OrgCodeCer},${provider1.createBy}
</body>
</html>


【3】Controller层写处理方法

在providerController.java添加代码(两个处理方法):

	
	@RequestMapping(value="/view",method=RequestMethod.POST)
	public String ViewProviderId(@RequestParam("viewId") Integer viewId,
					Model model){
		System.out.println("ProviderController-ViewProviderId");
		Provider provider1 = new Provider();
		model.addAttribute("provider1",provider1);
		provider1.setId(viewId);
		System.out.println("provider1: "+provider1.toString());
		return "providerviewId";
	}
	
	@RequestMapping(value="/view/{id}",method=RequestMethod.GET)
	public String viewProvider(@PathVariable String id,Model model,
					Provider provider1) throws ParseException, SQLException{
		System.out.println("ProviderController-viewProvider");
		System.out.println("view provider id ======="+id);
		provider1 = providerService.getProviderById(id);
		System.out.println("provider1: "+provider1);
		model.addAttribute("provider2",provider1);
		return "providerview";
	}


解释:1、ViewProviderId()方法:将输入的ID入参,转化为Integer类型数据,然后赋值成为模型provider1的属性;

2、viewProvider()方法:将模型provider1 以及REST风格的url的参数进行入参,url的参数是:${provider1.id};拿到id后,进行查找;

3、这里面的一个疑惑是:已经成为model的模型provider1,在前端无法输出信息;而新加入的模型provider2可以,因此做个记号,后续改进。


【4】Service层

接口--Service/ProviderService.java:

package com.Provider.Service;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import com.Provider.entities.Provider;

public interface ProviderService {

	public Provider getProviderById(String id) throws SQLException, ParseException;
}


实现类--Service/ProviderServiceImpl.java:

package com.Provider.Service;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.Provider.Dao.ProviderDao;
import com.Provider.entities.Provider;

@Service("providerService")
public class ProviderServiceImpl implements ProviderService {
	@Autowired
	ProviderDao providerDao;
	
	@Override
	public Provider getProviderById(String id) throws SQLException, ParseException {
		System.out.println("ProviderServiceImpl-getProviderById");
		return providerDao.getProviderById(id);
	}
}


【5】Dao层

接口--Dao/ProviderDao.java:

package com.Provider.Dao;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import com.Provider.entities.Provider;

public interface ProviderDao {

	Provider getProviderById(String id) throws SQLException, ParseException;

}


实现类--Dao/ProviderDaoImpl.java:

package com.Provider.Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.Provider.entities.Provider;

@Component("providerDao")
public class ProviderDaoImpl implements ProviderDao {
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	private String sql;
	
	@Override
	public Provider getProviderById(String id) throws SQLException, ParseException {
		System.out.println("ProviderDaoImpl-getProviderById");
		Provider provider = new Provider();
		SimpleDateFormat createDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Logger log = Logger.getLogger(ProviderDaoImpl.class.getName());
		String sql = "select * from smbms_provider where id="+id+";";
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test";
		String providername = "root";
		String password = "";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,providername,password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		stmt = conn.createStatement();
		System.out.println("add - sql1: "+sql);
		ResultSet rs = stmt.executeQuery(sql);
		if(rs.next()){
			provider.setProAddress(rs.getString("proAddress"));
			provider.setCreationDate(createDateFormat.parse(rs.getString("creatiomDate")));
			provider.setCreateBy(rs.getInt("createdBy"));
			provider.setId(rs.getInt("id"));
			provider.setProPhone(rs.getString("proPhone"));
			provider.setProCode(rs.getString("proCode"));
			provider.setProName(rs.getString("proName"));
			provider.setProDesc(rs.getString("proDesc"));
			provider.setProFax(rs.getString("proFax"));
			provider.setPic_BusinessLic(rs.getString("pic_BusinessLic"));
			provider.setPic_OrgCodeCer(rs.getString("pic_OrgCodeCer"));
		}
		if(stmt!=null){
			stmt.close();
		}
		if(rs!=null){
			rs.close();
		}
		System.out.println("Dao-provider: "+provider.toString());
		return provider;
	}
	
}

【6】配置文件:

1. springmvc配置--/resources/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: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.0.xsd  
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
     <!--mvc静态资源访问   -->
	 <mvc:resources mapping="/statics/**" location="/statics/"/>
	
   	<!-- 一键式配置 -->
    <context:component-scan base-package="com.User.Controller"></context:component-scan>
    <context:component-scan base-package="com.Provider.Controller"></context:component-scan>  
    <context:component-scan base-package="com.User"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>  
  
    <!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->  
    <!--prefix 前缀+suffix 后缀  -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean> 
  	
  	<!-- 全局异常处理 -->
  	<!--  -->
  	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  		<property name="exceptionMappings">
  			<props>
  				<prop key="java.lang.RuntimeException">sys</prop>
  			</props>
  		</property>
  	</bean>
  	
  	<!-- 配置MultipartResolver -->
  	<bean id="multipartResolver" 
  	  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  	 	<property name="maxUploadSize" value="5000000"></property>
  	 	<property name="defaultEncoding" value="UTF-8"></property> 
  	 </bean>
  	 
</beans> 

2. spring配置文件 -- applicationContext-jdbc.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
	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.0.xsd
        	http://www.springframework.org/schema/aop
        	http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        ">
	<context:component-scan base-package="com.User.Dao"></context:component-scan>
	<context:component-scan base-package="com.User.Service"></context:component-scan>
	<context:component-scan base-package="com.Role.Dao"></context:component-scan>
	<context:component-scan base-package="com.Role.Service"></context:component-scan>
	<context:component-scan base-package="com.Provider.Dao"></context:component-scan>
	<context:component-scan base-package="com.Provider.Service"></context:component-scan>
</beans>


3. web.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns="http://java.sun.com/xml/ns/javaee"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    id="WebApp_ID" version="2.5">  
  
      <!-- 这个指定了log4j.xml放置的目录 -->
    <context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value> 
	</context-param>
	 <!-- 一定要加上这个listener -->
	<listener>  
	    <listener-class>  
	        org.springframework.web.util.Log4jConfigListener 
	    </listener-class>  
	</listener> 
  
    <!-- 配置 DispatcherServlet -->
    <servlet>  
        <servlet-name>springmvc</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>  
        <!--容器启动时就被加载了    -->  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>springmvc</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
       	
   	<filter>
		<filter-name>springUtf8Encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>springUtf8Encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

    <welcome-file-list>
    	<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
    </welcome-file-list>
    
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>
    <!-- 配置Spring的ContextLoaderListener监听器,初始化spring容器 -->
    <listener>
    	<listener-class>
    	 	org.springframework.web.context.ContextLoaderListener
    	</listener-class>
    </listener>

</web-app>  


【7】测试结果:

测试输入:


图5


打印日志:

UserServiceImpl-login
18/02/08 15:15:45 INFO Controller.UserController: UserDaoImpl.loginMatch
sql: select * from smbms_user where userName='mmb0889' and userPassword='scua';
8888
4
18/02/08 15:15:45 INFO Controller.UserController: 后台找一下有没有这个username和password: User [id=4, userCode=test01, userName=mmb0889, userPassword=scua, gender=2, birthdayString=null, birthday=1991-12-29, phone=0000, address=maoming, userRole=110, createdBy=1, creationDate=2017-12-17, creationDateString=null, modifyBy=null, modifyDate=null, modifyDateString=null, idPicPath=null, workPicPath=null, roleName=null]
18/02/08 15:15:45 INFO Controller.UserController: user.toString(): User [id=4, userCode=test01, userName=mmb0889, userPassword=scua, gender=2, birthdayString=null, birthday=1991-12-29, phone=0000, address=maoming, userRole=110, createdBy=1, creationDate=2017-12-17, creationDateString=null, modifyBy=null, modifyDate=null, modifyDateString=null, idPicPath=null, workPicPath=null, roleName=null]
18/02/08 15:15:45 INFO Controller.UserController: 刚刚存入了一个session对象:User [id=4, userCode=test01, userName=mmb0889, userPassword=scua, gender=2, birthdayString=null, birthday=1991-12-29, phone=0000, address=maoming, userRole=110, createdBy=1, creationDate=2017-12-17, creationDateString=null, modifyBy=null, modifyDate=null, modifyDateString=null, idPicPath=null, workPicPath=null, roleName=null]
ProviderController-ViewProviderId
provider1: Provider [id=2, proCode=null, proName=null, proDesc=null, proContact=null, proPhone=null, proFax=null, createBy=null, creationDate=null, modifyDate=null, modifyBy=null, pic_BusinessLic=null, pic_OrgCodeCer=null, proAddress=null]
ProviderController-viewProvider
view provider id =======2
ProviderServiceImpl-getProviderById
ProviderDaoImpl-getProviderById
add - sql1: select * from smbms_provider where id=2;
Dao-provider: Provider [id=2, proCode=0022, proName=TianMao, proDesc=NianHuo, proContact=null, proPhone=654321, proFax=0213-22, createBy=110, creationDate=Sun Dec 31 18:32:43 CST 2017, modifyDate=null, modifyBy=null, pic_BusinessLic=D:java_ee_eclipsemmb_workplace.metadata.pluginsorg.eclipse.wst.server.core	mp4wtpwebappsspringmvc5staticsuploadfilesProvider1518021733889_Personal.jpg, pic_OrgCodeCer=D:java_ee_eclipsemmb_workplace.metadata.pluginsorg.eclipse.wst.server.core	mp4wtpwebappsspringmvc5staticsuploadfilesProvider1518021937800_Personal.jpg, proAddress=TianHe]
provider1: Provider [id=2, proCode=0022, proName=TianMao, proDesc=NianHuo, proContact=null, proPhone=654321, proFax=0213-22, createBy=110, creationDate=Sun Dec 31 18:32:43 CST 2017, modifyDate=null, modifyBy=null, pic_BusinessLic=D:java_ee_eclipsemmb_workplace.metadata.pluginsorg.eclipse.wst.server.core	mp4wtpwebappsspringmvc5staticsuploadfilesProvider1518021733889_Personal.jpg, pic_OrgCodeCer=D:java_ee_eclipsemmb_workplace.metadata.pluginsorg.eclipse.wst.server.core	mp4wtpwebappsspringmvc5staticsuploadfilesProvider1518021937800_Personal.jpg, proAddress=TianHe]

显示结果:


图6



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值