SpringBoot web综合开发

一、web开发
spring boot web开发非常的简单,其中包括常用的json输出、filters、property、log等。

(1)json 接口开发

在以前的spring开发的时候需要我们提供json接口的时候需要做的配置。

1.添加 jackjson 等相关jar包
2.配置spring controller扫描
3.对接的方法添加@ResponseBody
在springboot中,只需要类添加 @RestController 即可,默认类中的方法都会以json的格式返回。

/**

  • 用户类

  • @author bigkunkun
    */
    @RestController
    public class UserController {

    @RequestMapping("/getUser")
    public User getUser() {
    User user=new User();
    user.setName(“小明”);
    user.setPassword(“123456”);
    return user;
    }
    }
    在这里插入图片描述
    如果我们需要使用页面开发只要使用 @Controller ,下面会结合模板来说明。
    (2)自定义Filter

    我们常常在项目中会使用filters用于录调用日志、排除有XSS威胁的字符、执行权限验证等等。Spring Boot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,并且我们可以自定义Filter。
    步骤:

实现Filter接口,实现Filter方法
添加@Configuration 注解,将自定义Filter加入过滤链
/**

  • SpringBoot 自定义过滤器
  • @author bigkunkun
    /
    @Configuration
    public class WebConfiguration {
    /
    *
    • Servlet过滤器集成“x - forwarding - for”和“x - forwarding - proto”HTTP头信息。
      这个Servlet过滤器的大部分设计是一个mod_remoteip端口,这个Servlet过滤器用代理或
      负载均衡器通过请求头提供的IP地址列表代替请求的客户端远程IP地址和主机名。
      (例如:“X-Forwarded-For”)。

    • @return
      /
      @Bean
      public RemoteIpFilter remoteIpFilter() {
      return new RemoteIpFilter();
      }
      /
      *

    • Servlet 3.0+容器中注册过滤器的ServletContextInitializer。

    • 与ServletContext提供的注册特性类似,但是采用了Spring Bean的设计。
      必须在调用RegistrationBean.onStartup(ServletContext)之前指定过滤器。
      注册可以与URL模式和/或servlet(通过名称或通过servletregistrationbean)相关联。
      当没有指定URL模式或servlet时,过滤器将关联到’/*’。如果未指定过滤器名称,将推断过滤器名称。

    • @return
      */
      @Bean
      public FilterRegistrationBean testFilterRegistration() {

      FilterRegistrationBean registration = new FilterRegistrationBean();
      // 设置要注册的过滤器
      registration.setFilter(new MyFilter());
      // 设置路径过滤模式
      registration.addUrlPatterns("/*");
      // 添加初始化参数
      registration.addInitParameter(“paramName”, “paramValue”);
      // 定义过滤器名称
      registration.setName(“MyFilter”);
      // 设置过滤器顺序
      registration.setOrder(1);
      return registration;
      }
      /**

    • 自定义Filter

    • @author bigkunkun
      */
      public class MyFilter implements Filter {

      @Override
      public void destroy() {
      // TODO Auto-generated method stub
      }

      @Override
      public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
      throws IOException, ServletException {
      // TODO Auto-generated method stub
      HttpServletRequest request = (HttpServletRequest) srequest;
      System.out.println(“this is MyFilter,url :” + request.getRequestURI());
      filterChain.doFilter(srequest, sresponse);
      }

      @Override
      public void init(FilterConfig arg0) throws ServletException {
      // TODO Auto-generated method stub
      }
      }
      }
      在这里插入图片描述
      (3)自定义Property

在eclipse中安装properties插件PropertiesEditor

在web开发的过程中,我经常需要自定义一些配置文件。配置在application.properties中。
在这里插入图片描述

测试代码

name=bingkunkun
blog=CSDN
获取方式:

通过@Value获取

@Value(" n a m e " ) p r i v a t e S t r i n g n a m e ; @ V a l u e ( " {name}") private String name; @Value(" name")privateStringname;@Value("{blog}")
private String blog;

@RequestMapping("/getProperties")
public String getProperties() {
    return "配置文件值为 name="+name+" blog="+blog;
}
发现中文乱码,在使用该类上标注@PropertySource解决乱码:

@PropertySource(value =“classpath:application.properties”, encoding = “utf-8”)
4)log配置

日志配置

logging.path=/user/local/log
logging.level.com.favorites=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR
二、数据库操作(jpa)
jpa是利用Hibernate生成各种自动化的sql,如果只是简单的增删改查,基本上不用手写了,spring内部已经帮大家封装实现了。
(1)添加maven依赖:

org.springframework.boot
spring-boot-starter-data-jpa


mysql
mysql-connector-java

(2)添加配置信息

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/first?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
# dialect 主要是指定生成表名的存储引擎为InneoDB 
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#  show-sql 是否打印出自动生产的SQL,方便调试的时候查看。
spring.jpa.show-sql= true

hibernate.hbm2ddl.auto参数的作用主要用于:自动创建|更新|验证数据库表结构,有四个值:
1.create: 每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
2.create-drop :每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
3.update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。
4.validate :每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
(3)编写实体类和Dao


/**
 * User实体类
 * @author bigkunkun
 */
@Entity
public class User implements Serializable {
 
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue
	private Long id;
	@Column(nullable = false, unique = true)
	private String userName;
	@Column(nullable = false)
	private String passWord;
	@Column(nullable = false, unique = true)
	private String email;
	@Column(nullable = true, unique = true)
	private String nickName;
	@Column(nullable = false)
	private String regTime;
    // 省略 get set
   }

注意:Entity中不映射成列的字段得加@Transient 注解,不加注解也会映射成列。
dao只要继承JpaRepository类就可以,它可以根据方法名来自动的生产SQL,比如findByUserName 会自动生产一个以 userName 为参数的查询方法,比如 findAlll 自动会查询表里面的所有数据,比如自动分页等等。


/**
 * Dao层
 * @author bigkunkun
public interface UserRepository extends JpaRepository<User, Long> {
    User findByUserName(String userName);
    User findByUserNameOrEmail(String username, String email);
    
}

(4)测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserRepositoryTest {
 
    @Autowired
    private UserRepository userRepository;
 
    @Test
    public void test() throws Exception {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);        
        String formattedDate = dateFormat.format(date);
         
        userRepository.save(new User("aa1", "aa@126.com", "aa", "aa123456",formattedDate));
        userRepository.save(new User("bb2", "bb@126.com", "bb", "bb123456",formattedDate));
        userRepository.save(new User("cc3", "cc@126.com", "cc", "cc123456",formattedDate));
 
        Assert.assertEquals(3, userRepository.findAll().size());
        Assert.assertEquals("bb123456", userRepository.findByUserNameOrEmail("bb2", "bb@126.com").getNickName());
        userRepository.delete(userRepository.findByUserName("aa1"));
    }
}
 

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值