SpringBoot Web应用

web开发

spring boot web开发包括常用的json输出、filters、property、log等

json 接口开发

在以前的spring 开发的时候需要我们提供json接口的时候需要做那些配置呢
1.添加 jackjson 等相关jar包
2.配置spring controller扫描
3.对接的方法添加@ResponseBody
就这样我们会经常由于配置错误,导致406错误等等,spring boot如何做呢,只需要类添加  @RestController  即可,默认类中的方法都会以json的格式返回
@RestController
public class HelloWorldController {
    @RequestMapping("/getUser")
    public User getUser() {
    	User user=new User();
    	user.setUserName("小明");
    	user.setPassWord("xxxx");
        return user;
    }
}
如果我们需要使用页面开发只要使用 @Controller ,下面会结合模板来说明

自定义Filter

我们常常在项目中会使用filters用于录调用日志、排除有XSS威胁的字符、执行权限验证等等。Spring Boot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,并且我们可以自定义Filter。
两个步骤:
1.实现Filter接口,实现Filter方法
2.添加@Configuration 注解,将自定义Filter加入过滤链
@Configuration
public class WebConfiguration {
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }
    
    @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;
    }
    
    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
		}
    }
}

自定义Property

在web开发的过程中,我经常需要自定义一些配置文件,如何使用呢
配置在application.properties中
title=java
description=java123

自定义配置类

@Component
public class PropertiesContant {
	@Value("${title}")
	private String title;
	@Value("${description}")
	private String description;
	
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
}

测试

System.out.println(status + ", " + content + ", " + propertiesContant.getTitle());

log配置

配置输出的地址和输出级别
application.properties
###日志
logging.path=/data/logs/tomcat/
logging.level.com.favorites=DEBUG
logging.level.org.springframework.web=INFO

数据库操作(jpa)

在这里我重点讲述mysql、spring data jpa的使用,其中mysql 就不用说了大家很熟悉,jpa是利用Hibernate生成各种自动化的sql,如果只是简单的增删改查,基本上不用手写了,spring内部已经帮大家封装实现了。

1、添加相jar包

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
     <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

2、添加配置文件

###mysql数据库
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.format_sql = true


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

dialect 主要是指定生成表名的存储引擎为InneoDB show-sql 是否打印出自动生产的SQL,方便调试的时候查看

3、添加实体类和Dao

@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)
    private int age;
	@Column(nullable = false, unique = true)
	private String email;
	@Column(nullable = true)
	private String nickName;
	@Column(nullable = true)
	private String regTime;
	
	public User(){}
	
	public User(String userName, String passWord, int age, String email, String nickName, String regTime) {
		super();
		this.userName = userName;
		this.passWord = passWord;
		this.age = age;
		this.email = email;
		this.nickName = nickName;
		this.regTime = regTime;
	}

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassWord() {
		return passWord;
	}
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getNickName() {
		return nickName;
	}
	public void setNickName(String nickName) {
		this.nickName = nickName;
	}
	public String getRegTime() {
		return regTime;
	}
	public void setRegTime(String regTime) {
		this.regTime = regTime;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", passWord=" + passWord + ", age=" + age + ", email=" + email + ", nickName=" + nickName + ", regTime=" + regTime + "]";
	}

}
dao只要继承JpaRepository类就可以,几乎可以不用写方法,还有一个特别有尿性的功能非常赞,就是可以根据方法名来自动的生产SQL,比如findByUserName 会自动生产一个以 userName 为参数的查询方法,比如 findAlll 自动会查询表里面的所有数据,比如自动分页等等。。
Entity中不映射成列的字段得加@Transient 注解,不加注解也会映射成列
public interface UserRepository extends JpaRepository<User, Long> {
    User findByUserName(String userName);
    User findByUserNameOrEmail(String username, String email);
}

4、测试

@EnableAutoConfiguration
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
public class SpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootDemoApplication.class, args);
	}
}

5、测试类

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserRepositoryTests {
	private static Logger log = LoggerFactory.getLogger(UserRepositoryTests.class);

	@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", "aa123456", 20, "aa@126.com", "aa",
		 formattedDate));
		 userRepository.save(new User("bb2", "bb123456", 21, "bb@126.com", "bb",
		 formattedDate));
		 userRepository.save(new User("cc3", "cc123456", 22, "cc@126.com",  "cc",
		 formattedDate));

		// 分页查询
//		int page = 1, size = 2;
//		Sort sort = new Sort(Direction.DESC, "id");
//
//		Pageable pageable = new PageRequest(page, size, sort);
//		List<User> users = userRepository.findALLPage(pageable);
//		
//		for (User user : users) {
//			log.info("=================== " + user.toString());
//		}
	}

6、注意:

1、字段属性添加,修改名称都会alter表,插入字段
2、修改数据类型,不会更新表
3、删除字段,不会更新表

thymeleaf模板

Thymeleaf 介绍

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
Thymeleaf是与众不同的,因为它使用了自然的模板技术。这意味着Thymeleaf的模板语法并不会破坏文档的结构,模板依旧是有效的XML文档。模板还可以用作工作原型,Thymeleaf会在运行期替换掉静态值。Velocity与FreeMarker则是连续的文本处理器。 下面的代码示例分别使用Velocity、FreeMarker与Thymeleaf打印出一条消息:
Thymeleaf: <p th:text="${message}">Hello World!</p>
** 注意,由于Thymeleaf使用了XML DOM解析器,因此它并不适合于处理大规模的XML文件。**

URL

URL在Web应用模板中占据着十分重要的地位,需要特别注意的是Thymeleaf对于URL的处理是通过语法@{…}来处理的。		Thymeleaf支持绝对路径URL:
<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>

if条件求值

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

for循环

<tr th:each="prod : ${prods}">
      <td th:text="${prod.name}">Onions</td>
      <td th:text="${prod.price}">2.41</td>
      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

页面即原型

在Web开发过程中一个绕不开的话题就是前端工程师与后端工程师的写作,在传统Java Web开发过程中,前端工程师和后端工程师一样,也需要安装一套完整的开发环境,然后各类Java IDE中修改模板、静态资源文件,启动/重启/重新加载应用服务器,刷新页面查看最终效果。
但实际上前端工程师的职责更多应该关注于页面本身而非后端,使用JSP,Velocity等传统的Java模板引擎很难做到这一点,因为它们必须在应用服务器中渲染完成后才能在浏览器中看到结果,而Thymeleaf从根本上颠覆了这一过程,通过属性进行模板渲染不会引入任何新的浏览器不能识别的标签,例如JSP中的,不会在Tag内部写表达式。整个页面直接作为HTML文件用浏览器打开,几乎就可以看到最终的效果,这大大解放了前端工程师的生产力,它们的最终交付物就是纯的HTML/CSS/JavaScript文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值