寫ssm項目的注意點


注意事項:

輸出台亂碼

1587649720639

a鏈接以post提交

1587631225911

表單提交前驗證

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進行頁面跳轉

c:if 判斷

字符串與域中的字符串是否相等

1、<c:if test="${student.sex eq '男'}我是空格"></c:if>,注意是${student.sex eq '男'}后面的空格

2、<c:if test="${student.sex eq '男'}"></c:if>

注意不要有多余的空格,判斷相等用eq關鍵字

jsr303驗證表單

@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 +
                '}';
    }
}

Ajax

參數:

​ url: 請求地址

​ type: 請求方式 (默認是get請求)

​ headers:

​ data: 待發送的參數數據key/value

​ success:成功之后的回調函數

​ dataType: 將服務器端返回的數據轉成指定類型("xml","json","text","html","jsonp"...)

$.post

shiro

shiro注解

Shiro的常用注解

@RequiresPermissions :要求當前Subject在執行被注解的方法時具備一個或多個對應的權限。
@RequiresRoles("xxx") :要求當前Subject在執行被注解的方法時具備所有的角色,否則將拋出AuthorizationException異常。
@RequiresAuthentication:要求在訪問或調用被注解的類/實例/方法時,Subject在當前的session中已經被驗證。

1584880103271

jsp中Shiro使用的標簽

需要在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"/> 顯示用戶身份中的屬性值

shiro使用

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>
    
  • 配置文件

    1. 配置自定義的realm類、(或者自動掃描)--》創建realm對象,如:myRealm
    2. 配置DefaultWebSecurityManager,需要用到realm對象--》創建DefaultWebSecurityManager,如:securityManager
    3. 配置ShiroFilterFactoryBean,需要用到DefaultWebSecurityManager對象---》創建ShiroFilterFactoryBean,如:shiroFilter(與web.xml中過濾器名字配置的一致)

    URL 權限采取第一次匹配優先的方式

    1584878199086
    <?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中身份驗證

    1. 封裝用戶名,密碼
    2. 調用Subject.login方法進行登錄,不匹配會出現 AuthenticationException 異常
    3. 自定義的realm類,重寫doGetAuthenticationInfo() 方法
  • controller中獲取登錄信息

    1. SecurityUtils.getSubject()獲取subject
    2. subject.getPrincipal()
  • controller中獲取授權信息

    1. subject.hasRole("xxx"),角色碼集合中的值
    2. 或者subject.isPermitted()
  • 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 的配置文件里面,一勞永逸 ;

轉換類如下:

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")

json亂碼

解決輸出JSON亂碼的問題

我們發現即使,我們在 web.xml 中配置了解決亂碼的攔截器,但是輸出JSON 到前台的時候,JSON 中的中文還會亂碼 ;

這與我們配置的過濾器無關了,我 猜測 是在JSON轉換器內部,它默認了ISO-8859編碼,導致過濾器在拿到數據的時候,就已經是亂碼的數據了。它再使用UTF8編碼,最終也還是亂碼,除非它能智能的先ISO-8859解碼,再UTF8編碼。

為了解決這個問題,我們需要在springMvc.xml 中的 MVC 注解標簽中配置JSON轉換器,制定編碼為UTF8

<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 方法上添加注解,表單是在 字段 上添加注解!

上面的方法,都是前台傳來 JSON ,然后轉成對象,指定 JSON 中的日期格式,以便正確的轉換日期對象;

如果反過來呢,對象轉成JSON,直接轉換的話 date 類型,就會被轉成 183138913131 這樣long 類型的一串數字,我們也可以指定轉成 JSON 串中 date 的格式:@JSONField(format = "yyyy-MM-dd")

  /**
     * JSON -> 對象,指定JSON 中日期格式,以便轉成對象
     */
    @DateTimeFormat(pattern = "yyyy/MM/dd")
    /**
     * 對象 -》 JSON 指定轉換以后的字符串中日期對象的格式
     */
    @JSONField(format = "yyyy-MM-dd")
    private Date newsTime;

重置按鈕

需要指定為:reset 。默認submit

1584875121755

路徑跳轉問題:

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

PageHelper使用

  1. 依賴

     <!-- MyBatis分頁插件 -->
     <dependency>
         <groupId>com.github.pagehelper</groupId>
         <artifactId>pagehelper</artifactId>
         <version>5.1.2</version>
     </dependency>
    
  2. 配置(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>
    
  3. 實現,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中


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM