spring mvc 整合 jdbc 实现Web后端数据库

    xiaoxiao2021-03-25  138

    本项目是在原来无数据库的版本上,整合Spring mvc和jdbc,来实现Web后端数据库的;

    1.首先要在pom.xml中为项目添加需要的依赖,主要为:

    <dependencies>

    <!--shiro 认证模块--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.3</version> </dependency> <!--jdbc驱动 用于shiro 的realm认证域--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <!-- utils -->     <dependency>             <groupId>com.google.guava</groupId>             <artifactId>guava</artifactId>             <version>18.0</version>     </dependency> </dependencies>

    其中shiro的认证模块可以暂时不用管,这是后面添加用户权限要用到的。

    2.添加资源文件,这里主要是本机mysql数据访问权限信息文件:

    其中,restaurant 是我们要创建的数据库的名称;user = root 表明我们的mysql用户名为root,密码是root;

    3.实现一个启动类,完成配置,注意:这部分工作其实也可以交给web.xml来完成,个人觉得使用启动类来配置更加好理解一点:

    import javax.servlet.Filter; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; public class SpringServletInitializer  extends AbstractDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public static AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();        public SpringServletInitializer() {           super();        }           @Override protected WebApplicationContext createServletApplicationContext() { context.register(SpringWebConfig.class); return context; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected WebApplicationContext createRootApplicationContext() { return null; } @Override protected Filter[] getServletFilters() {     final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();    encodingFilter.setEncoding(CHARACTER_ENCODING);     encodingFilter.setForceEncoding(true);     return new Filter[] { encodingFilter }; } }

    4.接下来,我们需要定义实体类了,我们需要三个实体类,客户,订单,还有菜品,这里以客户类为例,其他类似:

    import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Customer implements Serializable {

    private static final long serialVersionUID = 1L;     @Id    @Column(name = "customer_name")     private String name = null;   @Column(name="password")    private String password = null;    public Customer() {         super();     }   public Customer(String name, String password) {      this.name = name;      this.password = password;     }     public String getName() {         return this.name;     }

        public void setName(final String name) {         this.name = name;     }          public String getPassword() {         return this.password;     }

        public void setPassword(final String password) {         this.password = password;     } }

    5.定义好实体类,就可以使用JdbcTemplate为连接到数据库并提供统一的数据访问接口了,由于使用spring框架,我们要使用接口的形式来注入该接口的实例,为了规范,我们的命名以Dao以及 DaoImpl结尾,这里还是以客户类为例:

    接口“dao”:

    import java.util.List; import com.team.restaurant_second.persistence.entity.Customer; public interface CustomerDao { List<Customer> findAll(); Customer findOne(String name); void create(Customer entity); }

    实现:

    import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource;

    import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository;

    import com.team.restaurant_second.persistence.entity.Customer; @Repository public class CustomerDaoImpl implements CustomerDao { private JdbcTemplate jdbcTemplate; @Autowired     public void setDataSource(DataSource dataSource) {         this.jdbcTemplate = new JdbcTemplate(dataSource);     } public List<Customer> findAll() { List<Customer> customers = this.jdbcTemplate.query("select * from Customer", new CustomerMapper());     return customers; } public Customer findOne(String name) { List<Customer> customers = this.jdbcTemplate.query("select * from Customer where customer_name=" + name, new CustomerMapper());     if (customers.isEmpty()) return null;     return customers.get(0); } public void create(Customer entity) { final String INSERT_SQL = "insert into Customer (customer_name,password) values(?,?)";     final Customer temp = entity;     KeyHolder keyHolder = new GeneratedKeyHolder(); this.jdbcTemplate.update(    new PreparedStatementCreator() {        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {            PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[] {"customer_name"});            ps.setString(1, temp.getName());            ps.setString(2, temp.getPassword());            return ps;        }    },    keyHolder); } public static final class CustomerMapper implements RowMapper<Customer> { public Customer mapRow(ResultSet rs, int rowNum) throws SQLException { // TODO Auto-generated method stub Customer customer = new Customer(); customer.setName(rs.getString("customer_name")); customer.setPassword(rs.getString("password")); return customer; }         } }

    6.到这里,我们其实就已经完成对数据库访问的封装,并提供访问接口,接下来,就可以来写服务类了,其实也就是调用前面提供的访问接口,实现数据存取的封装,提供友好的接口:

    import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.team.restaurant_second.persistence.dao.CustomerDao; import com.team.restaurant_second.persistence.entity.Customer; @Service @Transactional public class CustomerService { @Autowired private CustomerDao dao;          public CustomerService() {         super();     }          public void create(final Customer entity) {         dao.create(entity);     }          public List<Customer> findAll() {         return dao.findAll();     }     public Customer findByName(final String name) {         return dao.findOne(name);     }      }

    注意:这里的元注解@Autowired非常重要,它起到注入接口类对应的实例的作用!

    7.最后,就是完成控制器了,以登录为例:

    import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.team.restaurant_second.persistence.entity.Customer; import com.team.restaurant_second.persistence.service.CustomerService; @Controller public class LoginController { @Autowired private CustomerService customerService; @RequestMapping(value = "/login", method = RequestMethod.POST)  public String login(@ModelAttribute("customer")Customer customer) { try { customerService.create(customer); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return "login"; } @RequestMapping(value = "/login")     public String startLogin(@ModelAttribute("customer")Customer customer) { return "login";     } }

    8.进行测试如下:

    1)注册后可以在mysql数据库中看到注册用户:

    2)运行并登录:

    我们将登录时的用户名和密码打印到了控制台,可以看到,控制台信息如下:

    成功登录!!

    转载请注明原文地址: https://ju.6miu.com/read-2712.html

    最新回复(0)