onsubmit 属性在提交表单时触发。
onsubmit 属性只在
<form action="/demo/demo_form.asp" onsubmit="checkForm()"> 姓:<input type="text" name="lname"><br> 名:<input type="text" name="fname"><br> <input type="submit" value="提交"> <script> function checkForm() { alert("表单已提交!"); } </script>
在跳转链接前,需要判断该用户是否有权限打开页面,没有权限的弹出一个确认框提示“没有权限”,有权限的则直接跳转页面。
参考资料一: http://jingyan.baidu.com/article/425e69e6d043bebe15fc16db.html a标签点击时跳出确认框 方法一: <a href="http://www.baidu.com" onClick="return confirm('确定删除?');">[删除]</a> 方法二: <a onclick="confirm(‘确定要跳转吗?')?location.href='www.baidu.com':''" href="javascript:;">百度</a> 参考资料二: http://blog.csdn.net/wujiangwei567/article/details/40352689 ①在html标签中出现提示 <a href="http://www.baidu.com" onclick="if(confirm('确认百度吗?')==false)return false;">百度</a> ②在js函数中调用 function foo(){ if(confirm("确认百度吗?")){ return true; } return false; } 对应的标签改为: <a href="http://www.baidu.com" onclick="return foo();">百度</a> 注意事项: 以上参考资料总结: 1.跳转的方法: 1>. 把连接放在a元素的href属性中进行页面跳转 2>. 使用location.href进行页面跳转
参考资料一: http://jingyan.baidu.com/article/425e69e6d043bebe15fc16db.html
a标签点击时跳出确认框 方法一:
<a href="http://www.baidu.com" onClick="return confirm('确定删除?');">[删除]</a>
方法二:
<a onclick="confirm(‘确定要跳转吗?')?location.href='www.baidu.com':''" href="javascript:;">百度</a>
参考资料二: http://blog.csdn.net/wujiangwei567/article/details/40352689
①在html标签中出现提示
<a href="http://www.baidu.com" onclick="if(confirm('确认百度吗?')==false)return false;">百度</a>
②在js函数中调用
function foo(){ if(confirm("确认百度吗?")){ return true; } return false; }
对应的标签改为:
<a href="http://www.baidu.com" onclick="return foo();">百度</a>
注意事项:
以上参考资料总结:
1.跳转的方法:
1>. 把连接放在a元素的href属性中进行页面跳转
2>. 使用location.href进行页面跳转
字符串与域中的字符串是否相等
1、<c:if test="${student.sex eq '男'}我是空格"></c:if>,注意是${student.sex eq '男'}后面的空格 2、<c:if test="${student.sex eq '男'}"></c:if> 注意不要有多余的空格,判断相等用eq关键字
1、<c:if test="${student.sex eq '男'}我是空格"></c:if>,注意是${student.sex eq '男'}后面的空格
2、<c:if test="${student.sex eq '男'}"></c:if>
注意不要有多余的空格,判断相等用eq关键字
@PostMapping("/editStudent") public String editStudentUI(@Valid @ModelAttribute Student student , BindingResult result, Model model){ if (!bindResult(result, model)){ return "error"; } try { studentServiceImpl.update(student); } catch (Exception e) { e.printStackTrace(); } return "redirect:/admin/showStudent"; } public boolean bindResult(BindingResult result, Model model){ if (result.hasErrors()){ List<String> errors=new ArrayList<>(); List<ObjectError> errorList = result.getAllErrors(); for(ObjectError error : errorList){ errors.add(error.getDefaultMessage()); } model.addAttribute("error",errors); return false; } else{ return true; } }
package com.system.pojo.base; import org.hibernate.validator.constraints.NotBlank; import org.springframework.format.annotation.DateTimeFormat; import javax.validation.constraints.NotNull; import java.util.Date; public class Student { private Integer userid; @NotBlank(message = "姓名不能为空") private String username; private String sex; private Date birthyear; private Date grade; private Integer collegeid; public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex == null ? null : sex.trim(); } public Date getBirthyear() { return birthyear; } public void setBirthyear(Date birthyear) { this.birthyear = birthyear; } public Date getGrade() { return grade; } public void setGrade(Date grade) { this.grade = grade; } public Integer getCollegeid() { return collegeid; } public void setCollegeid(Integer collegeid) { this.collegeid = collegeid; } @Override public String toString() { return "Student{" + "userid=" + userid + ", username='" + username + '\'' + ", sex='" + sex + '\'' + ", birthyear=" + birthyear + ", grade=" + grade + ", collegeid=" + collegeid + '}'; } }
参数: url: 请求地址 type: 请求方式 (默认是get请求) headers: data: 待发送的参数数据key/value success:成功之后的回调函数 dataType: 将服务器端返回的数据转成指定类型("xml","json","text","html","jsonp"...)
参数:
url: 请求地址
type: 请求方式 (默认是get请求)
headers:
data: 待发送的参数数据key/value
success:成功之后的回调函数
dataType: 将服务器端返回的数据转成指定类型("xml","json","text","html","jsonp"...)
$.post
Shiro的常用注解 @RequiresPermissions :要求当前Subject在执行被注解的方法时具备一个或多个对应的权限。 @RequiresRoles("xxx") :要求当前Subject在执行被注解的方法时具备所有的角色,否则将抛出AuthorizationException异常。 @RequiresAuthentication:要求在访问或调用被注解的类/实例/方法时,Subject在当前的session中已经被验证。
Shiro的常用注解
@RequiresPermissions :要求当前Subject在执行被注解的方法时具备一个或多个对应的权限。 @RequiresRoles("xxx") :要求当前Subject在执行被注解的方法时具备所有的角色,否则将抛出AuthorizationException异常。 @RequiresAuthentication:要求在访问或调用被注解的类/实例/方法时,Subject在当前的session中已经被验证。
需要在jsp页面中引入标签 <%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %> 标签: shiro:authenticated 认证且不是记住我 shiro:notAuthenticated 未身份认证,包括记住我自动登录 shiro:guest 用户没有认证在没有RememberMe时 shiro:user 用户认证且在RememberMe时 <shiro:hasAnyRoles name="abc,123" > 在有abc或者123角色时 <shiro:hasRole name="abc"> 拥有角色abc <shiro:lacksRole name="abc"> 没有角色abc <shiro:hasPermission name="abc"> 拥有权限资源abc <shiro:lacksPermission name="abc"> 没有abc权限资源 shiro:principal 显示用户身份名称 <shiro:principal property="username"/> 显示用户身份中的属性值
Subject:相当于用户 SecurityManager:相当于DispatcherServlet Realm:相等于DataSource
Subject:相当于用户
SecurityManager:相当于DispatcherServlet
Realm:相等于DataSource
导入依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.3</version> </dependency> .... //– shiro-all-1.3.2.jar //– log4j-1.2.15.jar //– slf4j-api-1.6.1.jar //– slf4j-log4j12-1.6.1.jar
web.xml
<!-- name要和 applicationContext.xml中的对应的bean的id一致 --> <!--Shiro拦截器 shiro入口--> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 --> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
配置文件
URL 权限采取第一次匹配优先的方式
<?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" 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.xsd "> <!--配置自定义realm类--> <!-- <bean id="myRealm" class="com.system.realm.MyRealm"> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="MD5"></property> <property name="hashIterations" value="1024"></property> </bean> </property> </bean>--> <context:component-scan base-package="com.system.realm" /> <!--安全管理器--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm"/> </bean> <!--与web.xml中过滤器名称一致--> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,这个属性是必须的 --> <property name="securityManager" ref="securityManager"/> <!-- 身份认证失败,则跳转到登录页面的配置 --> <!-- 要求登录时的链接(登录页面地址),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 --> <!--<property name="loginUrl" value="/login.jsp"/> <property name="successUrl" value="/index.jsp"/>--> <!-- 权限认证失败,则跳转到指定页面 --> <!--<property name="unauthorizedUrl" value="/login.htmls"/>--> <!-- Shiro连接约束配置,即过滤链的定义 --> <property name="filterChainDefinitions"> <value> <!--anon 表示匿名访问,不需要认证以及授权--> <!--authc表示需要认证 没有进行身份认证是不能进行访问的--> <!--当访问login时,不用进行认证--> /login = anon <!--配置静态资源可以匿名访问--> /css/** = anon /dist/** = anon /js/** = anon /fonts/** = anon /admin/** = authc,roles[admin] /teacher/** = authc,roles[teacher] /student/** = authc,roles[student] /logout = logout <!--只有登陆界面可以匿名访问,其他路径都需要登录认证才能访问,没有登陆访问其他路径回跳转登陆页面--> /**=authc </value> </property> </bean> <!-- 生命周期 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <!-- 启用shiro注解 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> </beans>
自定义realm
package com.system.realm; import com.system.pojo.base.Role; import com.system.pojo.base.User; import com.system.service.RoleService; import com.system.service.UserLoginService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashSet; import java.util.Set; /** * @Description: 自定义的Realm * @Date 2020/3/21 **/ @Component public class MyRealm extends AuthorizingRealm { @Autowired private UserLoginService userLoginServiceImpl; @Autowired private RoleService roleServiceImpl; /** * @Description: 权限验证,获取身份信息 * @Param0: principalCollection * @Return: org.apache.shiro.authz.AuthorizationInfo **/ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //1、获取当前用户名 String username = (String) getAvailablePrincipal(principalCollection); Role role = null; //2、通过当前用户名从数据库中获取用户信息 try { User user = userLoginServiceImpl.findByName(username); //3、获取角色信息 role=roleServiceImpl.findById(user.getRole()); } catch (Exception e) { e.printStackTrace(); } //4、为当前用户设置角色和权限 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //用来存放角色码的集合 Set<String> r = new HashSet<String>(); if (role != null) { r.add(role.getRolename()); //5、把用户角色码交给shiro info.setRoles(r); } return info; } /** * @Description: 身份验证,login时调用 * @Param0: authenticationToken * @Return: org.apache.shiro.authc.AuthenticationInfo **/ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //用户名 String username = (String) token.getPrincipal(); //密码 String password = new String((char[])token.getCredentials()); //获取用户信息 User user=null; try { user = userLoginServiceImpl.findByName(username); } catch (Exception e) { e.printStackTrace(); } // if (user == null) { //没有该用户名 throw new UnknownAccountException(); } else if (!password.equals(user.getPassword())) { //密码错误 throw new IncorrectCredentialsException(); } /* ByteSource salt = ByteSource.Util.bytes(user.getSalt());//盐值 SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassWord(),salt,getName());*/ SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName()); return authenticationInfo; } }
controller中身份验证
controller中获取登录信息
controller中获取授权信息
controller代码实例:
@RequestMapping(value = "/login", method = {RequestMethod.POST}) public String login(User user,Model model) throws Exception{ UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword()); //应用代码直接交互的对象是 Subject,Subject 代表了当前“用户” Subject subject = SecurityUtils.getSubject(); subject.login(token); //如果获取不到用户名就是登录失败,但登录失败的话,会直接抛出异常 if (subject.hasRole("admin")) { return "redirect:/admin/showStudent"; } else if (subject.hasRole("teacher")) { return "redirect:/teacher/showCourse"; } else if (subject.hasRole("student")) { return "redirect:/student/showCourse"; } return "redirect:/login"; }
//获取登录者信息 public User getUserInfo(){ Subject subject = SecurityUtils.getSubject(); String username= (String) subject.getPrincipal(); User user=null; try { user= userLoginServiceImpl.findByName(username); } catch (Exception e) { e.printStackTrace(); } return user; }
在 pojo 类的 日期字段 上,添加注解 @DateTimeFormat(pattern="yyyy/MM/dd") 根据自己情况,写具体的日期格式; 上面的仅仅对一个 po 类有效,如果你有很多 pojo 类,都有日期,则直接写一个日期转换类,然后注册到 springMvc 的配置文件里面,一劳永逸 ; 转换类如下:
在 pojo 类的 日期字段 上,添加注解 @DateTimeFormat(pattern="yyyy/MM/dd") 根据自己情况,写具体的日期格式;
pojo
@DateTimeFormat(pattern="yyyy/MM/dd")
上面的仅仅对一个 po 类有效,如果你有很多 pojo 类,都有日期,则直接写一个日期转换类,然后注册到 springMvc 的配置文件里面,一劳永逸 ;
po
springMvc
转换类如下:
import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 完成日期绑定,全局的 ,替换掉 @DateTimeFormat(pattern = "yyyy/MM/dd") */ public class DateConverter implements Converter<String, Date> { /** * 日期转换类 */ private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); @Override public Date convert(String source) { try { return simpleDateFormat.parse(source); } catch (ParseException e) { e.printStackTrace(); } // 转换失败,就返回 null ; return null; } }
注册到配置文件中
<!--配置 自定义 参数绑定(日期转换)--> <bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean" id="conversionService"> <!--写上自定义的转换器--> <property name="converters"> <list> <!--日期 转换 --> <bean class="cn.hyc.utils.DateConverter"/> </list> </property> </bean> <!--添加到 MVC 注解里面--> <mvc:annotation-driven validator="validator" conversion-service="conversionService">
在使用 @Request 进行 JSON 数据参数绑定的时候,对日期,需要另作操作; 否则就会报 400 bad request,请求也不会进后台方法; 在 pojo 类的 日期字段的get方法 上 添加 @JsonFormat(pattern="yyyy/MM/dd") ;
在使用 @Request 进行 JSON 数据参数绑定的时候,对日期,需要另作操作;
否则就会报 400 bad request,请求也不会进后台方法;
400 bad request
在 pojo 类的 日期字段的get方法 上 添加 @JsonFormat(pattern="yyyy/MM/dd") ;
get
@JsonFormat(pattern="yyyy/MM/dd")
解决输出JSON乱码的问题 我们发现即使,我们在 web.xml 中配置了解决乱码的拦截器,但是输出JSON 到前台的时候,JSON 中的中文还会乱码 ; 这与我们配置的过滤器无关了,我 猜测 是在JSON转换器内部,它默认了ISO-8859编码,导致过滤器在拿到数据的时候,就已经是乱码的数据了。它再使用UTF8编码,最终也还是乱码,除非它能智能的先ISO-8859解码,再UTF8编码。 为了解决这个问题,我们需要在springMvc.xml 中的 MVC 注解标签中配置JSON转换器,制定编码为UTF8;
解决输出JSON乱码的问题
我们发现即使,我们在 web.xml 中配置了解决乱码的拦截器,但是输出JSON 到前台的时候,JSON 中的中文还会乱码 ;
JSON
这与我们配置的过滤器无关了,我 猜测 是在JSON转换器内部,它默认了ISO-8859编码,导致过滤器在拿到数据的时候,就已经是乱码的数据了。它再使用UTF8编码,最终也还是乱码,除非它能智能的先ISO-8859解码,再UTF8编码。
ISO-8859
UTF8
为了解决这个问题,我们需要在springMvc.xml 中的 MVC 注解标签中配置JSON转换器,制定编码为UTF8;
springMvc.xml
MVC
<mvc:annotation-driven validator="validator" conversion-service="conversionService"> <mvc:message-converters> <!-- 处理请求返回json字符串的中文乱码问题 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven>
注意哦,对日期进行绑定的时候,JSON是在 字段 get 方法上添加注解,表单是在 字段 上添加注解!
字段 get 方法
字段
上面的方法,都是前台传来 JSON ,然后转成对象,指定 JSON 中的日期格式,以便正确的转换日期对象;
如果反过来呢,对象转成JSON,直接转换的话 date 类型,就会被转成 183138913131 这样long 类型的一串数字,我们也可以指定转成 JSON 串中 date 的格式:@JSONField(format = "yyyy-MM-dd")
date
183138913131
long
@JSONField(format = "yyyy-MM-dd")
/** * JSON -> 对象,指定JSON 中日期格式,以便转成对象 */ @DateTimeFormat(pattern = "yyyy/MM/dd") /** * 对象 -》 JSON 指定转换以后的字符串中日期对象的格式 */ @JSONField(format = "yyyy-MM-dd") private Date newsTime;
需要指定为:reset 。默认submit
controller跳转
redirect:/xxx 跳转到根路径下/**,(如果根路径为/,则跳转之后路径为localhost/xxx redirect:xxx 跳转到同级路径请求、即:在同一个controller里面跳转(假设:不同的controller类有不同的请求映射注解@RequestMapping("/abc")....,跳转之后路径localhost/abc/xxx,不能实现controller之间的跳转,因为controller类请求路径(abc)不同 forward:同redirect
/**
页面跳转
先配置视图解析器: <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--拼接视图地址的前缀和后缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> return "(想要跳转jsp路径)xxx" 跳转路径:localhost/xxx 如:return "student/showCourse"; 前面没有斜杠,视图解析器里面已经加了 实际jsp所在 D:\ideaFiles\Examination\src\main\webapp\WEB-INF\jsp\student\showCourse.jsp
先配置视图解析器:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--拼接视图地址的前缀和后缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
return "(想要跳转jsp路径)xxx"
跳转路径:localhost/xxx
如:return "student/showCourse"; 前面没有斜杠,视图解析器里面已经加了
实际jsp所在 D:\ideaFiles\Examination\src\main\webapp\WEB-INF\jsp\student\showCourse.jsp
依赖
<!-- MyBatis分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency>
配置(5.x.x版本)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- config params as the following --> <property name="helperDialect" value="mysql"/> </plugin> </plugins> </configuration>
实现,sql语句不用更改
public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) { // 1.调用PageHelper的静态方法开启分页功能 // 这里充分体现了PageHelper的“非侵入式”设计:原本要做的查询不必有任何修改 PageHelper.startPage(pageNum, pageSize); // 2.执行查询 List<Admin> list = adminMapper.selectAdminByKeyword(keyword); // 3.封装到PageInfo对象中 PageInfo<Admin> adminPageInfo = new PageInfo<>(list); return adminPageInfo; }
controller条用service返回pageinfo对象,存储到model中