spring+maven+freemarker+servlet项目连接数据库


pom.xml依赖的jar包


	
	
		org.springframework
		spring-context
		4.3.12.RELEASE
	
	
	
		org.springframework
		spring-jdbc
		4.3.12.RELEASE
	
	
	
		org.springframework
		spring-web
		4.3.12.RELEASE
	
	
	
		mysql
		mysql-connector-java
		5.1.26
	
	
	
		org.freemarker
		freemarker
		2.3.23
	
	
	
		jstl
		jstl
		1.2
	
	
		taglibs
		standard
		1.1.2
	

spring.xml文件配置

扫描注解

读取properties文件

在web.xml配置以下内容



  spring_web
  
  
    contextConfigLocation
    classpath:spring.xml
  
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  
    freemarker
    freemarker.ext.servlet.FreemarkerServlet
    
      TemplatePath
      /
    
    
      NoCache
      true
    
    
      ContentType
      text/html;UTF-8
    
    
      template_update_delay
      0
    
    
      default_encoding
      UTF-8
    
    
      number_format
      0.##
    
    1
  
  
    freemarker
    *.ftl
  
  
  
    
    NewsController
    NewsController
    cn.et.web.controller.NewsController
  
  
    NewsController
    /NewsController
  
  
    
    AddService
    AddService
    cn.et.web.controller.AddService
  
  
    AddService
    /AddService
  

JdbcTemplate的实例(使用Java创建)

package cn.et.web.conf;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@Configuration
public class MyConf {
    @Value("${url}")
    private String url;
    @Value("${driverClass}")
    private String driverClassName;
    @Value("${username1}")
    private String userName;
    @Value("${password}")
    private String password;
    
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    
    @Bean
    public DataSource dataSouce(){
        DriverManagerDataSource dmds=new DriverManagerDataSource();
        dmds.setUrl(url);
        dmds.setDriverClassName(driverClassName);
        dmds.setUsername(userName);
        dmds.setPassword(password);
        return dmds;
    }
}


实例

package cn.et.web.entity;


public class CC {
    private String c1;
    private String c2;
    public String getC1() {
        return c1;
    }
    public void setC1(String c1) {
        this.c1 = c1;
    }
    public String getC2() {
        return c2;
    }
    public void setC2(String c2) {
        this.c2 = c2;
    }
}




添加的servlet(调用service层)

package cn.et.web.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.et.web.service.NewsService;

/**
 * Servlet implementation class AddService
 */
public class AddService extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddService() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    WebApplicationContext ac=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        NewsService ns=(NewsService)ac.getBean("newsServiceImpl");
	    request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
	    String c1=request.getParameter("c1");
		String c2=request.getParameter("c2");
		request.setAttribute("c1", c1);
		request.setAttribute("c2", c2);
        ns.add(c1, c2);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

查询的servlet (调用service层)   servlet是由tomcat实例化的 tomcat不认识spring中的注解

package cn.et.web.controller;

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

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

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.et.web.entity.CC;
import cn.et.web.service.NewsService;

/**
 * Servlet implementation class NewsController
 */
public class NewsController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewsController() {
        super();
        // TODO Auto-generated constructor stub
    }

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		WebApplicationContext ac=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		NewsService ns=(NewsService)ac.getBean("newsServiceImpl");
		String name=request.getParameter("temp");
		if(name==null){
		    name="";
		}
		request.setAttribute("name", name);
		List queryNewsByContent = ns.queryNewsByContent(name);
		request.setAttribute("newsList", queryNewsByContent);
		request.getRequestDispatcher("/index.jsp").forward(request,response);
	
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

service层(调用到层)

package cn.et.web.service.impl;

import java.util.List;

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

import cn.et.web.dao.NewsDao;
import cn.et.web.entity.CC;
import cn.et.web.service.NewsService;
@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsDao dao;
    public List queryNewsByContent(String content) {
        if(content==null){
            content="";
        }
        return dao.queryNewsByContent(content);
    }
    
    public void add(String c1,String c2){
        if(c1==null){
            c1="";
        }
        if(c2==null){
            c2="";
        }
        
        dao.add(c1,c2);
    }
}

dao层

package cn.et.web.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import cn.et.web.dao.NewsDao;
import cn.et.web.entity.CC;
@Repository
public class NewsDaoImpl implements NewsDao {
    @Autowired
    private JdbcTemplate jdbc;
    //Map
    
    //查询
    public List queryNewsByContent(String content) {
        String sql="select * from cc where c1 like '%"+content+"%'";
        return jdbc.query(sql,new RowMapper(){

            public CC mapRow(ResultSet rs, int rowNum) throws SQLException {
                CC c=new CC();
               c.setC1(rs.getString("C1"));
               c.setC2(rs.getString("C2"));
               return c;
            }
        });
    }


    //新增
    public void add(String c1, String c2) {
       String sql="insert into cc (c1,c2) values('"+c1+"','"+c2+"')";
        jdbc.execute(sql);
    }
}

freemarker页面


新增 <#list newsList as temp> ${temp.c1} ${temp.c2}

增加的页面





Insert title here


	
请输入c1:
请输入c2:



你可能感兴趣的:(spring)